summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--org.tizen.common.connection/META-INF/MANIFEST.MF9
-rw-r--r--org.tizen.common.connection/OSGI-INF/l10n/bundle.properties27
-rw-r--r--org.tizen.common.connection/build.properties4
-rw-r--r--org.tizen.common.connection/icons/Emulator_stop.gifbin1023 -> 0 bytes
-rw-r--r--org.tizen.common.connection/icons/connection_explorer.gif (renamed from org.tizen.common.connection/icons/Connection Explorer.gif)bin1035 -> 1035 bytes
-rw-r--r--org.tizen.common.connection/icons/emulator_manager.gif (renamed from org.tizen.common.connection/icons/Emulator_start.gif)bin614 -> 614 bytes
-rw-r--r--org.tizen.common.connection/icons/log/add_tab.png (renamed from org.tizen.common.connection/icons/log/Add tab.png)bin3228 -> 3228 bytes
-rw-r--r--org.tizen.common.connection/icons/log/clear_log.png (renamed from org.tizen.common.connection/icons/log/Clear Log.png)bin3225 -> 3225 bytes
-rw-r--r--org.tizen.common.connection/icons/log/edit_tab.png (renamed from org.tizen.common.connection/icons/log/Edit tab.png)bin3214 -> 3214 bytes
-rw-r--r--org.tizen.common.connection/icons/log/export_log.png (renamed from org.tizen.common.connection/icons/log/Export Log.png)bin3236 -> 3236 bytes
-rw-r--r--org.tizen.common.connection/icons/log/logview.gif (renamed from org.tizen.common.connection/icons/log/Log View.gif)bin388 -> 388 bytes
-rw-r--r--org.tizen.common.connection/icons/log/remove_tab.png (renamed from org.tizen.common.connection/icons/log/Remove tab.png)bin3348 -> 3348 bytes
-rw-r--r--org.tizen.common.connection/icons/log/scroll_lock.pngbin0 -> 731 bytes
-rw-r--r--org.tizen.common.connection/plugin.xml128
-rwxr-xr-x[-rw-r--r--]org.tizen.common.connection/src/org/tizen/common/connection/ConnectionPlugin.java435
-rw-r--r--org.tizen.common.connection/src/org/tizen/common/connection/ConnectionPluginSurrogate.java44
-rw-r--r--org.tizen.common.connection/src/org/tizen/common/connection/ddmuilib/FileDialogUtils.java250
-rw-r--r--org.tizen.common.connection/src/org/tizen/common/connection/debugtools/DebugTool.java175
-rwxr-xr-x[-rw-r--r--]org.tizen.common.connection/src/org/tizen/common/connection/debugtools/ToolsInstall.java630
-rw-r--r--org.tizen.common.connection/src/org/tizen/common/connection/debugtools/ToolsInstallMessages.properties8
-rw-r--r--org.tizen.common.connection/src/org/tizen/common/connection/explorer/ConnectionExplorerContentProvider.java199
-rwxr-xr-x[-rw-r--r--]org.tizen.common.connection/src/org/tizen/common/connection/explorer/ConnectionExplorerLabelProvider.java241
-rwxr-xr-x[-rw-r--r--]org.tizen.common.connection/src/org/tizen/common/connection/explorer/ConnectionExplorerPanel.java2216
-rwxr-xr-x[-rw-r--r--]org.tizen.common.connection/src/org/tizen/common/connection/explorer/Messages.java76
-rw-r--r--org.tizen.common.connection/src/org/tizen/common/connection/explorer/messages.properties15
-rwxr-xr-x[-rw-r--r--]org.tizen.common.connection/src/org/tizen/common/connection/log/AddViewDialog.java622
-rw-r--r--org.tizen.common.connection/src/org/tizen/common/connection/log/LogColors.java16
-rwxr-xr-x[-rw-r--r--]org.tizen.common.connection/src/org/tizen/common/connection/log/LogPanel.java1697
-rw-r--r--org.tizen.common.connection/src/org/tizen/common/connection/log/LogTab.java1605
-rw-r--r--org.tizen.common.connection/src/org/tizen/common/connection/log/LogUIMessages.properties14
-rwxr-xr-x[-rw-r--r--]org.tizen.common.connection/src/org/tizen/common/connection/properties/ConnectionExplorerPermissionPropertyPages.java12
-rw-r--r--org.tizen.common.connection/src/org/tizen/common/connection/sdblib/dnd/FileEntryDropAdapter.java29
-rwxr-xr-x[-rw-r--r--]org.tizen.common.connection/src/org/tizen/common/connection/ui/ConnectionExplorer.java837
-rw-r--r--org.tizen.common.connection/src/org/tizen/common/connection/ui/ConnectionUIMessages.java61
-rw-r--r--org.tizen.common.connection/src/org/tizen/common/connection/ui/ConnectionUIMessages.properties17
-rw-r--r--org.tizen.common.connection/src/org/tizen/common/connection/ui/LogView.java457
-rw-r--r--org.tizen.common.connection/src/org/tizen/common/connection/ui/TizenRemoteFileDialog.java147
-rwxr-xr-x[-rw-r--r--]org.tizen.common.connection/src/org/tizen/common/connection/ui/TizenRemoteFileLabelProvider.java3
-rw-r--r--org.tizen.common.externals/.classpath7
-rw-r--r--org.tizen.common.externals/.project28
-rw-r--r--org.tizen.common.externals/.settings/org.eclipse.jdt.core.prefs8
-rw-r--r--org.tizen.common.externals/META-INF/MANIFEST.MF42
-rw-r--r--org.tizen.common.externals/OSGI-INF/l10n/bundle.properties3
-rw-r--r--org.tizen.common.externals/about.html41
-rw-r--r--org.tizen.common.externals/about_files/LICENSE-2.0.htm191
-rw-r--r--org.tizen.common.externals/about_files/epl-v10.html261
-rw-r--r--org.tizen.common.externals/build.properties8
-rw-r--r--org.tizen.common.externals/resources/opal.properties35
-rw-r--r--org.tizen.common.externals/resources/opal_de_DE.properties35
-rw-r--r--org.tizen.common.externals/resources/opal_es_ES.properties35
-rw-r--r--org.tizen.common.externals/resources/opal_fr_FR.properties35
-rw-r--r--org.tizen.common.externals/resources/opal_it_IT.properties35
-rw-r--r--org.tizen.common.externals/resources/opal_pl_PL.properties35
-rw-r--r--org.tizen.common.externals/resources/opal_pt_BR.properties35
-rw-r--r--org.tizen.common.externals/resources/opal_zh_CN.properties35
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/OpalItem.java158
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/angles/AngleSlider.java246
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/brushedMetalComposite/BrushedMetalComposite.java378
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/checkBoxGroup/CheckBoxGroup.java323
-rwxr-xr-xorg.tizen.common.externals/src/org/mihalis/opal/columns/ColumnBrowserWidget.java785
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/columns/ColumnItem.java416
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/flatButton/FlatButton.java633
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/gradientComposite/GradientComposite.java154
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/header/Header.java529
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/heapManager/HeapManager.java297
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/horizontalSpinner/HorizontalSpinner.java947
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/imageSelector/ISItem.java114
-rwxr-xr-xorg.tizen.common.externals/src/org/mihalis/opal/imageSelector/ImageSelector.java615
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/infinitePanel/InfiniteProgressPanel.java604
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/itemSelector/DLItem.java105
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/itemSelector/DualList.java1265
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/launcher/LLabel.java277
-rwxr-xr-xorg.tizen.common.externals/src/org/mihalis/opal/launcher/Launcher.java428
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/launcher/LauncherItem.java32
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/login/LoginDialog.java511
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/login/LoginDialogVerifier.java29
-rwxr-xr-xorg.tizen.common.externals/src/org/mihalis/opal/multiChoice/MultiChoice.java1195
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/multiChoice/MultiChoiceSelectionListener.java56
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/notify/Notifier.java347
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/notify/NotifierColors.java34
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/notify/NotifierColorsFactory.java66
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/opalDialog/ChoiceItem.java56
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/opalDialog/ChoiceWidget.java301
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/opalDialog/Dialog.java480
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/opalDialog/DialogArea.java154
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/opalDialog/FooterArea.java531
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/opalDialog/MessageArea.java541
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/panels/BlurredPanel.java151
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/panels/DarkPanel.java144
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/PWContainer.java45
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/PWGroup.java169
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/PWRow.java142
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/PWRowGroup.java79
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/PWTab.java111
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/PWTabContainer.java228
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/PreferenceWindow.java306
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/ValueAndAssociatedWidgets.java79
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/enabler/EnabledIfEquals.java44
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/enabler/EnabledIfNotEquals.java44
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/enabler/EnabledIfTrue.java46
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/enabler/Enabler.java57
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWButton.java63
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWCheckbox.java76
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWChooser.java82
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWColorChooser.java133
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWCombo.java107
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWDirectoryChooser.java78
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWFileChooser.java75
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWFloatText.java114
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWFontChooser.java95
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWIntegerText.java84
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWLabel.java81
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWPasswordText.java69
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWRadio.java98
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWScale.java91
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWSeparator.java78
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWSpinner.java86
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWStringText.java68
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWText.java74
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWTextarea.java77
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWURLText.java98
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWWidget.java264
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/promptSupport/BaseFocusControlListener.java169
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/promptSupport/CComboFocusControlListener.java68
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/promptSupport/ComboFocusControlListener.java73
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/promptSupport/FocusControlListenerFactory.java49
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/promptSupport/PromptSupport.java230
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/promptSupport/StyledTextFocusControlListener.java76
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/promptSupport/TextFocusControlListener.java75
-rwxr-xr-xorg.tizen.common.externals/src/org/mihalis/opal/rangeSlider/RangeSlider.java1060
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/switchButton/SwitchButton.java938
-rwxr-xr-xorg.tizen.common.externals/src/org/mihalis/opal/textAssist/TextAssist.java694
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/textAssist/TextAssistContentProvider.java46
-rwxr-xr-xorg.tizen.common.externals/src/org/mihalis/opal/tipOfTheDay/TipOfTheDay.java524
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/titledSeparator/TitledSeparator.java314
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/transitionComposite/DownUpAppearTransition.java34
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/transitionComposite/DownUpTransition.java33
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/transitionComposite/HorizontalTransition.java86
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/transitionComposite/LeftRightAppearTransition.java35
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/transitionComposite/LeftRightTransition.java35
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/transitionComposite/NoTransition.java31
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/transitionComposite/RightLeftAppearTransition.java35
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/transitionComposite/RightLeftTransition.java35
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/transitionComposite/TRANSITIONS.java18
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/transitionComposite/Transition.java28
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/transitionComposite/TransitionComposite.java274
-rwxr-xr-xorg.tizen.common.externals/src/org/mihalis/opal/transitionComposite/TransitionFactory.java48
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/transitionComposite/UpDownAppearTransition.java34
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/transitionComposite/UpDownTransition.java27
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/transitionComposite/VerticalTransition.java84
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/utils/FileToolbox.java47
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/utils/HTMLStyledTextParser.java179
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/utils/ResourceManager.java56
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/utils/SWTGraphicUtil.java463
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/utils/SimpleSelectionAdapter.java47
-rw-r--r--org.tizen.common.externals/src/org/mihalis/opal/utils/StringUtil.java73
-rw-r--r--org.tizen.common.externals/src/org/tizen/common/externals/ExternalsPlugin.java50
-rw-r--r--org.tizen.common.feature/build.properties3
-rw-r--r--org.tizen.common.feature/feature.xml70
-rw-r--r--org.tizen.common.feature/rootfiles/resources/icons/tizen-sdk-ide.icobin107078 -> 0 bytes
-rw-r--r--org.tizen.common.verrari/.classpath9
-rw-r--r--org.tizen.common.verrari/.project28
-rw-r--r--org.tizen.common.verrari/.settings/org.eclipse.jdt.core.prefs8
-rw-r--r--org.tizen.common.verrari/META-INF/MANIFEST.MF28
-rw-r--r--org.tizen.common.verrari/OSGI-INF/l10n/bundle.properties3
-rw-r--r--org.tizen.common.verrari/about.html41
-rw-r--r--org.tizen.common.verrari/about_files/LICENSE-2.0.htm191
-rw-r--r--org.tizen.common.verrari/about_files/jsoup-LICENSE.txt21
-rw-r--r--org.tizen.common.verrari/build.properties9
-rw-r--r--org.tizen.common.verrari/lib/jsoup-1.6.3.jarbin0 -> 276135 bytes
-rw-r--r--org.tizen.common.verrari/src/org/tizen/common/verrari/Activator.java78
-rw-r--r--org.tizen.common.verrari/src/org/tizen/common/verrari/engine/AbstractTemplateEngine.java131
-rw-r--r--org.tizen.common.verrari/src/org/tizen/common/verrari/engine/ITemplateEngine.java63
-rw-r--r--org.tizen.common.verrari/src/org/tizen/common/verrari/engine/TemplateEngineFactory.java87
-rw-r--r--org.tizen.common.verrari/src/org/tizen/common/verrari/engine/freemarker/FreemarkerTemplateEngine.java92
-rw-r--r--org.tizen.common.verrari/src/org/tizen/common/verrari/engine/jsoup/JsoupTemplateEngine.java110
-rw-r--r--org.tizen.common.verrari/src/org/tizen/common/verrari/model/IModel.java44
-rw-r--r--org.tizen.common.verrari/src/org/tizen/common/verrari/model/IModelProvider.java48
-rw-r--r--org.tizen.common.verrari/src/org/tizen/common/verrari/model/MapModel.java71
-rw-r--r--org.tizen.common.verrari/src/org/tizen/common/verrari/model/StaticModelProvider.java74
-rw-r--r--org.tizen.common.verrari/src/org/tizen/common/verrari/target/TargetGroup.java71
-rw-r--r--org.tizen.common.verrari/src/org/tizen/common/verrari/target/TargetUnit.java102
-rw-r--r--org.tizen.common.verrari/src/org/tizen/common/verrari/template/FileTemplate.java68
-rw-r--r--org.tizen.common.verrari/src/org/tizen/common/verrari/template/ITemplate.java47
-rw-r--r--org.tizen.common.verrari/src/org/tizen/common/verrari/template/ITemplateProvider.java52
-rw-r--r--org.tizen.common.verrari/src/org/tizen/common/verrari/template/StaticTemplateProvider.java88
-rw-r--r--org.tizen.common.verrari/template/html/description.ftl3
-rw-r--r--org.tizen.common.verrari/template/html/index_html.ftl36
-rw-r--r--org.tizen.common.verrari/template/html/index_html_body.ftl77
-rw-r--r--org.tizen.common.verrari/template/html/test.xml3
-rw-r--r--org.tizen.common.verrari/template/js/description.ftl3
-rw-r--r--org.tizen.common.verrari/template/js/main_js.ftl10
-rw-r--r--org.tizen.common.verrari/test/src/org/tizen/common/verrari/engine/TemplateEngineFactoryTest.java91
-rw-r--r--org.tizen.common.verrari/test/src/org/tizen/common/verrari/engine/freemarker/FreemarkerTemplateEngineTest.java128
-rw-r--r--org.tizen.common.verrari/test/src/org/tizen/common/verrari/engine/freemarker/description.ftl3
-rw-r--r--org.tizen.common.verrari/test/src/org/tizen/common/verrari/engine/freemarker/test.html24
-rw-r--r--org.tizen.common.verrari/test/src/org/tizen/common/verrari/engine/freemarker/testTizenMulti.html95
-rw-r--r--org.tizen.common.verrari/test/src/org/tizen/common/verrari/engine/freemarker/testTizenSingle.html55
-rw-r--r--org.tizen.common.verrari/test/src/org/tizen/common/verrari/engine/freemarker/testTizenSingle2.html49
-rw-r--r--org.tizen.common.verrari/test/src/org/tizen/common/verrari/engine/freemarker/test_html.ftl36
-rw-r--r--org.tizen.common.verrari/test/src/org/tizen/common/verrari/engine/freemarker/test_html_body.ftl77
-rw-r--r--org.tizen.common.verrari/test/src/org/tizen/common/verrari/engine/jsoup/JsoupTemplateEngineTest.java54
-rw-r--r--org.tizen.common.verrari/test/src/org/tizen/common/verrari/engine/jsoup/TizenSingle.html46
-rw-r--r--org.tizen.common.verrari/test/src/org/tizen/common/verrari/engine/jsoup/genTizenSingle.html46
-rw-r--r--org.tizen.common.verrari/test/src/org/tizen/common/verrari/target/TargetGruopTest.java165
-rw-r--r--org.tizen.common.verrari/test/src/org/tizen/common/verrari/target/TargetUnitTest.java230
-rw-r--r--org.tizen.common.verrari/test/src/org/tizen/common/verrari/template/FileTemplateTest.java144
-rw-r--r--org.tizen.common.verrari/test/src/org/tizen/common/verrari/template/StaticTemplateProviderTest.java180
-rw-r--r--org.tizen.common.verrari/test/src/org/tizen/common/verrari/template/test_html.ftl9
-rwxr-xr-x[-rw-r--r--]org.tizen.common/.classpath30
-rw-r--r--org.tizen.common/.settings/org.eclipse.core.resources.prefs3
-rwxr-xr-x[-rw-r--r--]org.tizen.common/META-INF/MANIFEST.MF146
-rw-r--r--org.tizen.common/OSGI-INF/l10n/bundle.properties25
-rw-r--r--org.tizen.common/about.html12
-rw-r--r--org.tizen.common/about_files/freemarker-LICENSE.txt69
-rwxr-xr-x[-rw-r--r--]org.tizen.common/build.properties11
-rw-r--r--org.tizen.common/icons/back.gifbin0 -> 327 bytes
-rw-r--r--org.tizen.common/icons/forward.gifbin0 -> 327 bytes
-rw-r--r--org.tizen.common/lib/commons-collections-3.2.1.jarbin0 -> 575389 bytes
-rw-r--r--org.tizen.common/lib/commons-io-2.4.jarbin0 -> 185140 bytes
-rw-r--r--org.tizen.common/lib/commons-lang3-3.1.jarbin0 -> 315805 bytes
-rw-r--r--org.tizen.common/lib/commons-logging-1.1.1.jarbin0 -> 60686 bytes
-rw-r--r--org.tizen.common/lib/commons-pool-1.6.jarbin0 -> 111119 bytes
-rw-r--r--org.tizen.common/lib/freemarker.jarbin0 -> 924269 bytes
-rw-r--r--org.tizen.common/lib/log4j-1.2.17.jarbin0 -> 489883 bytes
-rw-r--r--org.tizen.common/lib/sdblib.jarbin0 -> 77370 bytes
-rw-r--r--org.tizen.common/lib/slf4j-api-1.6.4.jarbin0 -> 25962 bytes
-rw-r--r--org.tizen.common/lib/slf4j-log4j12-1.6.4.jarbin0 -> 9748 bytes
-rw-r--r--org.tizen.common/plugin.xml105
-rw-r--r--org.tizen.common/schema/org.tizen.common.prompter.exsd109
-rw-r--r--org.tizen.common/sdblib.jarbin65586 -> 0 bytes
-rw-r--r--org.tizen.common/src/org/tizen/common/Adaptable.java49
-rw-r--r--org.tizen.common/src/org/tizen/common/AppIdGenerator.java127
-rwxr-xr-xorg.tizen.common/src/org/tizen/common/Cabinet.java10
-rw-r--r--org.tizen.common/src/org/tizen/common/CommonPlugin.java147
-rw-r--r--org.tizen.common/src/org/tizen/common/Factory.java (renamed from org.tizen.common/src/org/tizen/common/model/DefaultTableModel.java)88
-rw-r--r--org.tizen.common/src/org/tizen/common/FactoryWithArgument.java (renamed from org.tizen.common/src/org/tizen/common/control/TableViewContentProvider.java)95
-rwxr-xr-xorg.tizen.common/src/org/tizen/common/IApplicationConfiguration.java39
-rw-r--r--org.tizen.common/src/org/tizen/common/Surrogate.java44
-rw-r--r--org.tizen.common/src/org/tizen/common/SurrogateWithArgument.java (renamed from org.tizen.common/src/org/tizen/common/control/TreeViewLabelProvider.java)74
-rw-r--r--org.tizen.common/src/org/tizen/common/TizenHelpContextIds.java49
-rw-r--r--org.tizen.common/src/org/tizen/common/TizenPlatformConstants.java80
-rw-r--r--org.tizen.common/src/org/tizen/common/TizenProjectType.java41
-rw-r--r--org.tizen.common/src/org/tizen/common/cache/ImageCache.java105
-rw-r--r--org.tizen.common/src/org/tizen/common/control/TableViewCellModifier.java136
-rw-r--r--org.tizen.common/src/org/tizen/common/control/TableViewColumnSorter.java160
-rw-r--r--org.tizen.common/src/org/tizen/common/control/TableViewLabelProvider.java121
-rw-r--r--org.tizen.common/src/org/tizen/common/control/TreeViewContentProvider.java69
-rw-r--r--org.tizen.common/src/org/tizen/common/core/application/InstallPathConfig.java212
-rw-r--r--org.tizen.common/src/org/tizen/common/core/application/Messages.java19
-rw-r--r--org.tizen.common/src/org/tizen/common/core/application/Messages.properties5
-rw-r--r--org.tizen.common/src/org/tizen/common/core/application/StatusLineMessageManager.java80
-rwxr-xr-x[-rw-r--r--]org.tizen.common/src/org/tizen/common/core/application/UpdateManager.java (renamed from org.tizen.common/src/org/tizen/common/update/UpdateManager.java)77
-rw-r--r--org.tizen.common/src/org/tizen/common/core/command/AbstractCommand.java94
-rw-r--r--org.tizen.common/src/org/tizen/common/core/command/Command.java69
-rw-r--r--org.tizen.common/src/org/tizen/common/core/command/CommandCancelException.java45
-rw-r--r--org.tizen.common/src/org/tizen/common/core/command/CompositeCommand.java103
-rw-r--r--org.tizen.common/src/org/tizen/common/core/command/EclipseExecutor.java70
-rw-r--r--org.tizen.common/src/org/tizen/common/core/command/ExecutionContext.java138
-rw-r--r--org.tizen.common/src/org/tizen/common/core/command/Executor.java213
-rw-r--r--org.tizen.common/src/org/tizen/common/core/command/Policy.java154
-rw-r--r--org.tizen.common/src/org/tizen/common/core/command/PolicyRegistryFactory.java240
-rw-r--r--org.tizen.common/src/org/tizen/common/core/command/Prompter.java94
-rw-r--r--org.tizen.common/src/org/tizen/common/core/command/file/DirectoryCopyHandlingCommand.java145
-rw-r--r--org.tizen.common/src/org/tizen/common/core/command/file/FileHandlingCommand.java192
-rw-r--r--org.tizen.common/src/org/tizen/common/core/command/file/WriteFileCommand.java40
-rw-r--r--org.tizen.common/src/org/tizen/common/core/command/policy/AbstractMessagePolicy.java66
-rw-r--r--org.tizen.common/src/org/tizen/common/core/command/policy/AbstractPolicy.java73
-rw-r--r--org.tizen.common/src/org/tizen/common/core/command/policy/FilePolicy.java76
-rw-r--r--org.tizen.common/src/org/tizen/common/core/command/policy/MessagePolicy.java146
-rw-r--r--org.tizen.common/src/org/tizen/common/core/command/policy/OptionPolicy.java60
-rw-r--r--org.tizen.common/src/org/tizen/common/core/command/policy/PolicyRegistry.java294
-rw-r--r--org.tizen.common/src/org/tizen/common/core/command/policy/SimplePolicy.java49
-rw-r--r--org.tizen.common/src/org/tizen/common/core/command/policy/UncaughtExceptionHandlingPolicy.java113
-rw-r--r--org.tizen.common/src/org/tizen/common/core/command/prompter/AbstractOption.java181
-rw-r--r--org.tizen.common/src/org/tizen/common/core/command/prompter/AbstractPrompter.java86
-rw-r--r--org.tizen.common/src/org/tizen/common/core/command/prompter/ChoiceOption.java95
-rw-r--r--org.tizen.common/src/org/tizen/common/core/command/prompter/EclipsePrompter.java201
-rw-r--r--org.tizen.common/src/org/tizen/common/core/command/prompter/GenericOption.java149
-rw-r--r--org.tizen.common/src/org/tizen/common/core/command/prompter/NopPrompter.java129
-rw-r--r--org.tizen.common/src/org/tizen/common/core/command/prompter/Option.java11
-rw-r--r--org.tizen.common/src/org/tizen/common/core/command/prompter/RunableOption.java124
-rwxr-xr-xorg.tizen.common/src/org/tizen/common/core/command/prompter/SWTPrompter.java233
-rw-r--r--org.tizen.common/src/org/tizen/common/core/command/sdb/DevicesSdbCommand.java65
-rw-r--r--org.tizen.common/src/org/tizen/common/core/command/sdb/DlogSdbCommand.java54
-rw-r--r--org.tizen.common/src/org/tizen/common/core/command/sdb/ForwardSdbCommand.java70
-rw-r--r--org.tizen.common/src/org/tizen/common/core/command/sdb/PullSdbCommand.java87
-rw-r--r--org.tizen.common/src/org/tizen/common/core/command/sdb/PushSdbCommand.java93
-rw-r--r--org.tizen.common/src/org/tizen/common/core/command/sdb/SdbDevicesHandlingCommand.java (renamed from org.tizen.common/src/org/tizen/common/model/DefaultTreeModel.java)89
-rw-r--r--org.tizen.common/src/org/tizen/common/core/command/sdb/SdbHandlingCommand.java60
-rw-r--r--org.tizen.common/src/org/tizen/common/core/command/sdb/ShellSdbCommand.java142
-rw-r--r--org.tizen.common/src/org/tizen/common/core/command/sdb/SmartDevelopmentBridgeManager.java93
-rw-r--r--org.tizen.common/src/org/tizen/common/core/command/zip/ZipCommand.java196
-rw-r--r--org.tizen.common/src/org/tizen/common/file/AbstractFileHandler.java66
-rw-r--r--org.tizen.common/src/org/tizen/common/file/EclipseFileHandler.java448
-rw-r--r--org.tizen.common/src/org/tizen/common/file/FileHandler.java235
-rw-r--r--org.tizen.common/src/org/tizen/common/file/Filter.java48
-rw-r--r--org.tizen.common/src/org/tizen/common/file/PatternFilter.java77
-rw-r--r--org.tizen.common/src/org/tizen/common/file/SimpleFileFilter.java193
-rwxr-xr-xorg.tizen.common/src/org/tizen/common/file/StandardFileHandler.java394
-rw-r--r--org.tizen.common/src/org/tizen/common/file/VirtualFileHandler.java798
-rw-r--r--org.tizen.common/src/org/tizen/common/file/filter/WildCardFilter.java96
-rw-r--r--org.tizen.common/src/org/tizen/common/file/filter/WildCardFilterFactory.java60
-rw-r--r--org.tizen.common/src/org/tizen/common/handler/ClearHandler.java65
-rw-r--r--org.tizen.common/src/org/tizen/common/handler/ClipboardHandler.java51
-rw-r--r--org.tizen.common/src/org/tizen/common/handler/CopyHandler.java101
-rw-r--r--org.tizen.common/src/org/tizen/common/handler/Messages.java49
-rw-r--r--org.tizen.common/src/org/tizen/common/handler/OpenFileHandler.java103
-rw-r--r--org.tizen.common/src/org/tizen/common/handler/OpenPreferencesHandler.java61
-rw-r--r--org.tizen.common/src/org/tizen/common/handler/SaveFileHandler.java139
-rw-r--r--org.tizen.common/src/org/tizen/common/handler/messages.properties10
-rw-r--r--org.tizen.common/src/org/tizen/common/manager/StatusLineMessageManager.java47
-rw-r--r--org.tizen.common/src/org/tizen/common/manager/messages.properties1
-rw-r--r--org.tizen.common/src/org/tizen/common/model/AbstractTableModel.java180
-rw-r--r--org.tizen.common/src/org/tizen/common/model/AbstractTableVO.java80
-rw-r--r--org.tizen.common/src/org/tizen/common/model/AbstractTreeModel.java102
-rw-r--r--org.tizen.common/src/org/tizen/common/model/AbstractTreeVO.java109
-rw-r--r--org.tizen.common/src/org/tizen/common/model/ITableModel.java45
-rw-r--r--org.tizen.common/src/org/tizen/common/model/ITreeVO.java42
-rw-r--r--org.tizen.common/src/org/tizen/common/model/IVO.java29
-rw-r--r--org.tizen.common/src/org/tizen/common/preferences/PreferenceMessages.properties6
-rw-r--r--org.tizen.common/src/org/tizen/common/properties/InstallPathConfig.java141
-rw-r--r--org.tizen.common/src/org/tizen/common/queue/Queue.java71
-rw-r--r--org.tizen.common/src/org/tizen/common/ui/CommonColor.java (renamed from org.tizen.common/src/org/tizen/common/swt/CommonColor.java)20
-rw-r--r--org.tizen.common/src/org/tizen/common/ui/TableToolTipListener.java133
-rw-r--r--org.tizen.common/src/org/tizen/common/ui/dialog/ClosableTray.java (renamed from org.tizen.common/src/org/tizen/common/swt/ClosableTray.java)7
-rw-r--r--org.tizen.common/src/org/tizen/common/ui/dialog/PasswordInputDialog.java114
-rw-r--r--org.tizen.common/src/org/tizen/common/ui/page/preference/Messages.java (renamed from org.tizen.common/src/org/tizen/common/manager/Messages.java)23
-rw-r--r--org.tizen.common/src/org/tizen/common/ui/page/preference/Messages.properties5
-rw-r--r--org.tizen.common/src/org/tizen/common/ui/page/preference/PreferenceMessages.java (renamed from org.tizen.common/src/org/tizen/common/preferences/PreferenceMessages.java)2
-rw-r--r--org.tizen.common/src/org/tizen/common/ui/page/preference/PreferenceMessages.properties5
-rw-r--r--org.tizen.common/src/org/tizen/common/ui/page/preference/TizenBasePreferencePage.java (renamed from org.tizen.common/src/org/tizen/common/preferences/TizenBasePreferencePage.java)22
-rw-r--r--org.tizen.common/src/org/tizen/common/ui/page/wizard/TrayWizardPage.java (renamed from org.tizen.common/src/org/tizen/common/swt/TrayWizardPage.java)3
-rwxr-xr-x[-rw-r--r--]org.tizen.common/src/org/tizen/common/ui/view/console/AnsicodeAdapter.java (renamed from org.tizen.common/src/org/tizen/common/console/AnsicodeAdapter.java)122
-rw-r--r--org.tizen.common/src/org/tizen/common/ui/view/console/ConsoleManager.java (renamed from org.tizen.common/src/org/tizen/common/console/ConsoleManager.java)5
-rw-r--r--org.tizen.common/src/org/tizen/common/ui/view/console/ConsoleManager2.java411
-rw-r--r--org.tizen.common/src/org/tizen/common/ui/view/console/ConsoleProcessClosure.java (renamed from org.tizen.common/src/org/tizen/common/console/ConsoleProcessClosure.java)36
-rw-r--r--org.tizen.common/src/org/tizen/common/ui/view/console/HyperlinkManager.java131
-rw-r--r--org.tizen.common/src/org/tizen/common/ui/view/console/IConsolePrinter.java46
-rw-r--r--org.tizen.common/src/org/tizen/common/ui/view/console/IHyperlinkManager.java (renamed from org.tizen.common/src/org/tizen/common/model/ITableVO.java)81
-rw-r--r--org.tizen.common/src/org/tizen/common/ui/view/console/LinkInfo.java151
-rw-r--r--org.tizen.common/src/org/tizen/common/ui/view/console/MessageConsoleSpy.java55
-rw-r--r--org.tizen.common/src/org/tizen/common/ui/view/console/TextStyle.java (renamed from org.tizen.common/src/org/tizen/common/console/TextStyle.java)2
-rw-r--r--org.tizen.common/src/org/tizen/common/ui/widget/PictureLabel.java (renamed from org.tizen.common/src/org/tizen/common/swt/PictureLabel.java)5
-rw-r--r--org.tizen.common/src/org/tizen/common/update/UpdateMessages.properties3
-rwxr-xr-xorg.tizen.common/src/org/tizen/common/util/ArrayUtil.java1124
-rwxr-xr-xorg.tizen.common/src/org/tizen/common/util/Assert.java837
-rw-r--r--org.tizen.common/src/org/tizen/common/util/BrowserWrapper.java5
-rw-r--r--org.tizen.common/src/org/tizen/common/util/CipherUtil.java97
-rw-r--r--org.tizen.common/src/org/tizen/common/util/CollectionMap.java232
-rw-r--r--org.tizen.common/src/org/tizen/common/util/CollectionUtil.java1890
-rw-r--r--org.tizen.common/src/org/tizen/common/util/ControlFileConfig.java4
-rw-r--r--org.tizen.common/src/org/tizen/common/util/DialogUtil.java9
-rwxr-xr-xorg.tizen.common/src/org/tizen/common/util/EFSUtil.java303
-rw-r--r--org.tizen.common/src/org/tizen/common/util/FileUtil.java312
-rwxr-xr-xorg.tizen.common/src/org/tizen/common/util/FilenameUtil.java422
-rw-r--r--org.tizen.common/src/org/tizen/common/util/FilterIterator.java158
-rw-r--r--org.tizen.common/src/org/tizen/common/util/FreeMarkerUtil.java180
-rw-r--r--org.tizen.common/src/org/tizen/common/util/HelpBrowser.java120
-rwxr-xr-x[-rw-r--r--]org.tizen.common/src/org/tizen/common/util/HostUtil.java609
-rw-r--r--org.tizen.common/src/org/tizen/common/util/IOUtil.java352
-rw-r--r--org.tizen.common/src/org/tizen/common/util/ImageUtil.java (renamed from org.tizen.common/src/org/tizen/common/util/ImageUtils.java)66
-rw-r--r--org.tizen.common/src/org/tizen/common/util/IteratingAcceptor.java49
-rw-r--r--org.tizen.common/src/org/tizen/common/util/IteratingAdapter.java7
-rw-r--r--org.tizen.common/src/org/tizen/common/util/IteratingRunner.java (renamed from org.tizen.common/src/org/tizen/common/model/ITreeModel.java)89
-rw-r--r--org.tizen.common/src/org/tizen/common/util/IteratingUtil.java27
-rw-r--r--org.tizen.common/src/org/tizen/common/util/LocalPortChecker.java75
-rw-r--r--org.tizen.common/src/org/tizen/common/util/MapUtil.java219
-rw-r--r--org.tizen.common/src/org/tizen/common/util/NotificationType.java2
-rw-r--r--org.tizen.common/src/org/tizen/common/util/NotifierDialog.java17
-rw-r--r--org.tizen.common/src/org/tizen/common/util/OSChecker.java37
-rw-r--r--org.tizen.common/src/org/tizen/common/util/ObjectUtil.java411
-rw-r--r--org.tizen.common/src/org/tizen/common/util/ParsingUtil.java183
-rw-r--r--org.tizen.common/src/org/tizen/common/util/PluginUtil.java105
-rw-r--r--org.tizen.common/src/org/tizen/common/util/ProjectUtil.java199
-rw-r--r--org.tizen.common/src/org/tizen/common/util/PropertyUtil.java27
-rwxr-xr-xorg.tizen.common/src/org/tizen/common/util/SWTRunner.java44
-rwxr-xr-x[-rw-r--r--]org.tizen.common/src/org/tizen/common/util/SWTUtil.java294
-rw-r--r--org.tizen.common/src/org/tizen/common/util/SdbCommandUtil.java76
-rwxr-xr-x[-rw-r--r--]org.tizen.common/src/org/tizen/common/util/StreamGobbler.java9
-rwxr-xr-x[-rw-r--r--]org.tizen.common/src/org/tizen/common/util/StringUtil.java1072
-rw-r--r--org.tizen.common/src/org/tizen/common/util/ThreadUtil.java60
-rw-r--r--org.tizen.common/src/org/tizen/common/util/ValidationUtil.java94
-rw-r--r--org.tizen.common/src/org/tizen/common/util/ViewUtil.java25
-rw-r--r--org.tizen.common/src/org/tizen/common/util/cache/ColorCache.java (renamed from org.tizen.common/src/org/tizen/common/cache/ColorCache.java)41
-rwxr-xr-x[-rw-r--r--]org.tizen.common/src/org/tizen/common/util/cache/FontCache.java (renamed from org.tizen.common/src/org/tizen/common/cache/FontCache.java)30
-rw-r--r--org.tizen.common/src/org/tizen/common/util/cache/ImageCache.java108
-rw-r--r--org.tizen.common/src/org/tizen/common/util/cache/NamedColorCache.java (renamed from org.tizen.common/src/org/tizen/common/manager/ColorCache.java)14
-rw-r--r--org.tizen.common/src/org/tizen/common/util/io/Buffer.java504
-rw-r--r--org.tizen.common/src/org/tizen/common/util/io/BufferInputStream.java81
-rw-r--r--org.tizen.common/src/org/tizen/common/util/io/BufferOutputStream.java94
-rw-r--r--org.tizen.common/src/org/tizen/common/util/io/BufferPool.java248
-rw-r--r--org.tizen.common/src/org/tizen/common/util/log/Logger.java (renamed from org.tizen.common/src/org/tizen/common/log/Logger.java)9
-rw-r--r--org.tizen.common/src/org/tizen/common/util/url/classpath/Connection.java181
-rw-r--r--org.tizen.common/src/org/tizen/common/util/url/classpath/Handler.java104
-rw-r--r--org.tizen.common/src/org/tizen/common/util/url/cp/Connection.java54
-rw-r--r--org.tizen.common/src/org/tizen/common/util/url/cp/Handler.java60
-rw-r--r--org.tizen.common/src/org/tizen/common/util/url/vf/Connection.java125
-rw-r--r--org.tizen.common/src/org/tizen/common/util/url/vf/Handler.java59
-rw-r--r--org.tizen.common/test/lib/asm-4.0.jarbin0 -> 46018 bytes
-rw-r--r--org.tizen.common/test/lib/asm-tree-4.0.jarbin0 -> 21980 bytes
-rw-r--r--org.tizen.common/test/lib/junit-4.10-src.jarbin0 -> 141185 bytes
-rw-r--r--org.tizen.common/test/lib/junit-4.10.jarbin0 -> 253160 bytes
-rw-r--r--org.tizen.common/test/lib/mockito-all-1.9.0.jarbin0 -> 1495219 bytes
-rwxr-xr-xorg.tizen.common/test/src/log4j.xml15
-rw-r--r--org.tizen.common/test/src/org/tizen/common/AppIdGeneratorTest.java76
-rw-r--r--org.tizen.common/test/src/org/tizen/common/ClassSource.java53
-rw-r--r--org.tizen.common/test/src/org/tizen/common/CommonPluginTest.java80
-rw-r--r--org.tizen.common/test/src/org/tizen/common/DirectorySource.java85
-rw-r--r--org.tizen.common/test/src/org/tizen/common/FrequentlyUsedMatcher.java70
-rw-r--r--org.tizen.common/test/src/org/tizen/common/JarSource.java103
-rw-r--r--org.tizen.common/test/src/org/tizen/common/Location.java53
-rw-r--r--org.tizen.common/test/src/org/tizen/common/TestAgent.java17
-rw-r--r--org.tizen.common/test/src/org/tizen/common/Transformer.java38
-rw-r--r--org.tizen.common/test/src/org/tizen/common/UnsafeClassLoader.java255
-rw-r--r--org.tizen.common/test/src/org/tizen/common/UnsafeRunner.java180
-rw-r--r--org.tizen.common/test/src/org/tizen/common/core/application/MessagesTest.java58
-rw-r--r--org.tizen.common/test/src/org/tizen/common/core/application/StatusLineMessageManagerTest.java95
-rwxr-xr-xorg.tizen.common/test/src/org/tizen/common/core/command/CommandTest.java151
-rw-r--r--org.tizen.common/test/src/org/tizen/common/core/command/CompositeCommandTest.java104
-rw-r--r--org.tizen.common/test/src/org/tizen/common/core/command/ExecutionContextTest.java100
-rw-r--r--org.tizen.common/test/src/org/tizen/common/core/command/file/FileHandlingCommandTest.java103
-rw-r--r--org.tizen.common/test/src/org/tizen/common/core/command/policy/PolicyRegistryTest.java72
-rw-r--r--org.tizen.common/test/src/org/tizen/common/core/command/prompter/GenericOptionTest.java98
-rw-r--r--org.tizen.common/test/src/org/tizen/common/core/command/prompter/OptionTest.java91
-rw-r--r--org.tizen.common/test/src/org/tizen/common/core/command/prompter/SWTPrompterTest.java109
-rw-r--r--org.tizen.common/test/src/org/tizen/common/core/command/sdb/DevicesSdbCommandTest.java68
-rw-r--r--org.tizen.common/test/src/org/tizen/common/core/command/sdb/DlogSdbCommandTest.java82
-rw-r--r--org.tizen.common/test/src/org/tizen/common/core/command/sdb/ForwardSdbCommandTest.java94
-rw-r--r--org.tizen.common/test/src/org/tizen/common/core/command/sdb/PullSdbCommandTest.java83
-rw-r--r--org.tizen.common/test/src/org/tizen/common/core/command/sdb/PushSdbCommandTest.java71
-rw-r--r--org.tizen.common/test/src/org/tizen/common/core/command/sdb/ShellSdbCommandTest.java111
-rw-r--r--org.tizen.common/test/src/org/tizen/common/core/command/zip/ZipCommandTest.java79
-rwxr-xr-xorg.tizen.common/test/src/org/tizen/common/file/SimpleFileFilterTest.java90
-rw-r--r--org.tizen.common/test/src/org/tizen/common/file/VirtualFileHandlerTest.java71
-rw-r--r--org.tizen.common/test/src/org/tizen/common/file/filter/WildCardFilterFactoryTest.java81
-rw-r--r--org.tizen.common/test/src/org/tizen/common/file/filter/WildCardFilterTest.java89
-rw-r--r--org.tizen.common/test/src/org/tizen/common/ui/page/preference/MessagesTest.java66
-rw-r--r--org.tizen.common/test/src/org/tizen/common/ui/page/wizard/TrayWizardPageTest.java91
-rwxr-xr-xorg.tizen.common/test/src/org/tizen/common/util/ArrayUtilTest.java765
-rw-r--r--org.tizen.common/test/src/org/tizen/common/util/AssertTest.java158
-rw-r--r--org.tizen.common/test/src/org/tizen/common/util/CollectionMapTest.java139
-rw-r--r--org.tizen.common/test/src/org/tizen/common/util/CollectionUtilTest.java950
-rw-r--r--org.tizen.common/test/src/org/tizen/common/util/EFSUtilTest.java240
-rw-r--r--org.tizen.common/test/src/org/tizen/common/util/FileUtilTest.java113
-rw-r--r--org.tizen.common/test/src/org/tizen/common/util/FilenameUtilTest.java256
-rw-r--r--org.tizen.common/test/src/org/tizen/common/util/FilterIteratorTest.java70
-rw-r--r--org.tizen.common/test/src/org/tizen/common/util/FreeMarkerUtilTest.java62
-rw-r--r--org.tizen.common/test/src/org/tizen/common/util/HostUtilTest.java117
-rw-r--r--org.tizen.common/test/src/org/tizen/common/util/IOUtilTest.java242
-rw-r--r--org.tizen.common/test/src/org/tizen/common/util/ImageUtilTest.java276
-rw-r--r--org.tizen.common/test/src/org/tizen/common/util/ImageUtilTest.pngbin0 -> 1472 bytes
-rw-r--r--org.tizen.common/test/src/org/tizen/common/util/LocalPortCheckerTest.java105
-rw-r--r--org.tizen.common/test/src/org/tizen/common/util/MapUtilTest.java205
-rw-r--r--org.tizen.common/test/src/org/tizen/common/util/MockRunner.java (renamed from org.tizen.common/src/org/tizen/common/control/NotSupportedTypeException.java)27
-rw-r--r--org.tizen.common/test/src/org/tizen/common/util/ObjectUtilTest.java140
-rw-r--r--org.tizen.common/test/src/org/tizen/common/util/ParsingUtilTest.java108
-rw-r--r--org.tizen.common/test/src/org/tizen/common/util/PluginUtilTest.java111
-rw-r--r--org.tizen.common/test/src/org/tizen/common/util/SWTUtilTest.java123
-rw-r--r--org.tizen.common/test/src/org/tizen/common/util/StringUtilTest.java459
-rw-r--r--org.tizen.common/test/src/org/tizen/common/util/ThreadUtilTest.java70
-rw-r--r--org.tizen.common/test/src/org/tizen/common/util/ValidationUtilTest.java146
-rw-r--r--org.tizen.common/test/src/org/tizen/common/util/io/BufferPoolTest.java90
-rw-r--r--org.tizen.common/test/src/org/tizen/common/util/io/BufferTest.java274
-rw-r--r--org.tizen.common/test/src/org/tizen/common/util/test1
-rw-r--r--org.tizen.common/test/src/org/tizen/common/util/url/classpath/ConnectionTest.java92
-rw-r--r--org.tizen.common/test/src/org/tizen/common/util/url/classpath/HandlerTest.java126
-rw-r--r--org.tizen.common/test/src/org/tizen/common/util/url/classpath/a.txt1
-rw-r--r--org.tizen.common/test/src/org/tizen/common/util/url/cp/HandlerTest.java115
-rwxr-xr-xpackage/build.linux328
-rw-r--r--package/pkginfo.manifest48
471 files changed, 61036 insertions, 8109 deletions
diff --git a/org.tizen.common.connection/META-INF/MANIFEST.MF b/org.tizen.common.connection/META-INF/MANIFEST.MF
index 3aa5a4cd4..f3a3e077c 100644
--- a/org.tizen.common.connection/META-INF/MANIFEST.MF
+++ b/org.tizen.common.connection/META-INF/MANIFEST.MF
@@ -1,17 +1,18 @@
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
-Bundle-Name: Tizen Common Connection
+Bundle-Name: %Bundle-Name
Bundle-SymbolicName: org.tizen.common.connection;singleton:=true
Bundle-Version: 1.0.0.qualifier
Bundle-Activator: org.tizen.common.connection.ConnectionPlugin
-Bundle-Vendor: Samsung
+Bundle-Vendor: %Bundle-Vendor
Require-Bundle: org.eclipse.ui,
org.eclipse.core.runtime,
- org.eclipse.core.resources;bundle-version="3.6.1",
+ org.eclipse.core.resources,
org.tizen.common
Bundle-RequiredExecutionEnvironment: JavaSE-1.6
Bundle-ActivationPolicy: lazy
-Import-Package: org.tizen.common.util
+Import-Package: org.eclipse.ui.console,
+ org.tizen.common.util
Bundle-ClassPath: .
Export-Package: org.tizen.common.connection;
uses:="org.eclipse.jface.resource,
diff --git a/org.tizen.common.connection/OSGI-INF/l10n/bundle.properties b/org.tizen.common.connection/OSGI-INF/l10n/bundle.properties
new file mode 100644
index 000000000..30d37969d
--- /dev/null
+++ b/org.tizen.common.connection/OSGI-INF/l10n/bundle.properties
@@ -0,0 +1,27 @@
+Bundle-Name = Tizen Common Connection
+Bundle-Vendor = Samsung Electronics
+
+view.category = Tizen
+view.connectionExplorer = Connection Explorer
+view.log = Log
+
+properties.page.info = Info
+properties.page.permission = Permission
+
+command.category = Connection Explorer
+command.delete.name = Delete
+command.delete.description = Delete a file or folder on the connected target
+command.rename.name = Rename
+command.rename.description = Rename a file or folder on the connected target
+command.refresh.name = Refresh
+command.refresh.description = Referesh contents of the connected target
+command.property.name = Properties
+command.property.description = View properties for a selected file or folder
+
+context.delete.name = Delete
+context.rename.name = Rename
+context.refresh.name = Refresh
+context.properties.name = Properties
+
+extension.name = Connection Resource Drop
+extension-point.name = tools \ No newline at end of file
diff --git a/org.tizen.common.connection/build.properties b/org.tizen.common.connection/build.properties
index 414cf4bce..71c01b3ae 100644
--- a/org.tizen.common.connection/build.properties
+++ b/org.tizen.common.connection/build.properties
@@ -5,6 +5,8 @@ bin.includes = META-INF/,\
plugin.xml,\
icons/,\
about.html,\
- about_files/
+ about_files/,\
+ OSGI-INF/,\
+ OSGI-INF/l10n/bundle.properties
jars.compile.order = .,\
sdblib.jar
diff --git a/org.tizen.common.connection/icons/Emulator_stop.gif b/org.tizen.common.connection/icons/Emulator_stop.gif
deleted file mode 100644
index 60cf40cad..000000000
--- a/org.tizen.common.connection/icons/Emulator_stop.gif
+++ /dev/null
Binary files differ
diff --git a/org.tizen.common.connection/icons/Connection Explorer.gif b/org.tizen.common.connection/icons/connection_explorer.gif
index 111e3f9ea..111e3f9ea 100644
--- a/org.tizen.common.connection/icons/Connection Explorer.gif
+++ b/org.tizen.common.connection/icons/connection_explorer.gif
Binary files differ
diff --git a/org.tizen.common.connection/icons/Emulator_start.gif b/org.tizen.common.connection/icons/emulator_manager.gif
index 8737c07bd..8737c07bd 100644
--- a/org.tizen.common.connection/icons/Emulator_start.gif
+++ b/org.tizen.common.connection/icons/emulator_manager.gif
Binary files differ
diff --git a/org.tizen.common.connection/icons/log/Add tab.png b/org.tizen.common.connection/icons/log/add_tab.png
index b07109b79..b07109b79 100644
--- a/org.tizen.common.connection/icons/log/Add tab.png
+++ b/org.tizen.common.connection/icons/log/add_tab.png
Binary files differ
diff --git a/org.tizen.common.connection/icons/log/Clear Log.png b/org.tizen.common.connection/icons/log/clear_log.png
index 4f542ad11..4f542ad11 100644
--- a/org.tizen.common.connection/icons/log/Clear Log.png
+++ b/org.tizen.common.connection/icons/log/clear_log.png
Binary files differ
diff --git a/org.tizen.common.connection/icons/log/Edit tab.png b/org.tizen.common.connection/icons/log/edit_tab.png
index d13ab48cf..d13ab48cf 100644
--- a/org.tizen.common.connection/icons/log/Edit tab.png
+++ b/org.tizen.common.connection/icons/log/edit_tab.png
Binary files differ
diff --git a/org.tizen.common.connection/icons/log/Export Log.png b/org.tizen.common.connection/icons/log/export_log.png
index ee3f1e8a3..ee3f1e8a3 100644
--- a/org.tizen.common.connection/icons/log/Export Log.png
+++ b/org.tizen.common.connection/icons/log/export_log.png
Binary files differ
diff --git a/org.tizen.common.connection/icons/log/Log View.gif b/org.tizen.common.connection/icons/log/logview.gif
index 9007253b2..9007253b2 100644
--- a/org.tizen.common.connection/icons/log/Log View.gif
+++ b/org.tizen.common.connection/icons/log/logview.gif
Binary files differ
diff --git a/org.tizen.common.connection/icons/log/Remove tab.png b/org.tizen.common.connection/icons/log/remove_tab.png
index 6788fc85b..6788fc85b 100644
--- a/org.tizen.common.connection/icons/log/Remove tab.png
+++ b/org.tizen.common.connection/icons/log/remove_tab.png
Binary files differ
diff --git a/org.tizen.common.connection/icons/log/scroll_lock.png b/org.tizen.common.connection/icons/log/scroll_lock.png
new file mode 100644
index 000000000..41078de92
--- /dev/null
+++ b/org.tizen.common.connection/icons/log/scroll_lock.png
Binary files differ
diff --git a/org.tizen.common.connection/plugin.xml b/org.tizen.common.connection/plugin.xml
index 89e284e97..4a0b7715c 100644
--- a/org.tizen.common.connection/plugin.xml
+++ b/org.tizen.common.connection/plugin.xml
@@ -1,25 +1,37 @@
<?xml version="1.0" encoding="UTF-8"?>
<?eclipse version="3.4"?>
<plugin>
- <extension-point id="org.tizen.common.connection.tools" name="tools" schema="schema/tools.exsd"/>
- <extension
- point="org.eclipse.ui.views">
- <category
- name="Tizen"
- id="org.tizen.nativeapp.viewCategory"/>
+ <extension-point id="org.tizen.common.connection.tools" name="%extension-point.name" schema="schema/tools.exsd"/>
+ <extension
+ point="org.eclipse.ui.views">
+ <category
+ name="%view.category"
+ id="org.tizen.nativeapp.viewCategory"/>
</extension>
<extension
point="org.eclipse.ui.views">
<view
category="org.tizen.nativeapp.viewCategory"
class="org.tizen.common.connection.ui.ConnectionExplorer"
- icon="icons/Connection Explorer.gif"
+ icon="icons/connection_explorer.gif"
id="org.tizen.common.connection.ui.ConnectionExplorer"
- name="Connection Explorer"
+ name="%view.connectionExplorer"
restorable="true">
</view>
</extension>
-
+
+ <extension
+ point="org.eclipse.ui.views">
+ <view
+ name="%view.log"
+ icon="icons/log/logview.gif"
+ category="org.tizen.nativeapp.viewCategory"
+ class="org.tizen.common.connection.ui.LogView"
+ id="org.tizen.common.connection.ui.LogView"
+ allowMultiple = "true">
+ </view>
+ </extension>
+
<extension
point="org.eclipse.ui.perspectiveExtensions">
<perspectiveExtension
@@ -35,29 +47,55 @@
</viewShortcut>
</perspectiveExtension>
</extension>
+ <extension
+ point="org.eclipse.ui.perspectiveExtensions">
+ <perspectiveExtension
+ targetID="org.tizen.nativeapp.perspective">
+ <view
+ id="org.tizen.common.connection.ui.LogView"
+ ratio="1"
+ relationship="stack"
+ relative="org.eclipse.ui.views.TaskList">
+ </view>
+ <viewShortcut
+ id="org.tizen.common.connection.ui.LogView">
+ </viewShortcut>
+ </perspectiveExtension>
+ <perspectiveExtension
+ targetID="org.eclipse.debug.ui.DebugPerspective">
+ <view
+ id="org.tizen.common.connection.ui.LogView"
+ ratio="1"
+ relationship="stack"
+ relative="org.eclipse.ui.views.TaskList">
+ </view>
+ <viewShortcut
+ id="org.tizen.common.connection.ui.LogView">
+ </viewShortcut>
+ </perspectiveExtension>
+ </extension>
<extension
id="org.tizen.common.connection.ui.filedrop"
- name="Connection Resource Drop"
+ name="%extension.name"
point="org.eclipse.ui.dropActions">
- <action
- class="org.tizen.common.connection.sdblib.dnd.FileEntryDropAdapter"
- id="org.tizen.common.connection.filedrop">
- </action>
-
+ <action
+ class="org.tizen.common.connection.sdblib.dnd.FileEntryDropAdapter"
+ id="org.tizen.common.connection.filedrop">
+ </action>
</extension>
<extension
point="org.eclipse.ui.propertyPages">
<page
class="org.tizen.common.connection.properties.ConnectionExplorerInfoPropertyPages"
id="org.tizen.common.connection.properties.Info"
- name="Info"
+ name="%properties.page.info"
nameFilter="*"
objectClass="org.tizen.sdblib.FileListingService$FileEntry">
</page>
<page
class="org.tizen.common.connection.properties.ConnectionExplorerPermissionPropertyPages"
id="org.tizen.common.connection.properties.Permission"
- name="Permission"
+ name="%properties.page.permission"
nameFilter="*"
objectClass="org.tizen.sdblib.FileListingService$FileEntry">
</page>
@@ -91,72 +129,56 @@
</extension>
<extension
point="org.eclipse.ui.commands">
+ <category
+ id="org.tizen.common.connection.category"
+ name="%command.category">
+ </category>
<command
+ categoryId="org.tizen.common.connection.category"
+ description="%command.delete.description"
id="org.tizen.common.connection.delete"
- name="deleteaction">
+ name="%command.delete.name">
</command>
<command
+ categoryId="org.tizen.common.connection.category"
+ description="%command.rename.description"
id="org.tizen.common.connection.rename"
- name="renameaction">
+ name="%command.rename.name">
</command>
<command
+ categoryId="org.tizen.common.connection.category"
+ description="%command.refresh.description"
id="org.tizen.common.connection.refresh"
- name="refreshaction">
+ name="%command.refresh.name">
</command>
<command
+ categoryId="org.tizen.common.connection.category"
+ description="%command.property.description"
id="org.tizen.common.connection.property"
- name="propertyaction">
+ name="%command.property.name">
</command>
</extension>
<extension
point="org.eclipse.ui.contexts">
<context
id="org.tizen.common.connection.delete.context"
- name="delete"
+ name="%context.delete.name"
parentId="org.eclipse.ui.contexts.window">
</context>
<context
id="org.tizen.common.connection.rename.context"
- name="rename"
+ name="%context.rename.name"
parentId="org.eclipse.ui.contexts.window">
</context>
<context
id="org.tizen.common.connection.refresh.context"
- name="refresh"
+ name="%context.refresh.name"
parentId="org.eclipse.ui.contexts.window">
</context>
<context
id="org.tizen.common.connection.property.context"
- name="property"
+ name="%context.properties.name"
parentId="org.eclipse.ui.contexts.window">
</context>
</extension>
-
- <extension
- point="org.eclipse.ui.views">
- <view
- name="Log"
- icon="icons/log/Log View.gif"
- category="org.tizen.nativeapp.viewCategory"
- class="org.tizen.common.connection.ui.LogView"
- id="org.tizen.common.connection.ui.LogView"
- allowMultiple = "true">
- </view>
- </extension>
-
- <extension
- point="org.eclipse.ui.perspectiveExtensions">
- <perspectiveExtension
- targetID="org.tizen.nativeapp.perspective">
- <view
- id="org.tizen.common.connection.ui.LogView"
- ratio="1"
- relationship="stack"
- relative="org.eclipse.ui.views.TaskList">
- </view>
- <viewShortcut
- id="org.tizen.common.connection.ui.LogView">
- </viewShortcut>
- </perspectiveExtension>
- </extension>
</plugin>
diff --git a/org.tizen.common.connection/src/org/tizen/common/connection/ConnectionPlugin.java b/org.tizen.common.connection/src/org/tizen/common/connection/ConnectionPlugin.java
index dc5cbf606..09d28fd8b 100644..100755
--- a/org.tizen.common.connection/src/org/tizen/common/connection/ConnectionPlugin.java
+++ b/org.tizen.common.connection/src/org/tizen/common/connection/ConnectionPlugin.java
@@ -1,36 +1,36 @@
/*
-* Common
-*
-* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
-*
-* Contact:
-* Hoon Kang <h245.kang@samsung.com>
-* Hyunsik Noh <hyunsik.noh@samsung.com>
-*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * Hoon Kang <h245.kang@samsung.com>
+ * Hyunsik Noh <hyunsik.noh@samsung.com>
+ *
* 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.
-*
-* Contributors:
-* - S-Core Co., Ltd
-*
-*/
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
package org.tizen.common.connection;
import java.io.File;
+import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
-import java.util.Properties;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExtensionRegistry;
@@ -40,11 +40,13 @@ import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;
import org.tizen.common.connection.debugtools.DebugTool;
-import org.tizen.common.properties.InstallPathConfig;
-
+import org.tizen.common.core.application.InstallPathConfig;
+import org.tizen.common.util.FileUtil;
+import org.tizen.common.util.HostUtil;
+import org.tizen.common.util.OSChecker;
+import org.tizen.common.util.log.Logger;
import org.tizen.sdblib.FileListingService.FileEntry;
import org.tizen.sdblib.IDevice;
-import org.tizen.sdblib.Log;
import org.tizen.sdblib.SmartDevelopmentBridge;
/**
@@ -52,23 +54,23 @@ import org.tizen.sdblib.SmartDevelopmentBridge;
*/
public class ConnectionPlugin extends AbstractUIPlugin {
- // The plug-in ID
- public static final String PLUGIN_ID = "org.tizen.common.connection"; //$NON-NLS-1$
- public static final String ID_LOGS_VIEW = "org.tizen.common.connection.ui.LogView"; //$NON-NLS-1$
- public static final String ID_CONNECTION_VIEW = "org.tizen.common.connection.ui.ConnectionExplorer";
- public static final String ID_DEBUGTOOLS_EXTENSION = "org.tizen.common.connection.tools"; //$NON-NLS-1$
-
- // The shared instance
- private static ConnectionPlugin plugin;
-
- private IDevice currentDevice;
- private final ArrayList<ISelectionListener> listeners = new ArrayList<ISelectionListener>();
-
- public int os;
- public static final int LINUX = 0;
- public static final int WINDOWS = 1;
-
- /**
+ // The plug-in ID
+ public static final String PLUGIN_ID = "org.tizen.common.connection"; //$NON-NLS-1$
+ public static final String ID_LOGS_VIEW = "org.tizen.common.connection.ui.LogView"; //$NON-NLS-1$
+ public static final String ID_CONNECTION_VIEW = "org.tizen.common.connection.ui.ConnectionExplorer";
+ public static final String ID_DEBUGTOOLS_EXTENSION = "org.tizen.common.connection.tools"; //$NON-NLS-1$
+
+ // The shared instance
+ private static ConnectionPlugin plugin;
+
+ private IDevice currentDevice;
+ private final ArrayList<ISelectionListener> listeners = new ArrayList<ISelectionListener>();
+
+ public int os;
+ public static final int LINUX = 0;
+ public static final int WINDOWS = 1;
+
+ /**
* Implements for FileEntry changed status.
*/
public interface ISelectionListener {
@@ -79,143 +81,210 @@ public class ConnectionPlugin extends AbstractUIPlugin {
*/
void selectionChanged(FileEntry selectedEntry);
}
-
- /**
- * The constructor
- */
- public ConnectionPlugin() {
- }
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
- */
- public void start(BundleContext context) throws Exception {
-
- super.start(context);
- plugin = this;
-
- Properties properties = System.getProperties();
- String value = properties.getProperty("os.name");
- if (value.contains("Windows"))
- this.os = WINDOWS;
- else
- this.os = LINUX;
-
- }
-
- public static synchronized List<DebugTool> getDebugTools(IDevice device) {
-
- List<DebugTool> toolLists = new ArrayList<DebugTool>();
-
- IExtensionRegistry x = RegistryFactory.getRegistry();
- IConfigurationElement[] ces = x.getConfigurationElementsFor(ID_DEBUGTOOLS_EXTENSION);
-
- for (int i = 0; i < ces.length; ++i) {
- IConfigurationElement ce = ces[i];
- if (ce.getName().equals("tools")) {
- String packagename = ce.getAttribute("packagename");
- if (packagename == null)
- continue;
- String sourcepath = ce.getAttribute("sourcepath");
- if (sourcepath == null)
- continue;
- String description = ce.getAttribute("description");
-
- Path sourcePath = new Path(InstallPathConfig.getSDKPath() + "/" + sourcepath);
-
- File packageList = new File(sourcePath.toOSString());
- for (File f : packageList.listFiles()) {
- if (f.getName().startsWith(packagename)) {
- String[] filename = f.getName().split("_");
- if (filename.length != 3)
- continue;
- String version = filename[1];
- String[] arch = filename[2].split("\\.");
- if (arch.length != 2)
- continue;
- String architecture = arch[0];
-
- if (device.isEmulator()) {
- if (!architecture.equals("i386"))
- continue;
- } else {
- if (!architecture.equals("armel"))
- continue;
- }
- DebugTool dt = new DebugTool();
- dt.setPackagename(packagename);
- dt.setBinaryname(f.getName());
- dt.setSourcepath(sourcepath);
- dt.setDescription(description);
- dt.setVersion(version);
- dt.setArchitecture(architecture);
- toolLists.add(dt);
- }
- }
- }
- }
- return toolLists;
- }
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
- */
- public void stop(BundleContext context) throws Exception {
- plugin = null;
- SmartDevelopmentBridge.disconnectBridge();
- super.stop(context);
- }
-
- /**
- * Returns the shared instance
- *
- * @return the shared instance
- */
- public static ConnectionPlugin getDefault() {
- return plugin;
- }
-
- public void setCurrentDevice(IDevice device) {
- currentDevice = device;
- }
-
- public IDevice getCurrentDevice() {
- return currentDevice;
- }
-
-
- public void addSelectionListener(ISelectionListener listener) {
- listeners.add(listener);
- }
-
- public void removeSelectionListener(ISelectionListener listener) {
- listeners.remove(listener);
- }
-
- public void notifySelectionListeners(FileEntry file) {
-
- ISelectionListener[] listenersCopy = listeners.toArray(
- new ISelectionListener[listeners.size()]);
-
- for (ISelectionListener listener : listenersCopy) {
- try {
- listener.selectionChanged(file);
- } catch (Exception e) {
- Log.e("ConnectionPlugin", e);
- }
- }
- }
-
- /**
- * 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 getImageDescriptorFromPlugin(String path) {
- return imageDescriptorFromPlugin(PLUGIN_ID, path);
- }
+
+ /**
+ * The constructor
+ */
+ public ConnectionPlugin() {
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
+ */
+ public void start(BundleContext context) throws Exception {
+
+ super.start(context);
+ plugin = this;
+
+ if (OSChecker.isWindows())
+ {
+ this.os = WINDOWS;
+ }
+ else
+ {
+ this.os = LINUX;
+ }
+
+ }
+
+ public static synchronized List<DebugTool> getDebugTools(IDevice device) {
+ List<DebugTool> toolLists = new ArrayList<DebugTool>();
+ IExtensionRegistry x = RegistryFactory.getRegistry();
+ IConfigurationElement[] ces = x.getConfigurationElementsFor(ID_DEBUGTOOLS_EXTENSION);
+
+ try {
+ for ( IConfigurationElement ce : ces ) {
+ if (ce.getName().equals("tools")) {
+ String packagename = ce.getAttribute("packagename");
+ if (packagename == null)
+ {
+ continue;
+ }
+ String sourcepath = ce.getAttribute("sourcepath");
+ if (sourcepath == null)
+ {
+ continue;
+ }
+ String description = ce.getAttribute("description");
+ Path sourcePath = new Path(InstallPathConfig.getPlatformVersionPath() + "/" + sourcepath);
+ File packageList = new File(sourcePath.toOSString());
+
+ DebugTool dt = null;
+ File[] packageFileList = packageList.listFiles();
+ if ( packageFileList == null ) {
+ continue;
+ }
+ for (File f : packageList.listFiles()) {
+ if ( DebugTool.RPM_PACKAGE_TYPE.equals(FileUtil.getFileExtension(f.getName())) ) {
+ dt = makeDebugToolFromRPM(f, device, packagename, sourcepath, description);
+ }
+ else {
+ dt = makeDebugToolFromTar(f, device, packagename, sourcepath, description);
+ }
+ if ( dt != null ) {
+ toolLists.add(dt);
+ }
+ }
+ }
+ }
+ } catch (Throwable e) {
+ Logger.error("Failed making DebugTool list for on-demand install", e);
+ }
+ return toolLists;
+ }
+
+ private static DebugTool makeDebugToolFromRPM( File f, IDevice device, String packagename, String sourcepath, String description ) {
+ String architecture = "";
+ String version = "";
+ String name = "";
+
+ // Not supported "RPM" at windows
+ // architecture = HostUtil.returnExecute( String.format( DebugTool.RPM_QUERY_COMMAND, "%{ARCH}", "-p " + f.getCanonicalPath()) );
+ // version = HostUtil.returnExecute( String.format( DebugTool.RPM_QUERY_COMMAND, "%{VERSION}", "-p " + f.getCanonicalPath()) );
+ // name = HostUtil.returnExecute( String.format( DebugTool.RPM_QUERY_COMMAND, "%{NAME}", "-p " + f.getCanonicalPath()) );
+
+ // RPM file format : gtest-0.0.8-7.1.armv7l.rpm
+ String[] fileSplit = f.getName().split("-");
+ if ( fileSplit.length < 3 ) {
+ return null;
+ }
+ name = fileSplit[0];
+ // version is not used
+ // FIXME : Unsafe way to extract the version.
+ version = fileSplit[1];
+ String[] archSplit = fileSplit[fileSplit.length-1].split("\\.");
+ architecture = archSplit[archSplit.length-2];
+
+ if ( !packagename.equals(name) ) {
+ return null;
+ }
+ if (device.isEmulator()) {
+ if ( !architecture.contains("86")) {
+ return null;
+ }
+ }
+ else {
+ if ( !architecture.contains("arm")) {
+ return null;
+ }
+ }
+
+ DebugTool dt = new DebugTool(packagename, f.getName(), sourcepath, version, description, architecture, DebugTool.RPM_PACKAGE_TYPE);
+
+ return dt;
+ }
+
+ private static DebugTool makeDebugToolFromTar( File f, IDevice device, String packagename, String sourcepath, String description ) {
+ String[] filename = f.getName().split("_");
+ if (filename.length != 3) {
+ return null;
+ }
+ if( !filename[0].equals(packagename)) {
+ return null;
+ }
+ String version = filename[1];
+ String[] arch = filename[2].split("\\.");
+ if (arch.length != 2) {
+ return null;
+ }
+ String architecture = arch[0];
+
+ if (device.isEmulator()) {
+ if (!architecture.equals("i386"))
+ {
+ return null;
+ }
+ } else {
+ if (!architecture.equals("armel"))
+ {
+ return null;
+ }
+ }
+
+ DebugTool dt = new DebugTool(packagename, f.getName(), sourcepath, version, description, architecture, "tar");
+ return dt;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
+ */
+ public void stop(BundleContext context) throws Exception {
+ plugin = null;
+ int deviceCnt = SmartDevelopmentBridge.getBridge().getDevices().length;
+ if (deviceCnt==0)
+ SmartDevelopmentBridge.disconnectBridge();
+ super.stop(context);
+ }
+
+ /**
+ * Returns the shared instance
+ *
+ * @return the shared instance
+ */
+ public static ConnectionPlugin getDefault() {
+ return plugin;
+ }
+
+ public void setCurrentDevice(IDevice device) {
+ currentDevice = device;
+ }
+
+ public IDevice getCurrentDevice() {
+ return currentDevice;
+ }
+
+ public void addSelectionListener(ISelectionListener listener) {
+ listeners.add(listener);
+ }
+
+ public void removeSelectionListener(ISelectionListener listener) {
+ listeners.remove(listener);
+ }
+
+ public void notifySelectionListeners(FileEntry file) {
+
+ ISelectionListener[] listenersCopy = listeners.toArray(
+ new ISelectionListener[listeners.size()]);
+
+ for (ISelectionListener listener : listenersCopy) {
+ try {
+ listener.selectionChanged(file);
+ } catch (Exception e) {
+ Logger.error("ConnectionPlugin", e);
+ }
+ }
+ }
+
+ /**
+ * 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 getImageDescriptorFromPlugin(String path) {
+ return imageDescriptorFromPlugin(PLUGIN_ID, path);
+ }
} \ No newline at end of file
diff --git a/org.tizen.common.connection/src/org/tizen/common/connection/ConnectionPluginSurrogate.java b/org.tizen.common.connection/src/org/tizen/common/connection/ConnectionPluginSurrogate.java
new file mode 100644
index 000000000..5cc6a6c13
--- /dev/null
+++ b/org.tizen.common.connection/src/org/tizen/common/connection/ConnectionPluginSurrogate.java
@@ -0,0 +1,44 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* Kangho Kim <kh5325.kim@samsung.com>
+* Hyeongseok Heo <hyeongseok.heo@samsung.com>
+* BonYong Lee <bonyong.lee@samsung.com>
+* Gyeongseok Seo <gyeongseok.seo@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+
+package org.tizen.common.connection;
+
+import org.tizen.common.Surrogate;
+
+/**
+ * The ConnectionPluginSurrogate class adapt ConnectionPlugin default object
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ * @author Gyeongseok Seo <gyeongseok.seo@samsung.com>
+ */
+public class ConnectionPluginSurrogate implements Surrogate<ConnectionPlugin> {
+ @Override
+ public ConnectionPlugin getAdapter() {
+ return ConnectionPlugin.getDefault();
+ }
+}
diff --git a/org.tizen.common.connection/src/org/tizen/common/connection/ddmuilib/FileDialogUtils.java b/org.tizen.common.connection/src/org/tizen/common/connection/ddmuilib/FileDialogUtils.java
index 9d220354d..a6af7cbbe 100644
--- a/org.tizen.common.connection/src/org/tizen/common/connection/ddmuilib/FileDialogUtils.java
+++ b/org.tizen.common.connection/src/org/tizen/common/connection/ddmuilib/FileDialogUtils.java
@@ -1,30 +1,32 @@
/*
-* Common
-*
-* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
-*
-* Contact:
-* Hoon Kang <h245.kang@samsung.com>
-* Yoonki Park <yoonki.park@samsung.com>
-*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * Hoon Kang <h245.kang@samsung.com>
+ * Yoonki Park <yoonki.park@samsung.com>
+ *
* 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.
-*
-* Contributors:
-* - S-Core Co., Ltd
-*
-*/
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
package org.tizen.common.connection.ddmuilib;
+import java.util.concurrent.atomic.AtomicInteger;
+
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.osgi.util.NLS;
@@ -32,147 +34,73 @@ import org.eclipse.swt.SWT;
import org.eclipse.ui.PlatformUI;
import org.tizen.common.connection.explorer.Messages;
+public class FileDialogUtils
+{
+ public static int checkOverwrite(final String filename)
+ {
+ String message = NLS.bind(Messages.getString("FileDialogUtils.overwrite.message"), filename);
+ String[] labels = new String[] { IDialogConstants.YES_LABEL, IDialogConstants.YES_TO_ALL_LABEL, IDialogConstants.NO_LABEL,
+ IDialogConstants.CANCEL_LABEL };
+ int type = MessageDialog.QUESTION;
+ return openFileDialog(labels, message, type);
+ }
-public class FileDialogUtils {
- private static FileDialogUtils instance;
-
- private FileDialogUtils() { }
-
- public static FileDialogUtils getInstance() {
- if (instance == null)
- instance = new FileDialogUtils();
- return instance;
- }
-
- public int checkOverwrite(final String filename) {
- final int[] result = new int[1]; // using array since you can't change a final int
-
- Runnable query = new Runnable() {
- public void run() {
- int[] resultId = {
- IDialogConstants.YES_ID,
- IDialogConstants.YES_TO_ALL_ID,
- IDialogConstants.NO_ID,
- IDialogConstants.CANCEL_ID };
-
- String[] labels = new String[] {
- IDialogConstants.YES_LABEL,
- IDialogConstants.YES_TO_ALL_LABEL,
- IDialogConstants.NO_LABEL,
- IDialogConstants.CANCEL_LABEL };
-
- String msg = NLS.bind(Messages.getString("FileDialogUtils.overrite.message"), filename);
- MessageDialog dialog = new MessageDialog(
- PlatformUI.getWorkbench().getDisplay().getActiveShell(),
- Messages.getString("FileDialogUtils.overrite.title"),
- null, msg , MessageDialog.QUESTION, labels, 0);
- dialog.open();
- if (dialog.getReturnCode() == SWT.DEFAULT) {
- // A window close returns SWT.DEFAULT - mapped to a cancel
- result[0] = IDialogConstants.CANCEL_ID;
- } else {
- result[0] = resultId[dialog.getReturnCode()];
- }
- }
- };
-
- PlatformUI.getWorkbench().getDisplay().syncExec(query);
- return result[0];
- }
- public int confirmDelete(final String filename) {
- final int[] result = new int[1]; // using array since you can't change a final int
-
- Runnable query = new Runnable() {
- public void run() {
- int[] resultId = {
- IDialogConstants.YES_ID,
- IDialogConstants.CANCEL_ID };
-
- String[] labels = new String[] {
- IDialogConstants.YES_LABEL,
- IDialogConstants.CANCEL_LABEL };
-
- String msg = NLS.bind(Messages.getString("FileDialogUtils.delete.message"), filename);
- MessageDialog dialog = new MessageDialog(
- PlatformUI.getWorkbench().getDisplay().getActiveShell(),
- Messages.getString("FileDialogUtils.delete.title"),
- null, msg , MessageDialog.QUESTION, labels, 0);
- dialog.open();
- if (dialog.getReturnCode() == SWT.DEFAULT) {
- // A window close returns SWT.DEFAULT - mapped to a cancel
- result[0] = IDialogConstants.CANCEL_ID;
- } else {
- result[0] = resultId[dialog.getReturnCode()];
- }
- }
- };
-
- PlatformUI.getWorkbench().getDisplay().syncExec(query);
- return result[0];
- }
-
- public int checkFileOverwrite(final String filename) {
- final int[] result = new int[1]; // using array since you can't change a final int
-
- Runnable query = new Runnable() {
- public void run() {
- int[] resultId = {
- IDialogConstants.OK_ID,
- IDialogConstants.CANCEL_ID };
+ public static int confirmDelete(final String filename)
+ {
+ String message = NLS.bind(Messages.getString("FileDialogUtils.delete.message"), filename);
+ String[] labels = new String[] { IDialogConstants.OK_LABEL, IDialogConstants.CANCEL_LABEL };
+ int type = MessageDialog.QUESTION;
+ return openFileDialog(labels, message, type);
+ }
- String[] labels = new String[] {
- IDialogConstants.OK_LABEL,
- IDialogConstants.CANCEL_LABEL };
-
- String msg = NLS.bind(Messages.getString("FileDialogUtils.overrite.message"), filename);
- MessageDialog dialog = new MessageDialog(
- PlatformUI.getWorkbench().getDisplay().getActiveShell(),
- Messages.getString("FileDialogUtils.overrite.title"),
- null, msg , MessageDialog.QUESTION, labels, 0);
- dialog.open();
- if (dialog.getReturnCode() == SWT.DEFAULT) {
- // A window close returns SWT.DEFAULT - mapped to a cancel
- result[0] = IDialogConstants.CANCEL_ID;
- } else {
- result[0] = resultId[dialog.getReturnCode()];
- }
- }
- };
+ public static int allowFileOverwrite(final String filename)
+ {
+ String message = NLS.bind(Messages.getString("FileDialogUtils.overwrite.message"), filename);
+ String[] labels = new String[] { IDialogConstants.OK_LABEL, IDialogConstants.CANCEL_LABEL };
+ int type = MessageDialog.QUESTION;
+ return openFileDialog(labels, message, type);
+ }
- PlatformUI.getWorkbench().getDisplay().syncExec(query);
- return result[0];
- }
-
- public int checkTabName(final String filename) {
- final int[] result = new int[1]; // using array since you can't change a final int
+ public static int checkTabName(final String filename)
+ {
+ String message = NLS.bind(Messages.getString("FileDialogUtils.tabName.message"), filename);
+ String[] labels = new String[] { IDialogConstants.OK_LABEL };
+ int type = MessageDialog.ERROR;
+ return openFileDialog(labels, message, type);
+ }
- Runnable query = new Runnable() {
- public void run() {
- int[] resultId = {
- IDialogConstants.OK_ID
- };
+ public static void notifyDuplication(final String filename)
+ {
+ String message = NLS.bind(Messages.getString("FileDialogUtils.duplicate.message"), filename);
+ String[] labels = new String[] { IDialogConstants.OK_LABEL };
+ int type = MessageDialog.ERROR;
+ openFileDialog(labels, message, type);
+ }
- String[] labels = new String[] {
- IDialogConstants.OK_LABEL
- };
-
- String msg = NLS.bind(Messages.getString("FileDialogUtils.tabName.message"), filename);
- MessageDialog dialog = new MessageDialog(
- PlatformUI.getWorkbench().getDisplay().getActiveShell(),
- Messages.getString("FileDialogUtils.tabName.title"),
- null, msg , MessageDialog.ERROR, labels, 0);
- dialog.open();
- if (dialog.getReturnCode() == SWT.DEFAULT) {
- // A window close returns SWT.DEFAULT - mapped to a cancel
- result[0] = IDialogConstants.CANCEL_ID;
- } else {
- result[0] = resultId[dialog.getReturnCode()];
- }
- }
- };
+ private static int openFileDialog(final String[] labels, final String message, final int type)
+ {
+ final AtomicInteger resultAtomicInteger = new AtomicInteger();
+ Runnable query = new Runnable()
+ {
+ @Override
+ public void run()
+ {
+ String title = Messages.getString("FileDialogUtils.message.title");
+ MessageDialog dialog = new MessageDialog(PlatformUI.getWorkbench().getDisplay().getActiveShell(),
+ title, null, message, type, labels, 0);
+ dialog.open();
+ if (dialog.getReturnCode() == SWT.DEFAULT)
+ {
+ // A window close returns SWT.DEFAULT - mapped to a cancel
+ resultAtomicInteger.set(IDialogConstants.CANCEL_ID);
+ } else
+ {
+ resultAtomicInteger.set(dialog.getReturnCode());
+ }
+ }
+ };
- PlatformUI.getWorkbench().getDisplay().syncExec(query);
- return result[0];
- }
-
-}
+ PlatformUI.getWorkbench().getDisplay().syncExec(query);
+ return resultAtomicInteger.get();
+ }
+} \ No newline at end of file
diff --git a/org.tizen.common.connection/src/org/tizen/common/connection/debugtools/DebugTool.java b/org.tizen.common.connection/src/org/tizen/common/connection/debugtools/DebugTool.java
index 6ed16fdbb..24e52f912 100644
--- a/org.tizen.common.connection/src/org/tizen/common/connection/debugtools/DebugTool.java
+++ b/org.tizen.common.connection/src/org/tizen/common/connection/debugtools/DebugTool.java
@@ -1,85 +1,104 @@
/*
-* Common
-*
-* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
-*
-* Contact:
-* Hoon Kang <h245.kang@samsung.com>
-* YoonKi Park <yoonki.park@samsung.com>
-*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * Hoon Kang <h245.kang@samsung.com>
+ * YoonKi Park <yoonki.park@samsung.com>
+ *
* 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.
-*
-* Contributors:
-* - S-Core Co., Ltd
-*
-*/
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
package org.tizen.common.connection.debugtools;
-import org.tizen.common.properties.InstallPathConfig;
+import org.tizen.common.TizenPlatformConstants;
+import org.tizen.common.core.application.InstallPathConfig;
public class DebugTool {
- public static final String CONTROL_EXTENSION = ".control";
- public static final String TOOLS_TARGET_PATH = "/home/developer/sdk_tools";
- public static final String TOOLS_HOST_PATH = InstallPathConfig.getSDKPath();
-
- private String binaryname;
- private String packagename;
- private String sourcepath;
- private String architecture;
- private String description;
- private String version;
-
- public DebugTool() {
-
- }
- public String getBinaryname() {
- return binaryname;
- }
- public String getControlFile() {
- return "." + this.packagename + CONTROL_EXTENSION;
- }
- public String getVersion() {
- return version;
- }
- public void setVersion(String pVersion) {
- version = pVersion;
- }
- public void setBinaryname(String pBinaryname) {
- binaryname = pBinaryname;
- }
- public String getPackagename() {
- return packagename;
- }
- public void setPackagename(String pPackagename) {
- packagename = pPackagename;
- }
- public String getSourcepath() {
- return sourcepath;
- }
- public void setSourcepath(String pSourcepath) {
- sourcepath = pSourcepath;
- }
- public String getArchitecture() {
- return architecture;
- }
- public void setArchitecture(String pArchitecture) {
- architecture = pArchitecture;
- }
- public String getDescription() {
- return description;
- }
- public void setDescription(String pDescription) {
- description = pDescription;
- }
-
+ public static final String TOOLS_HOST_PATH = InstallPathConfig.getPlatformVersionPath();
+ public static final String RPM_QUERY_COMMAND = "rpm -q --queryformat=%s %s";
+ public static final String RPM_PACKAGE_TYPE = "rpm";
+ public static final String RPM_INSTALL_COMMAND = "rpm -i %s";
+ public static final String RPM_UPGRADE_COMMAND = "rpm -U %s";
+
+ private String binaryname;
+ private String packagename;
+ private String sourcepath;
+ private String architecture;
+ private String description;
+ private String version;
+ private String packagetype;
+
+ public DebugTool() {
+
+ }
+ public DebugTool(String packagename, String binaryname, String sourcepath, String version, String desc, String arch, String type) {
+ this.packagename = packagename;
+ this.binaryname = binaryname;
+ this.sourcepath = sourcepath;
+ this.version = version;
+ this.description = desc;
+ this.architecture = arch;
+ this.packagetype = type;
+ }
+ public String getBinaryname() {
+ return binaryname;
+ }
+ public String getControlFile() {
+ return "." + this.packagename + TizenPlatformConstants.CONTROL_EXTENSION;
+ }
+ public String getVersion() {
+ return version;
+ }
+ public void setVersion(String pVersion) {
+ version = pVersion;
+ }
+ public void setBinaryname(String pBinaryname) {
+ binaryname = pBinaryname;
+ }
+ public String getPackagename() {
+ return packagename;
+ }
+ public void setPackagename(String pPackagename) {
+ packagename = pPackagename;
+ }
+ public String getSourcepath() {
+ return sourcepath;
+ }
+ public void setSourcepath(String pSourcepath) {
+ sourcepath = pSourcepath;
+ }
+ public String getArchitecture() {
+ return architecture;
+ }
+ public void setArchitecture(String pArchitecture) {
+ architecture = pArchitecture;
+ }
+ public String getDescription() {
+ return description;
+ }
+ public void setDescription(String pDescription) {
+ description = pDescription;
+ }
+ public void setPackagetype(String packagetype) {
+ this.packagetype = packagetype;
+ }
+ public String getPackagetype() {
+ return packagetype;
+ }
+
}
diff --git a/org.tizen.common.connection/src/org/tizen/common/connection/debugtools/ToolsInstall.java b/org.tizen.common.connection/src/org/tizen/common/connection/debugtools/ToolsInstall.java
index c62827865..75f7af0c3 100644..100755
--- a/org.tizen.common.connection/src/org/tizen/common/connection/debugtools/ToolsInstall.java
+++ b/org.tizen.common.connection/src/org/tizen/common/connection/debugtools/ToolsInstall.java
@@ -1,35 +1,40 @@
/*
-* Common
-*
-* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
-*
-* Contact:
-* Hoon Kang <h245.kang@samsung.com>
-* YoonKi Park <yoonki.park@samsung.com>
-*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * Hoon Kang <h245.kang@samsung.com>
+ * YoonKi Park <yoonki.park@samsung.com>
+ * Gun Kim <gune.kim@samsung.com>
+ *
* 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.
-*
-* Contributors:
-* - S-Core Co., Ltd
-*
-*/
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
package org.tizen.common.connection.debugtools;
+import static org.tizen.common.util.CollectionUtil.isEmpty;
+import static org.tizen.common.util.IOUtil.tryClose;
+
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
+import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
@@ -41,284 +46,335 @@ import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
+import org.tizen.common.TizenPlatformConstants;
import org.tizen.common.connection.ConnectionPlugin;
-import org.tizen.common.log.Logger;
-
+import org.tizen.common.util.IOUtil;
+import org.tizen.common.util.SdbCommandUtil;
+import org.tizen.common.util.log.Logger;
import org.tizen.sdblib.IDevice;
-import org.tizen.sdblib.SdbCommandRejectedException;
import org.tizen.sdblib.SdbShellProcess;
-import org.tizen.sdblib.SyncService;
-import org.tizen.sdblib.SyncService.SyncResult;
-import org.tizen.sdblib.TimeoutException;
class PackageInstallMonitorDialog extends ProgressMonitorDialog {
- public PackageInstallMonitorDialog(Shell parent) {
- super(parent);
- int shellStyle = getShellStyle();
- shellStyle &= ~SWT.APPLICATION_MODAL;
- setShellStyle(shellStyle);
- }
+ public PackageInstallMonitorDialog(Shell parent) {
+ super(parent);
+ int shellStyle = getShellStyle();
+ shellStyle &= ~SWT.APPLICATION_MODAL;
+ setShellStyle(shellStyle);
+ }
}
class InstallProgress implements IRunnableWithProgress {
- private static final String CMD_RESULT_CHECK = "; echo $?";
-
- private IDevice device = null;
-
- IProgressMonitor monitor = null;
-
- private boolean checkDirectory(String dir) throws CoreException {
- String cmd = "ls " + dir + CMD_RESULT_CHECK;
- return checkExitCode(cmd, ToolsInstallMessages.CANNOT_CHECK_DIRECTORY);
- }
-
-
- private void makeDirectory(String dir) throws CoreException {
- String cmd = "mkdir -p -m 755 " + dir + CMD_RESULT_CHECK ;
- String msg = ToolsInstallMessages.CANNOT_CREATE_DIRECTORY;
-
- if (checkExitCode(cmd, msg) == false)
- installCoreException(msg, null);
- }
-
- private boolean checkExitCode( String cmd, String msg ) throws CoreException
- {
- boolean result = false;
- SdbShellProcess lsProc;
- BufferedReader br = null;
- try {
- lsProc = device.executeShellCommand(cmd);
- br = new BufferedReader(new InputStreamReader(
- lsProc.getInputStream()));
- String lsOut = null;
- while (null != (lsOut = br.readLine())) {
- if ("0".equals(lsOut)) {
- result = true;
- break;
- }
- }
- } catch (IOException e) {
- installCoreException(msg, e);
- Logger.error(msg, e);
- }finally
- {
- if( br != null )
- try {
- br.close();
- } catch (IOException e) {
- Logger.error("Error to close BufferedReader", e);
- }
- }
- return result;
- }
-
- private boolean isInstalled(DebugTool dt) throws CoreException {
- boolean ret = false;
- BufferedReader br = null;
- try {
-
- SdbShellProcess echoProc = device.executeShellCommand(
- "cat " + DebugTool.TOOLS_TARGET_PATH + "/" + dt.getControlFile() + CMD_RESULT_CHECK);
- br = new BufferedReader(new InputStreamReader(
- echoProc.getInputStream()));
-
- String lsOut = null;
- String oldVersion = null;
- while (null != (lsOut = br.readLine())) {
- //version:0.0.0
- if (lsOut.toLowerCase().startsWith("version:")) {
- oldVersion = lsOut.split(":")[1];
- }
-
- if ("0".equals(lsOut)) {
- String v1 = normalisedVersion(oldVersion, ".", 4);
- String v2 = normalisedVersion(dt.getVersion(), ".", 4);
- if (v2.compareTo(v1) > 0) {
- //TODO : do install and save!
- ret = false;
- } else { //same version
- ret = true;
- }
- break;
- } else
- ret = false;
- }
- } catch (IOException e) {
- installCoreException(ToolsInstallMessages.CANNOT_CHECK_INSTALLED, e);
- Logger.error(ToolsInstallMessages.CANNOT_CHECK_INSTALLED, e);
- } finally {
- if(br != null)
- try {
- br.close();
- } catch (IOException e) {
- Logger.error("Error to close BufferedReader", e);
- }
- }
- return ret;
-
- }
- private String normalisedVersion(String version, String sep, int maxWidth) {
- String[] split = Pattern.compile(sep, Pattern.LITERAL).split(version);
- StringBuilder sb = new StringBuilder();
- for (String s : split) {
- sb.append(String.format("%" + maxWidth + 's', s));
- }
- return sb.toString();
- }
-
- private boolean copyPackage(String source, String destination) {
- boolean pushResult = false;
- try {
- SyncService syncService = device.getSyncService();
- SyncResult pushSyncResult = syncService.pushFile(source, destination,
- SyncService.getNullProgressMonitor());
- if (SyncService.RESULT_OK == pushSyncResult.getCode()) {
- pushResult = true;
- }
- } catch (TimeoutException e) {
- return false;
- } catch (SdbCommandRejectedException e) {
- return false;
- } catch (IOException e) {
- return false;
- }
- return pushResult;
- }
-
- private final void installPackage(DebugTool tool) throws CoreException {
- String local = DebugTool.TOOLS_HOST_PATH + "/" + tool.getSourcepath() + "/" + tool.getBinaryname();
- String remote = DebugTool.TOOLS_TARGET_PATH + "/" + tool.getBinaryname();
-
- // delete old version
- try {
- device.executeShellCommand(
- "cd " + DebugTool.TOOLS_TARGET_PATH + " && rm " + tool.getControlFile());
- } catch (IOException e) {
- installCoreException(ToolsInstallMessages.CANNOT_REMOVE_CONTROLFILE, e);
- Logger.error(ToolsInstallMessages.CANNOT_REMOVE_CONTROLFILE, e);
- }
-
-
- boolean isCopied = copyPackage(local, remote);
- monitor.worked(5);
- if (isCopied) {
- try {
- //make one string command for sequential executing
- device.executeShellCommand(
- "rm -rf " + DebugTool.TOOLS_TARGET_PATH + "/" + tool.getPackagename() + ";"
- + "cd " + DebugTool.TOOLS_TARGET_PATH + " && tar -xzf " + tool.getBinaryname() + ";"
- + "echo 'version:" + tool.getVersion() + "' >" + DebugTool.TOOLS_TARGET_PATH + "/" + tool.getControlFile() + ";"
- + "cd " + DebugTool.TOOLS_TARGET_PATH + " && rm " + tool.getBinaryname());
-
- } catch (IOException e) {
- Logger.error("Error after copied " + tool.getPackagename() , e);
- }
- }
- }
-
- @Override
- public void run(IProgressMonitor pMonitor) throws InvocationTargetException, InterruptedException {
- final List<DebugTool> debugTools = ConnectionPlugin.getDebugTools(device);
-
- if (debugTools == null || debugTools.size() == 0)
- return;
- boolean isInstalled = false;
- for (int i = 0; i < debugTools.size(); i++) {
- DebugTool dt = (DebugTool) debugTools.get(i);
- try {
- isInstalled = isInstalled(dt);
- } catch (CoreException e) {
- Logger.error("Error to check installed", e);
- }
- if (isInstalled == false)
- break;
- }
- if (isInstalled)
- return;
-
- this.monitor = pMonitor;
-
- pMonitor.beginTask(ToolsInstallMessages.DIALOG_INITILIZE, 100);
- //monitor.subTask("Prepare install");
-
- // check directory exist
- try {
- if (!checkDirectory(DebugTool.TOOLS_TARGET_PATH))
- makeDirectory(DebugTool.TOOLS_TARGET_PATH);
- } catch (CoreException e) {
- Logger.error("Error to check or make directory", e);
- }
-
- pMonitor.worked(10);
-
- // get package list to install
-
- pMonitor.worked(15);
-
- // install loop (cp, tar)
- for (int i=0 ; i<debugTools.size(); i++) {
- final DebugTool dt = (DebugTool)debugTools.get(i);
-
- if (device.isEmulator()) {
- if (!dt.getArchitecture().equals("i386"))
- continue;
- }
- else {
- if (!dt.getArchitecture().equals("armel"))
- continue;
- }
- Thread thread = new Thread(null, new Runnable() {
-
- @Override
- public void run() {
- try {
- installPackage(dt);
- } catch (CoreException e) {
- Logger.error("Error to install tools", e);
- }
- }
- }, "package check and install");
- thread.start();
- }
- pMonitor.done();
- }
-
- public void setDevice(IDevice pDevice) {
- device = pDevice;
- }
-
- private void installCoreException(String message, Throwable exception) throws CoreException {
+ private static final String CMD_RESULT_CHECK = "; echo $?";
+ private static final String CMD_TAR_INSTALL =
+ "rm -rf " + TizenPlatformConstants.TOOLS_TARGET_PATH + "/%s && " + // remove old version package
+ "cd " + TizenPlatformConstants.TOOLS_TARGET_PATH + " && " + // move to directory for on-demand
+ "tar -xzf %s && " + // install new version package
+ "echo 'version:%s'>" + TizenPlatformConstants.TOOLS_TARGET_PATH + "/%s && " + // create control file
+ "rm -f " + TizenPlatformConstants.TOOLS_TARGET_PATH + "/%s"; // remove package.tar
+
+
+ private IDevice device = null;
+
+ IProgressMonitor monitor = null;
+
+ private boolean checkDirectory(String dir) throws CoreException {
+ String cmd = "ls " + dir + CMD_RESULT_CHECK;
+ return checkExitCode(cmd, ToolsInstallMessages.CANNOT_CHECK_DIRECTORY);
+ }
+
+
+ private void makeDirectory(String dir) throws CoreException {
+ String cmd = "mkdir -p -m 755 " + dir + CMD_RESULT_CHECK ;
+ String msg = ToolsInstallMessages.CANNOT_CREATE_DIRECTORY;
+
+ if (checkExitCode(cmd, msg) == false)
+ {
+ installCoreException(msg, null);
+ }
+ }
+
+ private boolean checkExitCode( String cmd, String msg ) throws CoreException
+ {
+ boolean result = false;
+ SdbShellProcess lsProc;
+ BufferedReader br = null;
+ try {
+ lsProc = device.executeShellCommand(cmd);
+ br = new BufferedReader(new InputStreamReader(
+ lsProc.getInputStream()));
+ String lsOut = null;
+ while (null != (lsOut = br.readLine())) {
+ if ("0".equals(lsOut)) {
+ result = true;
+ break;
+ }
+ }
+ } catch (IOException e) {
+ installCoreException(msg, e);
+ Logger.error(msg, e);
+ }finally
+ {
+ tryClose( br );
+ }
+ return result;
+ }
+
+ private boolean isInstalled(DebugTool dt) throws CoreException {
+ boolean ret = false;
+ BufferedReader br = null;
+ try {
+
+ SdbShellProcess echoProc = device.executeShellCommand(
+ "cat " + TizenPlatformConstants.TOOLS_TARGET_PATH + "/" + dt.getControlFile() + CMD_RESULT_CHECK);
+ br = new BufferedReader(new InputStreamReader(
+ echoProc.getInputStream()));
+
+ String lsOut = null;
+ String oldVersion = null;
+ while (null != (lsOut = br.readLine())) {
+ //version:0.0.0
+ if (lsOut.toLowerCase().startsWith("version:")) {
+ oldVersion = lsOut.split(":")[1];
+ }
+
+ if ("0".equals(lsOut)) {
+ String v1 = normalisedVersion(oldVersion, ".", 4);
+ String v2 = normalisedVersion(dt.getVersion(), ".", 4);
+ if (v2.compareTo(v1) > 0) {
+ //TODO : do install and save!
+ ret = false;
+ } else { //same version
+ ret = true;
+ }
+ break;
+ } else
+ {
+ ret = false;
+ }
+ }
+ } catch (IOException e) {
+ installCoreException(ToolsInstallMessages.CANNOT_CHECK_INSTALLED, e);
+ Logger.error(ToolsInstallMessages.CANNOT_CHECK_INSTALLED, e);
+ } finally {
+ tryClose( br );
+ }
+ return ret;
+
+ }
+ private String normalisedVersion(String version, String sep, int maxWidth) {
+ String[] split = Pattern.compile(sep, Pattern.LITERAL).split(version);
+ StringBuilder sb = new StringBuilder();
+ for (String s : split) {
+ sb.append(String.format("%" + maxWidth + 's', s));
+ }
+ return sb.toString();
+ }
+
+ @Override
+ public void run(IProgressMonitor pMonitor) throws InvocationTargetException, InterruptedException {
+ final List<DebugTool> allDebugTools = ConnectionPlugin.getDebugTools(device);
+ List<DebugTool> installDebugTools = new ArrayList<DebugTool>();
+
+ if ( isEmpty( allDebugTools ) )
+ {
+ return;
+ }
+ boolean isInstalled = false;
+ for ( DebugTool dt : allDebugTools ) {
+ try {
+ isInstalled = isInstalled(dt);
+ } catch (CoreException e) {
+ Logger.error("Error to check installed", e);
+ }
+ if (isInstalled == false) {
+ installDebugTools.add(dt);
+ }
+ }
+ if ( installDebugTools.isEmpty() ) {
+ return;
+ }
+
+ this.monitor = pMonitor;
+
+ pMonitor.beginTask(ToolsInstallMessages.DIALOG_INITILIZE, 100);
+ //monitor.subTask("Prepare install");
+
+ // check directory exist
+ try {
+ if (!checkDirectory(TizenPlatformConstants.TOOLS_TARGET_PATH))
+ makeDirectory(TizenPlatformConstants.TOOLS_TARGET_PATH);
+ } catch (CoreException e) {
+ Logger.error("Error to check or make directory", e);
+ }
+
+ pMonitor.worked(10);
+
+ // get package list to install
+
+ pMonitor.worked(15);
+ String threadName = "";
+ // install loop (cp, tar)
+ for ( DebugTool dt : installDebugTools ) {
+ if (device.isEmulator()) {
+ if (!dt.getArchitecture().contains("86"))
+ continue;
+ }
+ else {
+ if (!dt.getArchitecture().contains("arm"))
+ continue;
+ }
+
+ threadName = "OnDemandInstallThread-" + dt.getPackagename();
+ Runnable r = new OnDemandInstall(dt);
+ Thread t = new Thread(r, threadName);
+ t.start();
+ }
+ pMonitor.done();
+ }
+
+ public void setDevice(IDevice pDevice) {
+ device = pDevice;
+ }
+
+ private boolean copyPackage(String source, String destination) {
+ return SdbCommandUtil.filePush(device, source, destination);
+ }
+
+ private final void installTarPackage(DebugTool tool) throws CoreException {
+ String local = DebugTool.TOOLS_HOST_PATH + "/" + tool.getSourcepath() + "/" + tool.getBinaryname();
+ String remote = TizenPlatformConstants.TOOLS_TARGET_PATH + "/" + tool.getBinaryname();
+
+ // delete old version
+ try {
+ device.executeShellCommand(
+ "cd " + TizenPlatformConstants.TOOLS_TARGET_PATH + " && rm " + tool.getControlFile());
+ } catch (IOException e) {
+ Logger.error("Failed delete old version ( " + tool.getPackagename() + " )");
+ return;
+ }
+
+ boolean isCopied = copyPackage(local, remote);
+ if (isCopied) {
+ try {
+ //make one string command for sequential executing
+ String installCommand = String.format(CMD_TAR_INSTALL, tool.getPackagename(),
+ tool.getBinaryname(),
+ tool.getVersion(), tool.getControlFile(),
+ tool.getBinaryname());
+ device.executeShellCommand(installCommand);
+
+ } catch (IOException e) {
+ Logger.error("Error after copied " + tool.getPackagename() , e);
+ }
+ }
+ else if (!isCopied) {
+ Logger.error("Failed file copy ( " + tool.getBinaryname() + " )");
+ }
+ }
+
+ private final void installRPMPackage(DebugTool tool) throws CoreException {
+ boolean isInstalled = false;
+ String local = DebugTool.TOOLS_HOST_PATH + "/" + tool.getSourcepath() + "/" + tool.getBinaryname();
+ String remote = TizenPlatformConstants.TOOLS_TARGET_PATH + "/" + tool.getBinaryname();
+
+ String packagename;
+
+ BufferedReader br = null;
+ SdbShellProcess sdbShell = null;
+ try {
+ sdbShell = device.executeShellCommand(String.format( DebugTool.RPM_QUERY_COMMAND, "\"%{NAME}\\n\"", tool.getPackagename()));
+ br = new BufferedReader(new InputStreamReader(sdbShell.getInputStream()));
+
+ while (null != (packagename = br.readLine())) {
+ if ( tool.getPackagename().equals(packagename)){
+ isInstalled = true;
+ break;
+ }
+ }
+ } catch (IOException e1) {
+ } finally {
+ IOUtil.tryClose(br);
+ if ( sdbShell != null ) {
+ sdbShell.destroy();
+ }
+ }
+
+ boolean isCopied = copyPackage(local, remote);
+ if (isCopied) {
+ String command = null;
+ if ( isInstalled ) {
+ command = String.format(DebugTool.RPM_UPGRADE_COMMAND, remote);
+ }
+ else {
+ command = String.format(DebugTool.RPM_INSTALL_COMMAND, remote);
+ }
+ try {
+ command = command + String.format("; rm -f %s", remote);
+ device.executeShellCommand(command);
+ } catch (IOException e) {
+ Logger.error("Error occurred while executing rpm command " + command , e);
+ }
+ }
+ else if (!isCopied) {
+ Logger.error("Failed file copy ( " + tool.getBinaryname() + " )");
+ }
+ }
+
+ private void installCoreException(String message, Throwable exception) throws CoreException {
Status status = new Status(Status.ERROR, ConnectionPlugin.PLUGIN_ID, message, exception);
throw new CoreException(status);
}
+
+ class OnDemandInstall implements Runnable {
+ private final DebugTool tool;
+
+ OnDemandInstall(final DebugTool tool) {
+ this.tool = tool;
+ }
+
+ @Override
+ public void run() {
+ try {
+ if ( DebugTool.RPM_PACKAGE_TYPE.equals(tool.getPackagetype()) ) {
+ installRPMPackage(tool);
+ }
+ else {
+ installTarPackage(tool);
+ }
+ } catch (CoreException e) {
+ Logger.error("Error to install tools", e);
+ }
+ }
+ }
}
public class ToolsInstall {
- public static void installPackages(IDevice device) {
- final IDevice tDevice = device;
-
- if (tDevice.isOffline()) {
- return;
- }
-
- Display.getDefault().asyncExec(new Runnable() {
- @Override
- public void run() {
- final PackageInstallMonitorDialog installDialog = new PackageInstallMonitorDialog(
- Display.getDefault().getActiveShell());
- try {
- InstallProgress installProgress = new InstallProgress();
- installProgress.setDevice(tDevice);
- installDialog.run(true, false, installProgress);
- } catch (InvocationTargetException e) {
- return;
- } catch (InterruptedException e) {
- return;
- }
- }
- });
-
- }
+ public static void installPackages(IDevice device) {
+ final IDevice tDevice = device;
+
+ if (tDevice.isOffline()) {
+ return;
+ }
+
+ Display.getDefault().asyncExec(new Runnable() {
+ @Override
+ public void run() {
+ final PackageInstallMonitorDialog installDialog = new PackageInstallMonitorDialog(
+ Display.getDefault().getActiveShell());
+ try {
+ InstallProgress installProgress = new InstallProgress();
+ installProgress.setDevice(tDevice);
+ installDialog.run(true, false, installProgress);
+ } catch (InvocationTargetException e) {
+ Logger.error("Failed on-demand install", e);
+ return;
+ } catch (InterruptedException e) {
+ Logger.error("Failed on-demand install", e);
+ return;
+ }
+ }
+ });
+ }
}
diff --git a/org.tizen.common.connection/src/org/tizen/common/connection/debugtools/ToolsInstallMessages.properties b/org.tizen.common.connection/src/org/tizen/common/connection/debugtools/ToolsInstallMessages.properties
index 5d8397958..f192516cf 100644
--- a/org.tizen.common.connection/src/org/tizen/common/connection/debugtools/ToolsInstallMessages.properties
+++ b/org.tizen.common.connection/src/org/tizen/common/connection/debugtools/ToolsInstallMessages.properties
@@ -1,8 +1,6 @@
-
-DIALOG_INITILIZE=Connection Explorer is initializing now. It might take few minutes.
+DIALOG_INITILIZE=Connection Explorer is initializing. It can take a few minutes.
CANNOT_CREATE_DIRECTORY=Cannot create sdk tools directory
CANNOT_CHECK_DIRECTORY=Cannot check sdk tools directory
CANNOT_CHECK_INSTALLED=Cannot check installed tools
-CANNOT_COPY_FILE=Cannot copy file
-CANNOT_REMOVE_CONTROLFILE=Cannot copy file
-
+CANNOT_COPY_FILE=Cannot copy the file
+CANNOT_REMOVE_CONTROLFILE=Cannot delete the file
diff --git a/org.tizen.common.connection/src/org/tizen/common/connection/explorer/ConnectionExplorerContentProvider.java b/org.tizen.common.connection/src/org/tizen/common/connection/explorer/ConnectionExplorerContentProvider.java
index 4aa5e2d27..f469f27e5 100644
--- a/org.tizen.common.connection/src/org/tizen/common/connection/explorer/ConnectionExplorerContentProvider.java
+++ b/org.tizen.common.connection/src/org/tizen/common/connection/explorer/ConnectionExplorerContentProvider.java
@@ -1,152 +1,107 @@
/*
-* Common
-*
-* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
-*
-* Contact:
-* Hoon Kang <h245.kang@samsung.com>
-* Hyunsik Noh <hyunsik.noh@samsung.com>
-*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * Hoon Kang <h245.kang@samsung.com>
+ * Hyunsik Noh <hyunsik.noh@samsung.com>
+ *
* 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.
-*
-* Contributors:
-* - S-Core Co., Ltd
-*
-*/
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
package org.tizen.common.connection.explorer;
import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Tree;
-
import org.tizen.sdblib.FileListingService;
import org.tizen.sdblib.FileListingService.FileEntry;
-import org.tizen.sdblib.FileListingService.IListingReceiver;
import org.tizen.sdblib.IDevice;
import org.tizen.sdblib.SmartDevelopmentBridge;
-public class ConnectionExplorerContentProvider implements ITreeContentProvider {
-
- private TreeViewer viewer;
- private FileEntry rootEntry;
-
- private IListingReceiver listingReceiver = new IListingReceiver() {
- public void setChildren(final FileEntry entry, FileEntry[] children) {
- final Tree t = viewer.getTree();
- if (t != null && t.isDisposed() == false) {
- Display display = t.getDisplay();
- if (display.isDisposed() == false) {
- display.asyncExec(new Runnable() {
- public void run() {
- if (t.isDisposed() == false) {
- // refresh the entry.
- viewer.refresh(entry);
- viewer.setExpandedState(entry, true);
- }
- }
- });
- }
- }
- }
+public class ConnectionExplorerContentProvider implements ITreeContentProvider
+{
- public void refreshEntry(final FileEntry entry) {
- final Tree t = viewer.getTree();
- if (t != null && t.isDisposed() == false) {
- Display display = t.getDisplay();
- if (display.isDisposed() == false) {
- display.asyncExec(new Runnable() {
- public void run() {
- if (t.isDisposed() == false) {
- // refresh the entry.
- viewer.refresh(entry);
- }
- }
- });
- }
- }
- }
- };
+ @Override
+ public void dispose()
+ {
+ }
-
- @Override
- public void dispose() {
- }
+ @Override
+ public void inputChanged(Viewer pViewer, Object pOldInput, Object pNewInput)
+ {
+ }
- @Override
- public void inputChanged(Viewer pViewer, Object pOldInput, Object pNewInput) {
- if (pViewer instanceof TreeViewer) {
- viewer = (TreeViewer) pViewer;
- }
- if (pNewInput instanceof FileEntry) {
- rootEntry = (FileEntry) pNewInput;
- }
- }
-
- @Override
- public Object[] getChildren(Object arg0) {
- if (arg0 instanceof FileEntry) {
+ @Override
+ public Object[] getChildren(Object arg0)
+ {
+ if (arg0 instanceof FileEntry)
+ {
FileEntry parentEntry = (FileEntry) arg0;
+ Object[] newEntries = parentEntry.getFileListingService().getChildren(parentEntry, false, null);
- Object[] oldEntries = parentEntry.getCachedChildren();
- Object[] newEntries = parentEntry.getFileListingService().getChildren(parentEntry,
- true, listingReceiver);
-
- if (newEntries != null) {
+ if (newEntries != null)
+ {
return newEntries;
- } else {
- return oldEntries;
}
}
return new Object[0];
- }
+ }
- @Override
- public Object[] getElements(Object arg0) {
- IDevice[] devices = SmartDevelopmentBridge.getBridge().getDevices();
- FileEntry[] entries = new FileEntry[ devices.length ];
- for (int i = 0; i < devices.length; i++) {
- entries[i] = devices[i].getFileListingService().getRoot();
+ @Override
+ public Object[] getElements(Object arg0)
+ {
+ IDevice[] devices = SmartDevelopmentBridge.getBridge().getDevices();
+ FileEntry[] entries = new FileEntry[devices.length];
+ for (int i = 0; i < devices.length; i++)
+ {
+ entries[i] = devices[i].getFileListingService().getRoot();
}
return entries;
- }
+ }
- @Override
- public Object getParent(Object arg0) {
- if (arg0 instanceof FileEntry) {
+ @Override
+ public Object getParent(Object arg0)
+ {
+ if (arg0 instanceof FileEntry)
+ {
FileEntry entry = (FileEntry) arg0;
return entry.getParent();
}
return null;
- }
+ }
- @Override
- public boolean hasChildren(Object arg0) {
- if (arg0 instanceof FileEntry) {
- FileEntry entry = (FileEntry) arg0;
- if (entry.getType() == FileListingService.TYPE_DIRECTORY_LINK)
- return true;
- else if (entry.getType() == FileListingService.TYPE_LINK)
- return true;
- else if (entry.getType() == FileListingService.TYPE_DIRECTORY)
- return true;
- else if (entry.getType() == FileListingService.TYPE_ROOT_EMULATOR)
- return true;
- else if (entry.getType() == FileListingService.TYPE_ROOT_DEVICE)
- return true;
- }
- return false;
- }
-}
+ @Override
+ public boolean hasChildren(Object arg0)
+ {
+ if (arg0 instanceof FileEntry)
+ {
+ FileEntry entry = (FileEntry) arg0;
+ if (entry.getType() == FileListingService.TYPE_DIRECTORY_LINK)
+ return true;
+ else if (entry.getType() == FileListingService.TYPE_LINK)
+ return true;
+ else if (entry.getType() == FileListingService.TYPE_DIRECTORY)
+ return true;
+ else if (entry.getType() == FileListingService.TYPE_ROOT_EMULATOR)
+ return true;
+ else if (entry.getType() == FileListingService.TYPE_ROOT_DEVICE)
+ return true;
+ }
+ return false;
+ }
+} \ No newline at end of file
diff --git a/org.tizen.common.connection/src/org/tizen/common/connection/explorer/ConnectionExplorerLabelProvider.java b/org.tizen.common.connection/src/org/tizen/common/connection/explorer/ConnectionExplorerLabelProvider.java
index 3b8c5ca14..c9a59c4d9 100644..100755
--- a/org.tizen.common.connection/src/org/tizen/common/connection/explorer/ConnectionExplorerLabelProvider.java
+++ b/org.tizen.common.connection/src/org/tizen/common/connection/explorer/ConnectionExplorerLabelProvider.java
@@ -1,124 +1,161 @@
/*
-* Common
-*
-* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
-*
-* Contact:
-* Hoon Kang <h245.kang@samsung.com>
-* Hyunsik Noh <hyunsik.noh@samsung.com>
-*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * Hoon Kang <h245.kang@samsung.com>
+ * Hyunsik Noh <hyunsik.noh@samsung.com>
+ *
* 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.
-*
-* Contributors:
-* - S-Core Co., Ltd
-*
-*/
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
package org.tizen.common.connection.explorer;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Display;
-import org.tizen.common.connection.ddmuilib.ImageLoader;
-
+import org.tizen.common.connection.ConnectionPlugin;
+import org.tizen.common.util.SWTUtil;
import org.tizen.sdblib.FileListingService;
import org.tizen.sdblib.FileListingService.FileEntry;
import org.tizen.sdblib.IDevice;
-public class ConnectionExplorerLabelProvider implements ITableLabelProvider {
+public class ConnectionExplorerLabelProvider implements ITableLabelProvider
+{
+
+ private final Image fileImage;
+ private final Image folderImage;
+ private final Image fileLinkImage;
+ private final Image folderLinkImage;
+ private final Image otherImage;
+ private final Image emulatorImage;
+ private final Image deviceImage;
+ public static int index;
+
+ public ConnectionExplorerLabelProvider(Display display)
+ {
+
+ fileImage = ConnectionPlugin.getImageDescriptorFromPlugin("icons/file.gif").createImage();
+ folderImage = ConnectionPlugin.getImageDescriptorFromPlugin("icons/directory.gif")
+ .createImage();
+ fileLinkImage = ConnectionPlugin.getImageDescriptorFromPlugin("icons/file_link.gif")
+ .createImage();
+ folderLinkImage = ConnectionPlugin.getImageDescriptorFromPlugin("icons/directory_link.gif")
+ .createImage();
+ otherImage = ConnectionPlugin.getImageDescriptorFromPlugin("icons/file.gif").createImage();
+ emulatorImage = ConnectionPlugin.getImageDescriptorFromPlugin("icons/emulator.gif")
+ .createImage();
+ deviceImage = ConnectionPlugin.getImageDescriptorFromPlugin("icons/device.gif")
+ .createImage();
+ }
- private Image fileImage;
- private Image folderImage;
- private Image fileLinkImage;
- private Image folderLinkImage;
- private Image otherImage;
- private Image emulatorImage;
- private Image deviceImage;
- public static int index;
-
- public ConnectionExplorerLabelProvider(Display display) {
- ImageLoader loader = ImageLoader.getDdmUiLibLoader();
-
- fileImage = loader.loadImage("file.gif", display);
- folderImage = loader.loadImage("directory.gif", display);
- fileLinkImage = loader.loadImage("file_link.gif", display);
- folderLinkImage = loader.loadImage("directory_link.gif", display);
- otherImage = loader.loadImage("file.gif", display);
- emulatorImage = loader.loadImage("emulator.gif", display);
- deviceImage = loader.loadImage("device.gif", display);
- }
+ @Override
+ public Image getColumnImage(Object element, int columnIndex)
+ {
+ if (columnIndex == 0)
+ {
+ if (element instanceof FileEntry)
+ {
+ FileEntry entry = (FileEntry) element;
+ switch (entry.getType())
+ {
+ case FileListingService.TYPE_FILE:
+ return fileImage;
+ case FileListingService.TYPE_LINK:
+ return fileLinkImage;
+ case FileListingService.TYPE_DIRECTORY:
+ return folderImage;
+ case FileListingService.TYPE_DIRECTORY_LINK:
+ return folderLinkImage;
+ case FileListingService.TYPE_ROOT_EMULATOR:
+ return emulatorImage;
+ case FileListingService.TYPE_ROOT_DEVICE:
+ return deviceImage;
+ default:
+ return otherImage;
+ }
+ }
+ }
+ return null;
+ }
- @Override
- public Image getColumnImage(Object element, int columnIndex) {
- if (columnIndex == 0) {
- if (element instanceof FileEntry) {
- FileEntry entry = (FileEntry) element;
- switch (entry.getType()) {
- case FileListingService.TYPE_FILE:
- return fileImage;
- case FileListingService.TYPE_LINK:
- return fileLinkImage;
- case FileListingService.TYPE_DIRECTORY:
- return folderImage;
- case FileListingService.TYPE_DIRECTORY_LINK:
- return folderLinkImage;
- case FileListingService.TYPE_ROOT_EMULATOR:
- return emulatorImage;
- case FileListingService.TYPE_ROOT_DEVICE:
- return deviceImage;
- default:
- return null;
- }
- }
+ @Override
+ public String getColumnText(Object element, int columnIndex)
+ {
+ if (element instanceof FileEntry)
+ {
+ FileEntry entry = (FileEntry) element;
- return otherImage;
- }
- return null;
- }
+ switch (columnIndex)
+ {
+ case 0:
+ if (entry.isRoot())
+ {
+ return getDeviceSerialWithName(entry);
+ } else
+ {
+ return entry.getName();
+ }
+ default:
+ return null;
+ }
+ } else if (element instanceof IDevice)
+ {
+ IDevice device = (IDevice) element;
+ return device.getDeviceName();
+ }
+ return null;
+ }
- @Override
- public String getColumnText(Object element, int columnIndex) {
- if (element instanceof FileEntry) {
- FileEntry entry = (FileEntry) element;
+ @Override
+ public void addListener(ILabelProviderListener listener)
+ {}
- switch (columnIndex) {
- case 0:
- return entry.getName();
- default:
- return null;
- }
- } else if (element instanceof IDevice) {
- IDevice device = (IDevice) element;
- return device.getSerialNumber();
- }
- return null;
- }
+ @Override
+ public void dispose()
+ {
+ SWTUtil.tryDispose(fileImage, folderImage, fileLinkImage, folderLinkImage, otherImage,
+ emulatorImage, deviceImage);
+ }
- @Override
- public void addListener(ILabelProviderListener listener) {
- }
+ @Override
+ public boolean isLabelProperty(Object element, String property)
+ {
+ return false;
+ }
- @Override
- public void dispose() {
- }
+ @Override
+ public void removeListener(ILabelProviderListener listener)
+ {}
- @Override
- public boolean isLabelProperty(Object element, String property) {
- return false;
- }
+ public static String getDeviceSerialWithName(IDevice device)
+ {
+ return combineSerialWithName(device.getSerialNumber(), device.getDeviceName());
+ }
- @Override
- public void removeListener(ILabelProviderListener listener) {
- }
+ public static String getDeviceSerialWithName(FileEntry entry)
+ {
+ return combineSerialWithName(entry.getFileListingService().getDevice().getSerialNumber(), entry.getName());
+ }
+
+ private static String combineSerialWithName(String serial, String name)
+ {
+ return String.format("%s (%s)", serial, name);
+ }
-}
+} \ No newline at end of file
diff --git a/org.tizen.common.connection/src/org/tizen/common/connection/explorer/ConnectionExplorerPanel.java b/org.tizen.common.connection/src/org/tizen/common/connection/explorer/ConnectionExplorerPanel.java
index 3f72e4746..2478c1dc4 100644..100755
--- a/org.tizen.common.connection/src/org/tizen/common/connection/explorer/ConnectionExplorerPanel.java
+++ b/org.tizen.common.connection/src/org/tizen/common/connection/explorer/ConnectionExplorerPanel.java
@@ -1,35 +1,35 @@
/*
-* Common
-*
-* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
-*
-* Contact:
-* Hoon Kang <h245.kang@samsung.com>
-* Hyunsik Noh <hyunsik.noh@samsung.com>
-*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * Hoon Kang <h245.kang@samsung.com>
+ * Hyunsik Noh <hyunsik.noh@samsung.com>
+ *
* 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.
-*
-* Contributors:
-* - S-Core Co., Ltd
-*
-*/
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
package org.tizen.common.connection.explorer;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
-import java.util.regex.Pattern;
+import java.util.List;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
@@ -59,14 +59,19 @@ import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.ToolItem;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
+import org.eclipse.ui.IWorkbenchPartSite;
+import org.eclipse.ui.console.MessageConsoleStream;
+import org.eclipse.ui.dialogs.PropertyDialogAction;
import org.eclipse.ui.part.PluginTransfer;
import org.eclipse.ui.part.PluginTransferData;
+import org.tizen.common.TizenPlatformConstants;
import org.tizen.common.connection.ConnectionPlugin;
import org.tizen.common.connection.ConnectionPlugin.ISelectionListener;
import org.tizen.common.connection.ddmuilib.DdmUiPreferences;
@@ -74,13 +79,14 @@ import org.tizen.common.connection.ddmuilib.FileDialogUtils;
import org.tizen.common.connection.ddmuilib.Panel;
import org.tizen.common.connection.ddmuilib.SyncProgressMonitor;
import org.tizen.common.connection.ddmuilib.TableHelper;
-import org.tizen.common.connection.ddmuilib.console.DdmConsole;
import org.tizen.common.connection.debugtools.ToolsInstall;
import org.tizen.common.connection.sdblib.dnd.FileEntryTransfer;
-import org.tizen.common.console.AnsicodeAdapter;
-import org.tizen.common.log.Logger;
-
-import org.tizen.sdblib.FileListingService;
+import org.tizen.common.connection.ui.ConnectionUIMessages;
+import org.tizen.common.ui.view.console.AnsicodeAdapter;
+import org.tizen.common.ui.view.console.ConsoleManager;
+import org.tizen.common.util.DialogUtil;
+import org.tizen.common.util.FilenameUtil;
+import org.tizen.common.util.log.Logger;
import org.tizen.sdblib.FileListingService.FileEntry;
import org.tizen.sdblib.IDevice;
import org.tizen.sdblib.MultiLineReceiver;
@@ -91,1028 +97,1132 @@ import org.tizen.sdblib.SyncService;
import org.tizen.sdblib.SyncService.ISyncProgressMonitor;
import org.tizen.sdblib.SyncService.SyncResult;
-public class ConnectionExplorerPanel extends Panel
- implements
- IDeviceChangeListener,
- IDebugBridgeChangeListener,
- ISelectionListener {
-
- private static final String DRAGACTIONID = "org.tizen.common.connection.filedrop";
- private static final String INVALID_FOR_FILENAME = ";";
-
- private static final String COLUMN_NAME = "name"; //$NON-NLS-1S
- private static final String CMD_RESULT_CHECK = "; echo $?";
-
- private Composite parent;
- private TreeViewer treeViewer;
- private Tree tree;
- private ConnectionExplorerContentProvider mContentProvider;
-
- private ToolItem pushToolItem;
- private ToolItem pullToolItem;
- private ToolItem emulStartToolItem;
-
- private MenuManager subMenu;
- private Action actionPush;
- private Action actionPull;
- private Action actionRefresh;
- private Action actionRename;
- private Action actionProperty;
- private Action actionDelete;
-
- private IDevice mCurrentDevice;
-
- private String defaultSave;
- // only use on linux system
- private static final String PATH_SEPARATOR = "/";
-
- private final ArrayList<IDevice> devicesToExpand = new ArrayList<IDevice>();
- private final ArrayList<IDevice> devicesList = new ArrayList<IDevice>();
- private FileEntry currentFileEntry;
-
- public ConnectionExplorerPanel() {
- }
-
-
- @Override
- protected Control createControl(Composite pParent) {
- parent = pParent;
- parent.setLayout(new FillLayout());
-
- tree = new Tree(parent, SWT.MULTI | SWT.FULL_SELECTION);
- tree.setHeaderVisible(true);
-
- IPreferenceStore store = DdmUiPreferences.getStore();
-
- TableHelper.createTreeColumn(tree, "FileEntry", SWT.LEFT,
- "abcdefghijklmnopqrstuvwzabcdefghijk", COLUMN_NAME, store); //$NON-NLS-1$
- tree.setHeaderVisible(true);
-
- treeViewer = new TreeViewer(tree);
- mContentProvider = new ConnectionExplorerContentProvider();
- treeViewer.setContentProvider(mContentProvider);
- treeViewer.setLabelProvider(new ConnectionExplorerLabelProvider(
- parent.getDisplay()));
-
- tree.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- notifyListeners();
- }
- });
-
- // setup drag listener
- treeViewer.addDragSupport(
- DND.DROP_MOVE | DND.DROP_COPY,
- new Transfer[]{PluginTransfer.getInstance(),
- FileEntryTransfer.getInstance()},
- new DragSourceListener() {
-
- @Override
- public void dragStart(DragSourceEvent e) {
-
- TreeItem[] items = tree.getSelection();
-
- for (int i = 0; i < items.length; i++) {
- Object data = items[i].getData();
- if (data instanceof FileEntry) {
- if (((FileEntry) data).isDirectory() == true || ((FileEntry) data).isRoot() == true) {
- e.doit = false;
- return;
- }
- }
- }
- e.doit = true;
- }
- @Override
- public void dragFinished(DragSourceEvent arg0) {
-
- }
-
- @Override
- public void dragSetData(DragSourceEvent e) {
- // get the selection
- TreeItem[] items = tree.getSelection();
- FileEntry[] entries = new FileEntry[items.length];
-
- for (int i = 0; i < items.length; i++) {
- Object data = items[i].getData();
- if (data instanceof FileEntry) {
- entries[i] = ((FileEntry) data);
- }
- }
-
- if (FileEntryTransfer.getInstance().isSupportedType(
- e.dataType)) {
- e.data = entries;
- } else if (PluginTransfer.getInstance()
- .isSupportedType(e.dataType)) {
- byte[] data = FileEntryTransfer.getInstance()
- .toByteArray(entries);
- e.data = new PluginTransferData(DRAGACTIONID, data);
- }
-
- }
- });
-
- // setup drop listener
- treeViewer.addDropSupport(DND.DROP_COPY | DND.DROP_MOVE,
- new Transfer[]{FileTransfer.getInstance()},
- new ViewerDropAdapter(treeViewer) {
- @Override
- public boolean performDrop(Object data) {
- // get the item on which we dropped the item(s)
- FileEntry target = (FileEntry) getCurrentTarget();
-
- // in case we drop at the same level as root
- if (target == null) {
- return false;
- }
-
- // if the target is not a directory, we get the parent
- // directory
- if (target.isDirectory() == false) {
- target = target.getParent();
- }
-
- if (target == null) {
- return false;
- }
-
- // get the list of files to drop
- String[] files = (String[]) data;
-
- // do the drop
- pushFiles(files, target);
-
- // we need to finish with a refresh
- refresh(target);
-
- return true;
- }
-
- @Override
- public boolean validateDrop(Object target, int operation,
- TransferData transferType) {
- if (target == null) {
- return false;
- }
-
- // convert to the real item
- FileEntry targetEntry = (FileEntry) target;
-
- // if the target is not a directory, we get the parent
- // directory
- if (targetEntry.isDirectory() == false) {
- target = targetEntry.getParent();
- }
-
- if (target == null) {
- return false;
- }
-
- return true;
- }
- });
-
- return tree;
- }
-
- public void setToolItems(ToolItem push, ToolItem pull, ToolItem start) {
- pushToolItem = push;
- pullToolItem = pull;
- emulStartToolItem = start;
- }
-
- public void setActions(MenuManager pSubMenu, Action pActionPush, Action pActionPull, Action pActionRefresh,
- Action pActionRename, Action pActionProperty, Action pActionDelete) {
- this.subMenu = pSubMenu;
- this.actionPush = pActionPush;
- this.actionPull = pActionPull;
- this.actionRefresh = pActionRefresh;
- this.actionRename = pActionRename;
- this.actionProperty = pActionProperty;
- this.actionDelete = pActionDelete;
- }
-
- @Override
- protected void postCreation() {
- ConnectionPlugin.getDefault().addSelectionListener(this);
- SmartDevelopmentBridge sdbBridge = SmartDevelopmentBridge.getBridge();
- SmartDevelopmentBridge.addDebugBridgeChangeListener(this);
- SmartDevelopmentBridge.addDeviceChangeListener(this);
-
- IDevice[] devices = null;
- if (sdbBridge != null) {
- devices = sdbBridge.getDevices();
- }
- if (devices != null && devices.length != 0) {
- for (IDevice device : devices) {
- this.deviceConnected(device);
- }
- }
- }
-
- /**
- * Sets the focus to the proper control inside the panel.
- */
- @Override
- public void setFocus() {
- tree.setFocus();
- }
-
- /**
- * Pull the current selection on the local drive. This method displays a
- * dialog box to let the user select where to store the file(s) and
- * folder(s).
- */
- public void pullSelection() {
- // get the selection
- TreeItem[] items = tree.getSelection();
-
- // name of the single file pull, or null if we're pulling a directory
- // or more than one object.
- String filePullName = null;
- FileEntry singleEntry = null;
-
- //Pull the single file
- if (items.length == 1) {
- singleEntry = (FileEntry) items[0].getData();
- if (singleEntry.getType() == FileListingService.TYPE_FILE) {
- filePullName = singleEntry.getName();
- }
- }
-
- // where do we save by default?
- String defaultPath = defaultSave;
- if (defaultPath == null) {
- defaultPath = System.getProperty("user.home"); //$NON-NLS-1$
- }
-
- if (filePullName != null) {
- FileDialog fileDialog = new FileDialog(parent.getShell(), SWT.SAVE);
-
- fileDialog.setText("Pull the Selection");
- fileDialog.setFileName(filePullName);
- fileDialog.setFilterPath(defaultPath);
-
- String fileName = fileDialog.open();
- if (fileName != null) {
- defaultSave = fileDialog.getFilterPath();
-
- pullFile(singleEntry, fileName);
- }
- } else {
- DirectoryDialog directoryDialog = new DirectoryDialog(
- parent.getShell(), SWT.SAVE);
-
- directoryDialog.setText("Pull the Selection");
- directoryDialog.setFilterPath(defaultPath);
-
- String directoryName = directoryDialog.open();
- if (directoryName != null) {
- pullSelection(items, directoryName);
- }
- }
- }
-
- /**
- * Push new file(s) and folder(s) into the current selection. Current
- * selection must be single item. If the current selection is not a
- * directory, the ` directory is used. This method displays a dialog to
- * let the user choose file to push to the device.
- */
- public void pushIntoSelection() {
- // get the name of the object we're going to pull
- TreeItem[] items = tree.getSelection();
-
- if (items.length == 0) {
- return;
- }
-
- FileDialog dlg = new FileDialog(parent.getShell(), SWT.OPEN);
- String fileName;
-
- dlg.setText("Push the Files");
-
- // There should be only one.
- FileEntry entry = (FileEntry) items[0].getData();
-
- String defaultPath = defaultSave;
- if (defaultPath == null) {
- defaultPath = System.getProperty("user.home"); //$NON-NLS-1$
- }
- dlg.setFilterPath(defaultPath);
-
- fileName = dlg.open();
- if (fileName != null) {
- defaultSave = dlg.getFilterPath();
-
- // we need to figure out the remote path based on the current
- // selection type.
- String remotePath;
- FileEntry toRefresh = entry;
- if (entry.isDirectory() || entry.isRoot()) {
- remotePath = entry.getFullPath();
- } else {
- toRefresh = entry.getParent();
- remotePath = toRefresh.getFullPath();
- }
-
- pushFile(fileName, remotePath);
- treeViewer.refresh(toRefresh);
- }
- }
-
- public void addNewFileSelection() {
- InputDialog addNewDialog = new InputDialog(Display.getCurrent()
- .getActiveShell(), "New File Resource", "New File Name: ", "",
- new FileNameValidator());
- if (addNewDialog.open() != Window.OK)
- return;
-
- String fullPath = currentFileEntry.getFullPath();
-
- TreeItem[] items = tree.getSelection();
-
- if (items.length != 1) {
- return;
- }
-
- final FileEntry parentEntry = ((FileEntry) items[0].getData())
- .getParent();
- // create the touch command
- String command = "touch " + fullPath + PATH_SEPARATOR + addNewDialog.getValue() + CMD_RESULT_CHECK; //$NON-NLS-1$
-
- try {
- mCurrentDevice.executeShellCommand(command,
- new MultiLineReceiver() {
-
- @Override
- public void processNewLines(String[] lines) {
- if(!lines[lines.length - 1].contains("0"))
- {
- StringBuilder sb = new StringBuilder();
- for (String line : lines) {
- line = AnsicodeAdapter.getStripAnsiString(line);
- sb.append(line);
-
- }
- Status status = new Status(IStatus.ERROR, "Add File Failed", 0,
- sb.toString() , null);
- ErrorDialog.openError(Display.getCurrent().getActiveShell(), "Add File Failed", "A file failed to be added", status);
-
-
- }
- }
- });
- } catch (IOException e) {
- Logger.error("failed to do add new file", e);
- throw new RuntimeException(e);
- }
- refresh(parentEntry);
- }
-
- public void addNewFolderSelection() {
- InputDialog addNewDialog = new InputDialog(Display.getCurrent()
- .getActiveShell(), "New Folder Resource", "New Folder Name: ",
- "", null);
- if (addNewDialog.open() != Window.OK)
- return;
- String fullPath = currentFileEntry.getFullPath();
-
- TreeItem[] items = tree.getSelection();
-
- if (items.length != 1) {
- return;
- }
-
- final FileEntry parentEntry = ((FileEntry) items[0].getData())
- .getParent();
- // create the mkdir command
- String command = "mkdir " + fullPath + PATH_SEPARATOR + addNewDialog.getValue() + CMD_RESULT_CHECK; //$NON-NLS-1$
- try {
- mCurrentDevice.executeShellCommand(command,
- new MultiLineReceiver() {
-
- @Override
- public void processNewLines(String[] lines) {
- if(!lines[lines.length - 1].contains("0"))
- {
- StringBuilder sb = new StringBuilder();
- for (String line : lines) {
- line = AnsicodeAdapter.getStripAnsiString(line);
- sb.append(line);
-
- }
- Status status = new Status(IStatus.ERROR, "Add Folder Failed", 0,
- sb.toString() , null);
- ErrorDialog.openError(Display.getCurrent().getActiveShell(), "Add Folder Failed", "A folder failed to be added", status);
- }
- }
- });
- } catch (IOException e) {
- Logger.error("failed to do add new folder", e);
- throw new RuntimeException(e);
- }
- refresh(parentEntry);
- }
-
- public void renameSelection() {
- InputDialog renameDialog = new InputDialog(Display.getCurrent()
- .getActiveShell(), "Rename Resource", "New name: ",
- currentFileEntry.getName(), new FileNameValidator());
- if (renameDialog.open() != Window.OK)
- return;
-
- String fullPath = currentFileEntry.getFullPath();
- int lastIndex = fullPath.lastIndexOf(PATH_SEPARATOR);
- String newPath = fullPath.substring(0, lastIndex) + PATH_SEPARATOR + renameDialog.getValue();
-
- TreeItem[] items = tree.getSelection();
-
- if (items.length != 1) {
- return;
- }
-
- final FileEntry parentEntry = ((FileEntry) items[0].getData())
- .getParent();
- // create the mv command
- String command = "mv " + fullPath + " " + newPath + CMD_RESULT_CHECK; //$NON-NLS-1$
-
- try {
- mCurrentDevice.executeShellCommand(command,
- new MultiLineReceiver() {
-
- @Override
- public void processNewLines(String[] lines) {
- if(!lines[lines.length - 1].contains("0"))
- {
- StringBuilder sb = new StringBuilder();
- for (String line : lines) {
- line = AnsicodeAdapter.getStripAnsiString(line);
- sb.append(line);
-
- }
- Status status = new Status(IStatus.ERROR, "Rename failed", 0,
- sb.toString() , null);
- ErrorDialog.openError(Display.getCurrent().getActiveShell(), "Rename failed", "A selection failed to be renamed",status);
- }
- }
- });
- } catch (IOException e) {
- Logger.error("failed to do rename", e);
- throw new RuntimeException(e);
- }
- refresh(parentEntry);
- }
-
- public void deleteSelection() {
- int ret = FileDialogUtils.getInstance().confirmDelete(
- currentFileEntry.getName());
- if (ret == IDialogConstants.CANCEL_ID)
- return;
-
- TreeItem[] items = tree.getSelection();
-
- for (TreeItem item : items) {
- final FileEntry entry = (FileEntry) item.getData();
- String command = null;
- // create the delete command
- if (entry.isDirectory()) {
- command = "rm -rf " + entry.getFullEscapedPath() + CMD_RESULT_CHECK; //$NON-NLS-1$
- } else {
- command = "rm " + entry.getFullEscapedPath() + CMD_RESULT_CHECK; //$NON-NLS-1$
- }
-
- try {
- mCurrentDevice.executeShellCommand(command,
- new MultiLineReceiver() {
-
- @Override
- public void processNewLines(String[] lines) {
- if(!lines[lines.length - 1].contains("0"))
- {
- StringBuilder sb = new StringBuilder();
- for (String line : lines) {
- line = AnsicodeAdapter.getStripAnsiString(line);
- sb.append(line);
- }
- Status status = new Status(IStatus.ERROR, "Delete Failed", 0,
- sb.toString() , null);
- ErrorDialog.openError(Display.getCurrent().getActiveShell(), "Delete failed", "A selection failed to be deleted", status);
- }
- }
- });
- } catch (IOException e) {
- Logger.error("failed to do delete", e);
- throw new RuntimeException(e);
-
- }
- refresh(entry.getParent());
- }
-
- }
-
- /**
- * Force a full refresh of the explorer.
- */
- public void refresh() {
- treeViewer.refresh(true);
- }
-
- /**
- * Sent when a new {@link SmartDevelopmentBridge} is started.
- * <p/>
- * This is sent from a non UI thread.
- *
- * @param bridge
- * the new {@link SmartDevelopmentBridge} object.
- *
- * @see IDebugBridgeChangeListener#serverChanged(SmartDevelopmentBridge)
- */
- public void bridgeChanged(final SmartDevelopmentBridge bridge) {
- if (tree.isDisposed() == false) {
- exec(new Runnable() {
- public void run() {
- if (tree.isDisposed() == false) {
- // set up the data source.
- treeViewer.setInput(bridge);
-
- } else {
- // tree is disposed, we need to do something.
- // lets remove ourselves from the listener.
- SmartDevelopmentBridge
- .removeDebugBridgeChangeListener(ConnectionExplorerPanel.this);
- SmartDevelopmentBridge
- .removeDeviceChangeListener(ConnectionExplorerPanel.this);
- }
- }
- });
- }
-
- // all current devices are obsolete
- synchronized (devicesToExpand) {
- devicesToExpand.clear();
- }
- }
-
- /**
- * Refresh an entry from a non ui thread.
- *
- * @param entry
- * the entry to refresh.
- */
- private void refresh(final FileEntry entry) {
- Display d = treeViewer.getTree().getDisplay();
- d.asyncExec(new Runnable() {
- public void run() {
- treeViewer.refresh(entry);
- }
- });
- }
- public void refreshSelection() {
- if (currentFileEntry == null)
- return;
- Display d = treeViewer.getTree().getDisplay();
- d.asyncExec(new Runnable() {
- public void run() {
- treeViewer.refresh(currentFileEntry);
- }
- });
- }
-
- /**
- * Pulls the selection from a device.
- *
- * @param items
- * the tree selection the remote file on the device
- * @param localDirector
- * the local directory in which to save the files.
- */
- private void pullSelection(TreeItem[] items, final String localDirectory) {
- try {
- final SyncService sync = mCurrentDevice.getSyncService();
- if (sync != null) {
- // make a list of the FileEntry.
- ArrayList<FileEntry> entries = new ArrayList<FileEntry>();
- for (TreeItem item : items) {
- Object data = item.getData();
- if (data instanceof FileEntry) {
- entries.add((FileEntry) data);
- }
- }
- final FileEntry[] entryArray = entries
- .toArray(new FileEntry[entries.size()]);
-
- // get a progress dialog
- new ProgressMonitorDialog(parent.getShell()).run(true, true,
- new IRunnableWithProgress() {
- public void run(IProgressMonitor monitor)
- throws InvocationTargetException,
- InterruptedException {
- // create a monitor wrapper around the jface
- // monitor
- SyncResult result = sync
- .pull(entryArray,
- localDirectory,
- (ISyncProgressMonitor) new SyncProgressMonitor(
- monitor,
- "Pulling file(s) from the device"));
-
- if (result.getCode() != SyncService.RESULT_OK) {
- DdmConsole.printErrorToConsole(String
- .format("Failed to pull selection: %1$s",
- result.getMessage()));
- }
- sync.close();
- }
- });
- }
- } catch (Exception e) {
- DdmConsole.printErrorToConsole("Failed to pull selection");
- DdmConsole.printErrorToConsole(e.getMessage());
- }
- }
-
- /**
- * Pulls a file from a device.
- *
- * @param remote
- * the remote file on the device
- * @param local
- * the destination filepath
- */
- private void pullFile(final FileEntry remote, final String local) {
- try {
- final SyncService sync = mCurrentDevice.getSyncService();
- if (sync != null) {
- new ProgressMonitorDialog(parent.getShell()).run(true, true,
- new IRunnableWithProgress() {
- public void run(IProgressMonitor monitor)
- throws InvocationTargetException,
- InterruptedException {
- SyncResult result = sync
- .pullFile(
- remote,
- local,
- (ISyncProgressMonitor) new SyncProgressMonitor(
- monitor,
- String.format(
- "Pulling %1$s from the device",
- remote.getName())));
- if (result.getCode() != SyncService.RESULT_OK) {
- DdmConsole.printErrorToConsole(String
- .format("Failed to pull %1$s: %2$s",
- remote, result.getMessage()));
- }
-
- sync.close();
- }
- });
- }
- } catch (Exception e) {
- DdmConsole.printErrorToConsole("Failed to pull selection");
- DdmConsole.printErrorToConsole(e.getMessage());
- }
- }
-
- /**
- * Pushes several files and directory into a remote directory.
- *
- * @param localFiles
- * @param remoteDirectory
- */
- private void pushFiles(final String[] localFiles,
- final FileEntry remoteDirectory) {
- try {
- final SyncService sync = mCurrentDevice.getSyncService();
- if (sync != null) {
- new ProgressMonitorDialog(parent.getShell()).run(true, true,
- new IRunnableWithProgress() {
- public void run(IProgressMonitor monitor)
- throws InvocationTargetException,
- InterruptedException {
- SyncResult result = sync
- .push(localFiles,
- remoteDirectory,
- (ISyncProgressMonitor) new SyncProgressMonitor(
- monitor,
- "Pushing file(s) to the device"));
- if (result.getCode() != SyncService.RESULT_OK) {
- DdmConsole.printErrorToConsole(String
- .format("Failed to push the items: %1$s",
- result.getMessage()));
- }
-
- sync.close();
- }
- });
- }
- } catch (Exception e) {
- DdmConsole.printErrorToConsole("Failed to push the items");
- DdmConsole.printErrorToConsole(e.getMessage());
- }
- }
-
- /**
- * Pushes a file on a device.
- *
- * @param local
- * the local file path of the file to push
- * @param remoteDirectory
- * the remote destination directory on the device
- */
- private void pushFile(final String local, final String remoteDirectory) {
- try {
- final SyncService sync = mCurrentDevice.getSyncService();
- if (sync != null) {
- new ProgressMonitorDialog(parent.getShell()).run(true, true,
- new IRunnableWithProgress() {
- public void run(IProgressMonitor monitor)
- throws InvocationTargetException,
- InterruptedException {
- // get the file name
- String[] segs = local.split(Pattern
- .quote(File.separator));
- String name = segs[segs.length - 1];
- String remoteFile = remoteDirectory + FileListingService.FILE_SEPARATOR + name;
-
- SyncResult result = sync
- .pushFile(
- local,
- remoteFile,
- (ISyncProgressMonitor) new SyncProgressMonitor(
- monitor,
- String.format(
- "Pushing %1$s to the device.",
- name)));
- if (result.getCode() != SyncService.RESULT_OK) {
- DdmConsole.printErrorToConsole(String
- .format("Failed to push %1$s on %2$s: %3$s",
- name, mCurrentDevice
- .getSerialNumber(),
- result.getMessage()));
- }
-
- sync.close();
- }
- });
- }
- } catch (Exception e) {
- DdmConsole.printErrorToConsole("Failed to push the item(s).");
- DdmConsole.printErrorToConsole(e.getMessage());
- }
- }
-
- /**
- * Sent when the a device is connected to the {@link SmartDevelopmentBridge}
- * .
- * <p/>
- * This is sent from a non UI thread.
- *
- * @param device
- * the new device.
- *
- * @see IDeviceChangeListener#deviceConnected(IDevice)
- */
- public void deviceConnected(IDevice device) {
- if (device.isOffline())
- return;
- devicesList.add(device);
- ToolsInstall.installPackages(device);
-
- exec(new Runnable() {
- public void run() {
- if (tree.isDisposed() == false) {
- // refresh all
- treeViewer.refresh();
-
- // notify the listener of a possible selection change.
- notifyListeners();
- } else {
- // tree is disposed, we need to do something.
- // lets remove ourselves from the listener.
- SmartDevelopmentBridge
- .removeDebugBridgeChangeListener(ConnectionExplorerPanel.this);
- SmartDevelopmentBridge
- .removeDeviceChangeListener(ConnectionExplorerPanel.this);
- }
- }
- });
-
- synchronized (devicesToExpand) {
- devicesToExpand.add(device);
- }
-
- }
-
- @Override
- public void deviceDisconnected(IDevice device) {
- devicesList.remove(device);
- exec(new Runnable() {
- public void run() {
- if (tree.isDisposed() == false) {
- // refresh all
- treeViewer.refresh();
-
- // notify the listener of a possible selection change.
- notifyListeners();
- } else {
- // tree is disposed, we need to do something.
- // lets remove ourselves from the listener.
- SmartDevelopmentBridge
- .removeDebugBridgeChangeListener(ConnectionExplorerPanel.this);
- SmartDevelopmentBridge
- .removeDeviceChangeListener(ConnectionExplorerPanel.this);
- }
- }
- });
-
- synchronized (devicesToExpand) {
- devicesToExpand.add(device);
- }
- // }
- }
-
- @Override
- public void deviceChanged(IDevice device, int changeMask) {
- if (changeMask == 1) {
- devicesList.add(device);
- ToolsInstall.installPackages(device);
- exec(new Runnable() {
- public void run() {
- if (tree.isDisposed() == false) {
- // refresh all
- treeViewer.refresh();
-
- // notify the listener of a possible selection change.
- notifyListeners();
- } else {
- // tree is disposed, we need to do something.
- // lets remove ourselves from the listener.
- SmartDevelopmentBridge
- .removeDebugBridgeChangeListener(ConnectionExplorerPanel.this);
- SmartDevelopmentBridge
- .removeDeviceChangeListener(ConnectionExplorerPanel.this);
- }
- }
- });
-
- synchronized (devicesToExpand) {
- devicesToExpand.add(device);
- }
- }
- }
-
- public ArrayList<IDevice> getDeviceList() {
- return devicesList;
- }
-
- private void exec(Runnable runnable) {
- if (tree.isDisposed() == false) {
- try {
- Display display = tree.getDisplay();
- display.asyncExec(runnable);
- } catch (SWTException e) {
- // tree is disposed, we need to do something. lets remove ourselves
- // from the listener.
- SmartDevelopmentBridge
- .removeDebugBridgeChangeListener(ConnectionExplorerPanel.this);
- SmartDevelopmentBridge
- .removeDeviceChangeListener(ConnectionExplorerPanel.this);
- }
- }
- }
-
- private void notifyListeners() {
- // get the selection
- TreeItem[] items = tree.getSelection();
-
- FileEntry file = null;
-
- if (items.length != 0) {
- Object object = items[0].getData();
- if (object instanceof FileEntry) {
- file = (FileEntry) object;
- }
- }
- notifySelectionListeners(file);
- }
-
- private void notifySelectionListeners(FileEntry file) {
- if (file != null) {
- mCurrentDevice = file.getFileListingService().getDevice();
- } else {
- IDevice[] devices = SmartDevelopmentBridge.getBridge().getDevices();
- if (devices.length != 0) {
- mCurrentDevice = devices[0];
- file = devices[0].getFileListingService().getRoot();
- for (TreeItem item : tree.getItems()) {
- if (item.getText().equals(file.getName()))
- tree.setSelection(item);
- }
- } else
- mCurrentDevice = null;
- }
- currentFileEntry = file;
- ConnectionPlugin.getDefault().setCurrentDevice(mCurrentDevice);
- ConnectionPlugin.getDefault().notifySelectionListeners(file);
- setIconEnabled();
- }
-
- public TreeViewer getTreeViewer() {
- return treeViewer;
- }
-
- class FileNameValidator implements IInputValidator {
-
- @Override
- public String isValid(String newText) {
- if (newText.contains(INVALID_FOR_FILENAME))
- return "\"" + INVALID_FOR_FILENAME + "\" is invalid character for file name.";
- return null;
- }
- }
-
- public void setActionState() {
- subMenu.setVisible(true);
- actionPush.setEnabled(true);
- actionPull.setEnabled(true);
- actionRename.setEnabled(true);
- actionRefresh.setEnabled(true);
- actionDelete.setEnabled(true);
- actionProperty.setEnabled(true);
-
- if (currentFileEntry == null) {
- subMenu.setVisible(false);
- actionPush.setEnabled(false);
- actionPull.setEnabled(false);
- actionRename.setEnabled(false);
- actionRefresh.setEnabled(false);
- actionDelete.setEnabled(false);
- actionProperty.setEnabled(false);
- return;
- }
- if (currentFileEntry.isRoot()) {
- actionPull.setEnabled(false);
- actionRename.setEnabled(false);
- actionDelete.setEnabled(false);
- return;
- }
- if (!currentFileEntry.isDirectory()) {
- subMenu.setVisible(false);
- actionPush.setEnabled(false);
- return;
- }
- }
-
- private void setIconEnabled() {
- boolean bPush = false;
- boolean bPull = false;
-
- if (currentFileEntry == null) {
- bPush = false;
- bPull = false;
- } else {
- if (currentFileEntry.isRoot()) {
- bPush = true;
- bPull = false;
- } else if (!currentFileEntry.isDirectory()) {
- bPush = false;
- bPull = true;
- } else {
- bPush = true;
- bPull = true;
- }
- }
-
- pushToolItem.setEnabled(bPush);
- pullToolItem.setEnabled(bPull);
-
- }
-
- @Override
- public void selectionChanged(final FileEntry selectedEntry) {
- if (selectedEntry == null)
- return;
-
- if (!selectedEntry.isRoot())
- return;
-
- exec(new Runnable() {
- public void run() {
- if (tree.isDisposed() == false) {
- for (TreeItem item : tree.getItems()) {
- if (item.getText().equals(selectedEntry.getName()))
- tree.setSelection(item);
- }
- } else {
- // tree is disposed, we need to do something.
- // lets remove ourselves from the listener.
- ConnectionPlugin.getDefault().removeSelectionListener(ConnectionExplorerPanel.this);
- }
- }
- });
- }
+public class ConnectionExplorerPanel extends Panel implements IDeviceChangeListener, IDebugBridgeChangeListener, ISelectionListener
+{
+
+ private static final String DRAGACTIONID = "org.tizen.common.connection.filedrop";
+
+ private static final String COLUMN_NAME = "name"; //$NON-NLS-1S
+
+ private Composite parent;
+ private TreeViewer treeViewer;
+ private ConnectionExplorerContentProvider contentProvider;
+
+ private final int STATE_PROPERTY = 0x0000001;
+ private final int STATE_DELETE = 0x0000010;
+ private final int STATE_RENAME = 0x0000100;
+ private final int STATE_REFRESH = 0x0001000;
+ private final int STATE_PULL = 0x0010000;
+ private final int STATE_PUSH = 0x0100000;
+ private final int STATE_SUB = 0x1000000;
+
+ private ToolItem pushToolItem;
+ private ToolItem pullToolItem;
+ private ToolItem emulStartToolItem;
+
+ private MenuManager subMenu;
+ private Action actionPush;
+ private Action actionPull;
+ private Action actionRefresh;
+ private Action actionRename;
+ private Action actionProperty;
+ private Action actionDelete;
+
+ private IDevice currentDevice;
+
+ private String defaultSave;
+ // only use on linux system
+ private static final String PATH_SEPARATOR = "/";
+
+ private final List<IDevice> devicesList = new ArrayList<IDevice>();
+
+ private final MessageConsoleStream console;
+
+ public ConnectionExplorerPanel()
+ {
+ ConsoleManager cm = new ConsoleManager("ConnectionExplorer", false);
+ cm.clear();
+ console = cm.getMessageConsoleStream();
+ }
+
+ @Override
+ protected Control createControl(Composite pParent)
+ {
+ parent = pParent;
+ parent.setLayout(new FillLayout());
+
+ treeViewer = new TreeViewer(parent, SWT.MULTI | SWT.FULL_SELECTION);
+ Tree tree = treeViewer.getTree();
+ IPreferenceStore store = DdmUiPreferences.getStore();
+
+ TableHelper.createTreeColumn(tree, Messages.getString("ConnectionExplorer.tree.header"), SWT.LEFT, "abcdefghijklmnopqrstuvwzabcdefghijk", COLUMN_NAME, store); //$NON-NLS-1$
+ tree.setHeaderVisible(true);
+
+ contentProvider = new ConnectionExplorerContentProvider();
+ treeViewer.setContentProvider(contentProvider);
+ treeViewer.setLabelProvider(new ConnectionExplorerLabelProvider(parent.getDisplay()));
+
+ tree.addSelectionListener(new SelectionAdapter()
+ {
+ @Override
+ public void widgetSelected(SelectionEvent e)
+ {
+ // set device for selected FileEntry when select FileEntry on
+ // tree
+ notifyListeners();
+ }
+ });
+
+ // setup drag listener
+ treeViewer.addDragSupport(DND.DROP_MOVE | DND.DROP_COPY, new Transfer[] { PluginTransfer.getInstance(), FileEntryTransfer.getInstance() },
+ new DragSourceListener()
+ {
+
+ @Override
+ public void dragStart(DragSourceEvent e)
+ {
+
+ TreeItem[] items = treeViewer.getTree().getSelection();
+
+ for (int i = 0; i < items.length; i++)
+ {
+ Object data = items[i].getData();
+ if (data instanceof FileEntry)
+ {
+ if (((FileEntry) data).isDirectory() == true || ((FileEntry) data).isRoot() == true)
+ {
+ e.doit = false;
+ return;
+ }
+ }
+ }
+ e.doit = true;
+ }
+
+ @Override
+ public void dragFinished(DragSourceEvent arg0)
+ {
+
+ }
+
+ @Override
+ public void dragSetData(DragSourceEvent e)
+ {
+ // get the selection
+ TreeItem[] items = treeViewer.getTree().getSelection();
+ FileEntry[] entries = new FileEntry[items.length];
+
+ for (int i = 0; i < items.length; i++)
+ {
+ Object data = items[i].getData();
+ if (data instanceof FileEntry)
+ {
+ entries[i] = ((FileEntry) data);
+ }
+ }
+
+ if (FileEntryTransfer.getInstance().isSupportedType(e.dataType))
+ {
+ e.data = entries;
+ } else if (PluginTransfer.getInstance().isSupportedType(e.dataType))
+ {
+ byte[] data = FileEntryTransfer.getInstance().toByteArray(entries);
+ e.data = new PluginTransferData(DRAGACTIONID, data);
+ }
+ }
+ });
+
+ // setup drop listener
+ treeViewer.addDropSupport(DND.DROP_COPY | DND.DROP_MOVE, new Transfer[] { FileTransfer.getInstance() }, new ViewerDropAdapter(treeViewer)
+ {
+ @Override
+ public boolean performDrop(Object data)
+ {
+ // get the item on which we dropped the item(s)
+ FileEntry target = (FileEntry) getCurrentTarget();
+
+ // in case we drop at the same level as root
+ if (target == null)
+ {
+ return false;
+ }
+
+ // if the target is not a directory, we get the parent directory
+ if (target.isDirectory() == false)
+ {
+ target = target.getParent();
+ }
+
+ if (target == null)
+ {
+ return false;
+ }
+
+ // get the list of files to drop
+ String[] files = (String[]) data;
+
+ // do the drop
+ pushFiles(files, target);
+
+ // we need to finish with a refresh
+ refresh(target);
+
+ return true;
+ }
+
+ @Override
+ public boolean validateDrop(Object target, int operation, TransferData transferType)
+ {
+ if (target == null)
+ {
+ return false;
+ }
+
+ // convert to the real item
+ FileEntry targetEntry = (FileEntry) target;
+
+ // if the target is not a directory, we get the parent directory
+ if (targetEntry.isDirectory() == false)
+ {
+ target = targetEntry.getParent();
+ }
+
+ if (target == null)
+ {
+ return false;
+ }
+
+ return true;
+ }
+ });
+
+ return tree;
+ }
+
+ public void setToolItems(ToolItem push, ToolItem pull, ToolItem start)
+ {
+ pushToolItem = push;
+ pullToolItem = pull;
+ emulStartToolItem = start;
+ }
+
+ public void setActions(MenuManager pSubMenu, Action pActionPush, Action pActionPull, Action pActionRefresh, Action pActionRename, Action pActionProperty,
+ Action pActionDelete)
+ {
+ this.subMenu = pSubMenu;
+ this.actionPush = pActionPush;
+ this.actionPull = pActionPull;
+ this.actionRefresh = pActionRefresh;
+ this.actionRename = pActionRename;
+ this.actionProperty = pActionProperty;
+ this.actionDelete = pActionDelete;
+ setActionEnabled();
+ }
+
+ @Override
+ protected void postCreation()
+ {
+ ConnectionPlugin.getDefault().addSelectionListener(this);
+ SmartDevelopmentBridge sdbBridge = SmartDevelopmentBridge.getBridge();
+ SmartDevelopmentBridge.addDebugBridgeChangeListener(this);
+ SmartDevelopmentBridge.addDeviceChangeListener(this);
+
+ IDevice[] devices = null;
+ if (sdbBridge != null)
+ {
+ devices = sdbBridge.getDevices();
+ }
+ if (devices != null && devices.length != 0)
+ {
+ for (IDevice device : devices)
+ {
+ this.deviceConnected(device);
+ }
+ }
+ }
+
+ /**
+ * Sets the focus to the proper control inside the panel.
+ */
+ @Override
+ public void setFocus()
+ {
+ treeViewer.getTree().setFocus();
+ }
+
+ /**
+ * Pull the current selection on the local drive. This method displays a
+ * dialog box to let the user select where to store the file(s) and
+ * folder(s).
+ */
+ public void pullSelection()
+ {
+ DirectoryDialog dlg = new DirectoryDialog(parent.getShell(), SWT.SAVE);
+
+ setDialog(dlg, "Pull the selected content");
+
+ String directoryName = dlg.open();
+
+ if (directoryName != null)
+ {
+ pullSelection(treeViewer.getTree().getSelection(), directoryName);
+ }
+ }
+
+ /**
+ * Push new file(s) and folder(s) into the current selection. Current
+ * selection must be single item. If the current selection is not a
+ * directory, the ` directory is used. This method displays a dialog to let
+ * the user choose file to push to the device.
+ */
+ public void pushIntoSelection()
+ {
+ doActionForEntry(new IActionForEntry()
+ {
+ @Override
+ public void doAction()
+ {
+ FileEntry entry = getSingleFileEntry();
+
+ FileDialog dlg = new FileDialog(parent.getShell(), SWT.OPEN);
+
+ setDialog(dlg, "Push the Files");
+
+ String[] fileName = new String[1];
+ fileName[0] = dlg.open();
+
+ if (fileName[0] != null)
+ {
+ // we need to figure out the remote path based on the
+ // current selection type.
+ FileEntry refreshFileEntry;
+
+ if (entry.isDirectory() || entry.isRoot())
+ {
+ refreshFileEntry = entry;
+ } else
+ {
+ refreshFileEntry = entry.getParent();
+ }
+
+ pushFiles(fileName, refreshFileEntry);
+ refresh(refreshFileEntry);
+ }
+ }
+
+ @Override
+ public boolean doCheckEnable()
+ {
+ return isSingleEntry() && actionPush.isEnabled();
+ }
+ });
+ }
+
+ // only for FileDialog and DirectoryDialog
+ private void setDialog(Dialog dialog, String text)
+ {
+ dialog.setText(text);
+
+ String defaultPath = defaultSave;
+ if (defaultPath == null)
+ {
+ defaultPath = System.getProperty("user.home"); //$NON-NLS-1$
+ }
+
+ if (dialog instanceof FileDialog)
+ {
+ FileDialog dlg = (FileDialog) dialog;
+ dlg.setFilterPath(defaultPath);
+ defaultSave = dlg.getFilterPath();
+ } else if (dialog instanceof DirectoryDialog)
+ {
+ DirectoryDialog dlg = (DirectoryDialog) dialog;
+ dlg.setFilterPath(defaultPath);
+ defaultSave = dlg.getFilterPath();
+ }
+ }
+
+ public void addNewFileSelection()
+ {
+ doActionForEntry(new IActionForEntry()
+ {
+ @Override
+ public void doAction()
+ {
+
+ FileEntry entry = getSingleFileEntry();
+
+ String name = getNameFromInputDialog("New File Resource", "New File Name: ", entry, "");
+
+ if (name == null)
+ {
+ return;
+ }
+
+ String fullPath = FilenameUtil.addDoubleQuote(entry.getFullEscapedPath() + "/" + name);
+ String command = String.format("touch %s; echo $?", fullPath);
+ try
+ {
+ currentDevice.executeShellCommand(command, new MultiLineReceiver()
+ {
+
+ @Override
+ public void processNewLines(String[] lines)
+ {
+ sayError(lines, "add_file_error", "A file failed to be added");
+ }
+ });
+ } catch (IOException e)
+ {
+ Logger.error("failed to add new file", e);
+ throw new RuntimeException(e);
+ }
+ refresh(entry);
+ }
+
+ @Override
+ public boolean doCheckEnable()
+ {
+ return isSingleEntry();
+ }
+ });
+ }
+
+ public void addNewFolderSelection()
+ {
+ doActionForEntry(new IActionForEntry()
+ {
+ @Override
+ public void doAction()
+ {
+
+ FileEntry entry = getSingleFileEntry();
+
+ String name = getNameFromInputDialog("New Folder Resource", "New Folder Name: ", entry, "");
+ if (name == null)
+ {
+ return;
+ }
+
+ // create the mkdir command
+ String fullPath = FilenameUtil.addDoubleQuote(entry.getFullEscapedPath() + "/" + name);
+ String command = String.format("mkdir %s; echo $?", fullPath);
+ try
+ {
+ currentDevice.executeShellCommand(command, new MultiLineReceiver()
+ {
+ @Override
+ public void processNewLines(String[] lines)
+ {
+ sayError(lines, "add_folder_error", "A folder failed to be added");
+ }
+ });
+ } catch (IOException e)
+ {
+ Logger.error("failed to add new folder", e);
+ throw new RuntimeException(e);
+ }
+ refresh(entry);
+ }
+
+ @Override
+ public boolean doCheckEnable()
+ {
+ return isSingleEntry();
+ }
+ });
+ }
+
+ // Get user input for adding new file or folder and rename
+ private String getNameFromInputDialog(String title, String message, FileEntry entry, String initValue)
+ {
+ boolean again;
+ InputDialog inputDialog;
+
+ do
+ {
+ again = false;
+ // open dialog to get input
+ inputDialog = new InputDialog(Display.getCurrent().getActiveShell(), title, message, initValue, new FileNameValidator());
+
+ if (inputDialog.open() != Window.OK)
+ {
+ return null;
+ }
+
+ String input = inputDialog.getValue();
+ // same entry is already exist..
+ if (findDuplicateFileEntry(input, entry))
+ {
+ again = true;
+ }
+
+ } while (again);
+
+ return FilenameUtil.getEscapedName(inputDialog.getValue());
+ }
+
+ public void renameSelection()
+ {
+ doActionForEntry(new IActionForEntry()
+ {
+ @Override
+ public void doAction()
+ {
+
+ FileEntry entry = getSingleFileEntry();
+
+ String name = getNameFromInputDialog("Rename Resource", "New name: ", entry.getParent(), entry.getName());
+
+ if (name == null)
+ {
+ return;
+ }
+
+ String fullPath = entry.getFullEscapedPath();
+ int lastIndex = fullPath.lastIndexOf(PATH_SEPARATOR);
+ String newPath = fullPath.substring(0, lastIndex) + PATH_SEPARATOR + name;
+
+ // create the mv command
+ String command = String.format("mv %s %s; echo $?", FilenameUtil.addDoubleQuote(fullPath), FilenameUtil.addDoubleQuote(newPath));
+ try
+ {
+ currentDevice.executeShellCommand(command, new MultiLineReceiver()
+ {
+
+ @Override
+ public void processNewLines(String[] lines)
+ {
+ sayError(lines, "rename_error", "A selection failed to be renamed");
+ }
+ });
+ } catch (IOException e)
+ {
+ Logger.error("failed to rename", e);
+ throw new RuntimeException(e);
+ }
+ refresh(entry.getParent());
+ }
+
+ @Override
+ public boolean doCheckEnable()
+ {
+ return isSingleEntry() && actionRename.isEnabled();
+ }
+ });
+ }
+
+ public void deleteSelection()
+ {
+ doActionForEntry(new IActionForEntry()
+ {
+ @Override
+ public void doAction()
+ {
+ TreeItem[] items = treeViewer.getTree().getSelection();
+ for (TreeItem item : items)
+ {
+ Object obj = item.getData();
+ if (obj instanceof FileEntry)
+ {
+ FileEntry entry = (FileEntry) obj;
+ int ret = FileDialogUtils.confirmDelete(entry.getName());
+ if (ret == IDialogConstants.CANCEL_ID)
+ continue;
+
+ String command = null;
+ // create the delete command
+ if (entry.isDirectory())
+ {
+ command = String.format("rm -rf %s; echo $?", FilenameUtil.addDoubleQuote(entry.getFullEscapedPath()));
+ } else
+ {
+ command = String.format("rm %s; echo $?", FilenameUtil.addDoubleQuote(entry.getFullEscapedPath()));
+ }
+
+ try
+ {
+ currentDevice.executeShellCommand(command, new MultiLineReceiver()
+ {
+
+ @Override
+ public void processNewLines(String[] lines)
+ {
+ sayError(lines, "delete_error", "A selection failed to be deleted");
+ }
+ });
+ item.dispose();
+ } catch (IOException e)
+ {
+ Logger.error("failed to delete", e);
+ throw new RuntimeException(e);
+
+ }
+ refresh(entry.getParent());
+ setActionEnabled();
+ }
+ }
+ }
+
+ @Override
+ public boolean doCheckEnable()
+ {
+ return actionDelete.isEnabled();
+ }
+ });
+ }
+
+ public void showPropertySelection(final IWorkbenchPartSite site)
+ {
+ doActionForEntry(new IActionForEntry()
+ {
+ @Override
+ public void doAction()
+ {
+ PropertyDialogAction pda = new PropertyDialogAction(site, treeViewer);
+ pda.run();
+ }
+
+ @Override
+ public boolean doCheckEnable()
+ {
+ return actionProperty.isEnabled();
+ }
+ });
+ }
+
+ private void sayError(String[] lines, String id, String message)
+ {
+ if (!lines[lines.length - 1].contains("0"))
+ {
+ StringBuilder sb = new StringBuilder();
+ for (String line : lines)
+ {
+ line = AnsicodeAdapter.getStripAnsiString(line);
+ sb.append(line);
+ }
+ Status status = new Status(IStatus.ERROR, id, 0, sb.toString(), null);
+ ErrorDialog.openError(Display.getCurrent().getActiveShell(), Messages.getString("FileDialogUtils.message.title"), message, status);
+ }
+ }
+
+ /**
+ * Sent when a new {@link SmartDevelopmentBridge} is started.
+ * <p/>
+ * This is sent from a non UI thread.
+ *
+ * @param bridge
+ * the new {@link SmartDevelopmentBridge} object.
+ *
+ * @see IDebugBridgeChangeListener#serverChanged(SmartDevelopmentBridge)
+ */
+ @Override
+ public void bridgeChanged(final SmartDevelopmentBridge bridge)
+ {
+ final Tree tree = treeViewer.getTree();
+ if (tree.isDisposed() == false)
+ {
+ exec(new Runnable()
+ {
+ @Override
+ public void run()
+ {
+ if (tree.isDisposed() == false)
+ {
+ // set up the data source.
+ treeViewer.setInput(bridge);
+ } else
+ {
+ // tree is disposed, we need to do something.
+ // lets remove ourselves from the listener.
+ SmartDevelopmentBridge.removeDebugBridgeChangeListener(ConnectionExplorerPanel.this);
+ SmartDevelopmentBridge.removeDeviceChangeListener(ConnectionExplorerPanel.this);
+ }
+ }
+ });
+ }
+ }
+
+ /**
+ * Refresh an entry from a non ui thread.
+ *
+ * @param entry
+ * the entry to refresh.
+ */
+ private void refresh(final FileEntry entry)
+ {
+ Display d = treeViewer.getTree().getDisplay();
+ d.asyncExec(new Runnable()
+ {
+ @Override
+ public void run()
+ {
+ treeViewer.refresh(entry, true);
+ }
+ });
+ }
+
+ public void refreshSelection()
+ {
+ if (treeViewer.getTree().getSelectionCount() == 0)
+ {
+ return;
+ }
+ refresh(getSingleFileEntry());
+ }
+
+ /**
+ * Pulls the selection from a device.
+ *
+ * @param items
+ * the tree selection the remote file on the device
+ * @param localDirector
+ * the local directory in which to save the files.
+ */
+ private void pullSelection(TreeItem[] items, final String localDirectory)
+ {
+ try
+ {
+ final SyncService sync = currentDevice.getSyncService();
+ if (sync != null)
+ {
+ // make a list of the FileEntry.
+ List<FileEntry> entries = new ArrayList<FileEntry>();
+ for (TreeItem item : items)
+ {
+ Object data = item.getData();
+ if (data instanceof FileEntry)
+ {
+ FileEntry entry = (FileEntry)data;
+ if (!FilenameUtil.isVaildName(entry.getName()))
+ {
+ DialogUtil.openErrorDialog(entry.getName() + "\n" +
+ ConnectionUIMessages.Explorer_Message_Invalid_Character
+ + FilenameUtil.getInvalidCharacters());
+ continue;
+ }
+ entries.add((FileEntry) data);
+ }
+ }
+ final FileEntry[] entryArray = entries.toArray(new FileEntry[entries.size()]);
+
+ // get a progress dialog
+ new ProgressMonitorDialog(parent.getShell()).run(true, true, new IRunnableWithProgress()
+ {
+ @Override
+ public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException
+ {
+ // create a monitor wrapper around the jface monitor
+ SyncResult result = sync.pull(entryArray, localDirectory, (ISyncProgressMonitor) new SyncProgressMonitor(monitor,
+ "Pulling file(s) from the device"));
+
+ if (result.getCode() != SyncService.RESULT_OK)
+ {
+ String message = String.format("Failed to pull selection: %1$s", result.getMessage());
+ console.println(message);
+ DialogUtil.openErrorDialog(message);
+ }
+ sync.close();
+ }
+ });
+ }
+ } catch (Exception e)
+ {
+ String message = "Failed to pull selection";
+ DialogUtil.openErrorDialog(message);
+ console.println(message);
+ console.println(e.getMessage());
+ }
+ }
+
+ /**
+ * Pushes several files and directory into a remote directory.
+ *
+ * @param localFiles
+ * @param remoteDirectory
+ */
+ private void pushFiles(final String[] localFiles, final FileEntry remoteDirectory)
+ {
+ final String[] files = getFilesToOverwrite(localFiles, remoteDirectory);
+ if (files == null || files.length == 0)
+ return;
+ try
+ {
+ final SyncService sync = currentDevice.getSyncService();
+ if (sync != null)
+ {
+ new ProgressMonitorDialog(parent.getShell()).run(true, true, new IRunnableWithProgress()
+ {
+ @Override
+ public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException
+ {
+ SyncResult result = sync.push(files, remoteDirectory, (ISyncProgressMonitor) new SyncProgressMonitor(monitor,
+ "Pushing file(s) to the device"));
+ if (result.getCode() != SyncService.RESULT_OK)
+ {
+ String message = String.format("Failed to push the items: %1$s", result.getMessage());
+ console.println(message);
+ DialogUtil.openErrorDialog(message);
+ }
+ sync.close();
+ }
+ });
+ }
+ } catch (Exception e)
+ {
+ String message = "Failed to push the items";
+ DialogUtil.openErrorDialog(message);
+ console.println(message);
+ console.println(e.getMessage());
+ }
+ }
+
+ private String[] getFilesToOverwrite(String[] src, FileEntry des)
+ {
+ FileEntry[] children = des.getFileListingService().getChildren(des, false, null);
+
+ List<String> listToOverwrite = new ArrayList<String>();
+ boolean yesAll = false;
+
+ for (String source : src)
+ {
+ File f = new File(source);
+ boolean bFind = false;
+ for (FileEntry entry : children)
+ {
+ if (entry.getName().equals(f.getName()))
+ {
+ bFind = true;
+ break;
+ }
+ }
+
+ if (bFind)
+ {
+ if (!yesAll)
+ {
+ int ret;
+ if (src.length == 1)
+ {
+ ret = FileDialogUtils.allowFileOverwrite(f.getName());
+ if( ret == IDialogConstants.CANCEL_ID)
+ break;
+ } else
+ {
+ ret = FileDialogUtils.checkOverwrite(f.getName());
+ switch (ret)
+ {
+ case IDialogConstants.CANCEL_ID:
+ return null;
+ case IDialogConstants.NO_ID:
+ continue;
+ case IDialogConstants.YES_TO_ALL_ID:
+ yesAll = true;
+ case IDialogConstants.YES_ID:
+ break;
+ default:
+ break;
+ }
+ }
+ }
+ }
+ listToOverwrite.add(source);
+ }
+ return listToOverwrite.toArray(new String[0]);
+ }
+
+ private boolean findDuplicateFileEntry(String src, FileEntry des)
+ {
+ FileEntry[] children = des.getFileListingService().getChildren(des, false, null);
+
+ for (FileEntry entry : children)
+ {
+ File f = new File(src);
+
+ if (entry.getName().equals(f.getName()))
+ {
+ FileDialogUtils.notifyDuplication((f.getName()));
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Sent when the a device is connected to the {@link SmartDevelopmentBridge}
+ * .
+ * <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 (device.isOffline())
+ {
+ return;
+ }
+ devicesList.add(device);
+ ToolsInstall.installPackages(device);
+ execRefresh();
+ }
+
+ @Override
+ public void deviceDisconnected(IDevice device)
+ {
+ devicesList.remove(device);
+ execRefresh();
+ }
+
+ @Override
+ public void deviceChanged(IDevice device, int changeMask)
+ {
+ if (changeMask == 1)
+ {
+ deviceConnected(device);
+ }
+ }
+
+ private void execRefresh()
+ {
+ exec(new Runnable()
+ {
+ @Override
+ public void run()
+ {
+ if (treeViewer.getTree().isDisposed() == false)
+ {
+ // refresh all
+ treeViewer.refresh();
+
+ // notify the listener of a possible selection change.
+ notifyListeners();
+ } else
+ {
+ // tree is disposed, we need to do something.
+ // lets remove ourselves from the listener.
+ SmartDevelopmentBridge.removeDebugBridgeChangeListener(ConnectionExplorerPanel.this);
+ SmartDevelopmentBridge.removeDeviceChangeListener(ConnectionExplorerPanel.this);
+ }
+ }
+ });
+ }
+
+ public List<IDevice> getDeviceList()
+ {
+ return devicesList;
+ }
+
+ private void exec(Runnable runnable)
+ {
+ Tree tree = treeViewer.getTree();
+
+ if (tree.isDisposed() == false)
+ {
+ try
+ {
+ Display display = tree.getDisplay();
+ display.asyncExec(runnable);
+ } catch (SWTException e)
+ {
+ // tree is disposed, we need to do something. lets remove
+ // ourselves from the listener.
+ SmartDevelopmentBridge.removeDebugBridgeChangeListener(ConnectionExplorerPanel.this);
+ SmartDevelopmentBridge.removeDeviceChangeListener(ConnectionExplorerPanel.this);
+ }
+ }
+ }
+
+ private void notifyListeners()
+ {
+ Tree tree = treeViewer.getTree();
+ FileEntry entry = null;
+ if (tree.getSelectionCount() > 0)
+ entry = getSingleFileEntry();
+
+ if (entry != null)
+ {
+ currentDevice = entry.getFileListingService().getDevice();
+ } else
+ {
+ IDevice[] devices = SmartDevelopmentBridge.getBridge().getDevices();
+ if (devices.length != 0)
+ {
+ currentDevice = devices[0];
+ entry = devices[0].getFileListingService().getRoot();
+ for (TreeItem item : tree.getItems())
+ {
+ if (item.getText().equals(entry.getName()))
+ {
+ tree.setSelection(item);
+ }
+ }
+ } else
+ currentDevice = null;
+ }
+ ConnectionPlugin.getDefault().setCurrentDevice(currentDevice);
+ ConnectionPlugin.getDefault().notifySelectionListeners(entry);
+ setActionEnabled();
+
+ }
+
+ public TreeViewer getTreeViewer()
+ {
+ return treeViewer;
+ }
+
+ class FileNameValidator implements IInputValidator
+ {
+ @Override
+ public String isValid(String fileName)
+ {
+ int os = TizenPlatformConstants.OS;
+ int validCheck = FilenameUtil.isVaildName(fileName, os);
+ if (validCheck != FilenameUtil.IS_VALID_NAME)
+ {
+ switch(validCheck)
+ {
+ case FilenameUtil.HAS_INVALID_CHARACTER:
+ return ConnectionUIMessages.Explorer_Message_Invalid_Character + FilenameUtil.getInvalidCharacters(os);
+ case FilenameUtil.HAS_NO_NAME:
+ return "";
+ default:
+ break;
+ }
+ }
+ return null;
+ }
+ }
+
+ public int getActionState()
+ {
+ //sub, push, pull, refresh, rename, delete, property
+ int length = treeViewer.getTree().getSelectionCount();
+
+ int state = 0x0000000;
+
+ if (length == 1)
+ {
+ FileEntry entry = getSingleFileEntry();
+ if (entry.isRoot())
+ {
+ state = STATE_SUB | STATE_PUSH| STATE_PULL | STATE_REFRESH | STATE_PROPERTY;
+ } else if (!entry.isDirectory())
+ {
+ state = STATE_PULL | STATE_REFRESH | STATE_RENAME | STATE_DELETE | STATE_PROPERTY;
+ } else
+ {
+ state = STATE_SUB | STATE_PUSH | STATE_PULL | STATE_REFRESH | STATE_RENAME | STATE_DELETE | STATE_PROPERTY;
+ }
+ } else if (length > 1)
+ {
+ state = STATE_PULL | STATE_DELETE;
+ }
+
+ return state;
+ }
+
+ private boolean getEnabled(int mode, int state)
+ {
+ int result = (mode & state);
+ return result != 0 ? true : false;
+ }
+
+ private void setActionEnabled()
+ {
+ int mode = getActionState();
+ subMenu.setVisible(getEnabled(mode, STATE_SUB));
+
+ boolean bPush = getEnabled(mode, STATE_PUSH);
+ actionPush.setEnabled(bPush);
+ pushToolItem.setEnabled(bPush);
+
+ boolean bPull = getEnabled(mode, STATE_PULL);
+ actionPull.setEnabled(bPull);
+ pullToolItem.setEnabled(bPull);
+
+ actionRename.setEnabled(getEnabled(mode, STATE_RENAME));
+ actionRefresh.setEnabled(getEnabled(mode, STATE_REFRESH));
+ actionDelete.setEnabled(getEnabled(mode, STATE_DELETE));
+ actionProperty.setEnabled(getEnabled(mode, STATE_PROPERTY));
+ }
+
+ private FileEntry getSingleFileEntry()
+ {
+ Tree tree = treeViewer.getTree();
+ if (tree.getSelectionCount() != 0)
+ {
+ TreeItem[] items = tree.getSelection();
+ return (FileEntry) items[0].getData();
+ } else
+ return null;
+ }
+
+ @Override
+ public void selectionChanged(final FileEntry selectedEntry)
+ {
+
+ if (selectedEntry == null)
+ {
+ return;
+ }
+
+ if (!selectedEntry.isRoot())
+ {
+ return;
+ }
+
+ final Tree tree = treeViewer.getTree();
+ exec(new Runnable()
+ {
+ @Override
+ public void run()
+ {
+ if (tree.isDisposed() == false)
+ {
+ for (TreeItem item : tree.getItems())
+ {
+ if (item.getText().equals(selectedEntry.getName()))
+ tree.setSelection(item);
+ }
+ } else
+ {
+ // tree is disposed, we need to do something.
+ // lets remove ourselves from the listener.
+ ConnectionPlugin.getDefault().removeSelectionListener(ConnectionExplorerPanel.this);
+ }
+ }
+ });
+ }
+
+ private boolean isSingleEntry()
+ {
+ Tree tree = treeViewer.getTree();
+ if (tree.getSelectionCount() == 1)
+ {
+ return true;
+ } else
+ {
+ return false;
+ }
+ }
+
+ public void doActionForEntry(IActionForEntry action)
+ {
+ if (action.doCheckEnable())
+ {
+ action.doAction();
+ }
+ }
+
+ private interface IActionForEntry
+ {
+ public boolean doCheckEnable();
+
+ public void doAction();
+ }
} \ No newline at end of file
diff --git a/org.tizen.common.connection/src/org/tizen/common/connection/explorer/Messages.java b/org.tizen.common.connection/src/org/tizen/common/connection/explorer/Messages.java
index 28a166170..f603e24c6 100644..100755
--- a/org.tizen.common.connection/src/org/tizen/common/connection/explorer/Messages.java
+++ b/org.tizen.common.connection/src/org/tizen/common/connection/explorer/Messages.java
@@ -52,80 +52,4 @@ public class Messages {
return '!' + key + '!';
}
}
- private static String messageBind(String message, Object[] args, String argZero, String argOne) {
- int length = message.length();
- //estimate correct size of string buffer to avoid growth
- int bufLen = length + (args.length * 5);
- if (argZero != null)
- bufLen += argZero.length() - 3;
- if (argOne != null)
- bufLen += argOne.length() - 3;
- StringBuffer buffer = new StringBuffer(bufLen < 0 ? 0 : bufLen);
- for (int i = 0; i < length; i++) {
- char c = message.charAt(i);
- switch (c) {
- case '{' :
- int index = message.indexOf('}', i);
- // if we don't have a matching closing brace then...
- if (index == -1) {
- buffer.append(c);
- break;
- }
- i++;
- if (i >= length) {
- buffer.append(c);
- break;
- }
- // look for a substitution
- int number = -1;
- try {
- number = Integer.parseInt(message.substring(i, index));
- } catch (NumberFormatException e) {
- throw (IllegalArgumentException) new IllegalArgumentException().initCause(e);
- }
- if (number == 0 && argZero != null)
- buffer.append(argZero);
- else if (number == 1 && argOne != null)
- buffer.append(argOne);
- else {
- if (number >= args.length || number < 0) {
- buffer.append("<missing argument>"); //$NON-NLS-1$
- i = index;
- break;
- }
- buffer.append(args[number]);
- }
- i = index;
- break;
- case '\'' :
- // if a single quote is the last char on the line then skip it
- int nextIndex = i + 1;
- if (nextIndex >= length) {
- buffer.append(c);
- break;
- }
- char next = message.charAt(nextIndex);
- // if the next char is another single quote then write out one
- if (next == '\'') {
- i++;
- buffer.append(c);
- break;
- }
- // otherwise we want to read until we get to the next single quote
- index = message.indexOf('\'', nextIndex);
- // if there are no more in the string, then skip it
- if (index == -1) {
- buffer.append(c);
- break;
- }
- // otherwise write out the chars inside the quotes
- buffer.append(message.substring(nextIndex, index));
- i = index;
- break;
- default :
- buffer.append(c);
- }
- }
- return buffer.toString();
- }
}
diff --git a/org.tizen.common.connection/src/org/tizen/common/connection/explorer/messages.properties b/org.tizen.common.connection/src/org/tizen/common/connection/explorer/messages.properties
index 3d54a9c15..28acc154d 100644
--- a/org.tizen.common.connection/src/org/tizen/common/connection/explorer/messages.properties
+++ b/org.tizen.common.connection/src/org/tizen/common/connection/explorer/messages.properties
@@ -1,9 +1,8 @@
-
-FileDialogUtils.overrite.title=File Exists
-FileDialogUtils.overrite.message=The file {0} already exists. Are you going to overwrite it?
-FileDialogUtils.delete.title=File Delete
-FileDialogUtils.delete.message=Are you going to delete {0}?
-FileDialogUtils.tabName.title=Invalid Name
-FileDialogUtils.tabName.message= "{0}" is already exist!\nPlease fill in the TabName with another.
+FileDialogUtils.message.title=Message
+FileDialogUtils.overwrite.message=The {0} file already exists. Do you want to overwrite it?
+FileDialogUtils.duplicate.message=Existing file
+FileDialogUtils.delete.message=Are you sure you want to delete the {0} file?
+FileDialogUtils.tabName.message= The tab name already exists. Enter a different name.
FileDialogUtils.update.title=Tizen SDK
-FileDialogUtils.update.message= Updates are available for Tizen SDK. Do you want to install them?
+FileDialogUtils.update.message= Tizen SDK updates are available. Do you want to install them now?
+ConnectionExplorer.tree.header=Files \ No newline at end of file
diff --git a/org.tizen.common.connection/src/org/tizen/common/connection/log/AddViewDialog.java b/org.tizen.common.connection/src/org/tizen/common/connection/log/AddViewDialog.java
index 2d6ccd340..13cb20247 100644..100755
--- a/org.tizen.common.connection/src/org/tizen/common/connection/log/AddViewDialog.java
+++ b/org.tizen.common.connection/src/org/tizen/common/connection/log/AddViewDialog.java
@@ -1,30 +1,32 @@
/*
-* Common
-*
-* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
-*
-* Contact:
-* Hoon Kang <h245.kang@samsung.com>
-* Hyunsik Noh <hyunsik.noh@samsung.com>
-*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * Hoon Kang <h245.kang@samsung.com>
+ * Hyunsik Noh <hyunsik.noh@samsung.com>
+ *
* 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.
-*
-* Contributors:
-* - S-Core Co., Ltd
-*
-*/
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
package org.tizen.common.connection.log;
+import static org.tizen.common.util.StringUtil.isEmpty;
+
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
@@ -50,268 +52,314 @@ import org.tizen.sdblib.SmartDevelopmentBridge;
/**
* Small dialog box to open new logtab with some options.
*/
-public class AddViewDialog extends Dialog {
-
- private static final int DLG_WIDTH = 400;
- private static final int DLG_HEIGHT = 300;
-
- private Shell parent;
-
- private Shell shell;
-
- private String dialogName = null;
-
- private boolean bOk = false;
-
- private LogTab oldTab = null;
-
- private static final String TEMPNAME = "LogTab-#";
- private static int cnt = 0;
-
- private String tabName = null;
- private String device = null;
- private String pidKeyword = null;
- private String tagKeyword = null;
- private String msgKeyword = null;
-
- private Text tabNameText;
- private Text tagText;
- private Text pidText;
- private Text msgText;
- private Button okButton;
-
- public AddViewDialog(Shell pParent) {
- super(pParent, SWT.DIALOG_TRIM | SWT.BORDER | SWT.APPLICATION_MODAL);
- }
-
- public AddViewDialog(Shell pParent, String deviceName) {
- super(pParent, SWT.DIALOG_TRIM | SWT.BORDER | SWT.APPLICATION_MODAL);
- device = deviceName;
- dialogName = "Add LogTab";
- }
-
- public AddViewDialog(Shell pParent, LogTab tab) {
- super(pParent, SWT.DIALOG_TRIM | SWT.BORDER | SWT.APPLICATION_MODAL);
- if (tab != null) {
- dialogName = "Edit LogTab";
- tabName = tab.getFilterName();
- if (tab.getFilterDeviceName() == null)
- return;
- device = tab.getFilterDeviceName();
-
- pidKeyword = tab.getPidFilter();
- tagKeyword = tab.getTagFilter();
- msgKeyword = tab.getMsgFilter();
-
- oldTab = tab;
- }
- }
-
- /**
- * 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 (parent == null || shell == null) {
- return false;
- }
-
- shell.setMinimumSize(DLG_WIDTH, DLG_HEIGHT);
- Rectangle r = parent.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;
- shell.setBounds(x, y, DLG_WIDTH, DLG_HEIGHT);
-
- shell.open();
-
- Display display = parent.getDisplay();
- while (!shell.isDisposed()) {
- if (!display.readAndDispatch())
- display.sleep();
- }
-
- return bOk;
- }
-
- private void createUI() {
- parent = getParent();
- shell = new Shell(parent, getStyle());
- shell.setText(dialogName);
-
- shell.setLayout(new GridLayout(1, false));
-
- shell.addListener(SWT.Close, new Listener() {
- @Override
- public void handleEvent(Event event) {
- }
- });
-
- Group top = new Group(shell, SWT.SHADOW_IN);
- top.setText("LogTab");
- top.setLayoutData(new GridData(GridData.FILL_BOTH));
- top.setLayout(new GridLayout(2, false));
-
- Label l = new Label(top, SWT.NONE);
- l.setText("Name : ");
-
- tabNameText = new Text(top, SWT.SINGLE | SWT.BORDER);
- if (tabName != null)
- tabNameText.setText(tabName);
- tabNameText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- l = new Label(top, SWT.NONE);
- l.setText("Device : ");
-
- final Combo dCombo = new Combo(top, SWT.DROP_DOWN | SWT.READ_ONLY | SWT.CENTER);
- GridData gd = new GridData(GridData.FILL_HORIZONTAL);
-
- dCombo.setLayoutData(gd);
- IDevice[] devices = SmartDevelopmentBridge.getBridge().getDevices();
-
- if (devices.length != 0) {
- for (IDevice d : devices) {
- if (d.isOnline())
- dCombo.add(d.getSerialNumber());
- }
-
- if (device != null) {
- for (int i = 0; i < devices.length; i++) {
- if (device.equals(devices[i].getSerialNumber())) {
- dCombo.select(i);
- break;
- }
- }
- } else {
- dCombo.select(0);
- device = dCombo.getItem(0);
- }
- }
-
- Group mid = new Group(shell, SWT.SHADOW_IN);
- mid.setText("Search Keywords");
- mid.setLayoutData(new GridData(GridData.FILL_BOTH));
- mid.setLayout(new GridLayout(2, false));
-
- l = new Label(mid, SWT.NONE);
- l.setText("Tag : ");
-
- tagText = new Text(mid, SWT.SINGLE | SWT.BORDER);
- if (tagKeyword != null)
- tagText.setText(tagKeyword);
- tagText.setMessage("Separated by a space/comma");
- tagText.setToolTipText("Search Tag Keywords are separated by a space as well as a comma");
- tagText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- l = new Label(mid, SWT.NONE);
- l.setText("Pid : ");
-
- pidText = new Text(mid, SWT.SINGLE | SWT.BORDER);
- if (pidKeyword != null)
- pidText.setText(pidKeyword);
- pidText.setMessage("Separated by a space/comma");
- pidText.setToolTipText("Search Pid Keywords are separated by a space as well as a comma");
- pidText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- l = new Label(mid, SWT.NONE);
- l.setText("Message : ");
-
- msgText = new Text(mid, SWT.SINGLE | SWT.BORDER);
- if (msgKeyword != null)
- msgText.setText(msgKeyword);
- msgText.setMessage("Separated by a space/comma");
- msgText.setToolTipText("Search Message Keywords are separated by a space as well as a comma");
- msgText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- // bottom part with the ok/cancel
- Composite bottomComp = new Composite(shell, SWT.NONE);
- bottomComp
- .setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_CENTER));
- bottomComp.setLayout(new GridLayout(2, true));
-
- okButton = new Button(bottomComp, SWT.NONE);
- okButton.setText("OK");
- okButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- String newName = tabNameText.getText();
- for (LogTab tab : LogPanel.tabs) {
- if (tab.getFilterName().equals(newName)) {
- if (oldTab != null && oldTab == tab)
- continue;
- int ret = FileDialogUtils.getInstance().checkTabName(newName);
- if (ret == IDialogConstants.OK_ID)
- return;
- }
- }
-
- bOk = true;
-
- if (tabNameText.getText().length() != 0)
- tabName = tabNameText.getText();
- else
- tabName = TEMPNAME + cnt++;
-
- if (tagText.getText().length() != 0)
- tagKeyword = tagText.getText();
- else
- tagKeyword = null;
-
- if (pidText.getText().length() != 0)
- pidKeyword = pidText.getText();
- else
- pidKeyword = null;
-
- if (msgText.getText().length() != 0)
- msgKeyword = msgText.getText();
- else
- msgKeyword = null;
-
- device = dCombo.getItem(dCombo.getSelectionIndex());
-
- shell.close();
- }
- });
- shell.setDefaultButton(okButton);
-
- Button cancelButton = new Button(bottomComp, SWT.NONE);
- cancelButton.setText("Cancel");
- cancelButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- shell.close();
- }
- });
-
- }
-
- public String getName() {
- return tabName;
- }
-
- public String getDevice() {
- return device;
- }
-
- public String getPidKeyword() {
- return pidKeyword;
- }
-
- public String getTagKeyword() {
- return tagKeyword;
- }
-
- public String getMsgKeyword() {
- return msgKeyword;
- }
-
- public void setName(String name) {
- this.tabName = name;
- }
+public class AddViewDialog extends Dialog
+{
+
+ private static final int DLG_WIDTH = 400;
+ private static final int DLG_HEIGHT = 300;
+
+ private Shell parent;
+
+ private Shell shell;
+
+ private String dialogName = null;
+
+ private boolean bOk = false;
+
+ private LogTab oldTab = null;
+
+ private static final String TEMPNAME = "LogTab-#";
+ private static int cnt = 0;
+
+ private String tabName = null;
+ private String device = null;
+ private String pidKeyword = null;
+ private String tagKeyword = null;
+ private String msgKeyword = null;
+
+ private Text tabNameText;
+ private Text tagText;
+ private Text pidText;
+ private Text msgText;
+ private Button okButton;
+
+ public AddViewDialog(Shell pParent)
+ {
+ super(pParent, SWT.DIALOG_TRIM | SWT.BORDER | SWT.APPLICATION_MODAL);
+ }
+
+ public AddViewDialog(Shell pParent, String deviceName)
+ {
+ super(pParent, SWT.DIALOG_TRIM | SWT.BORDER | SWT.APPLICATION_MODAL);
+ device = deviceName;
+ dialogName = "Add LogTab";
+ }
+
+ public AddViewDialog(Shell pParent, LogTab tab)
+ {
+ super(pParent, SWT.DIALOG_TRIM | SWT.BORDER | SWT.APPLICATION_MODAL);
+ if (tab != null)
+ {
+ dialogName = "Edit LogTab";
+ tabName = tab.getLogTabName();
+ if (tab.getDeviceSerialNumber() == null)
+ {
+ return;
+ }
+ device = tab.getDeviceSerialNumber();
+
+ pidKeyword = tab.getPidFilter();
+ tagKeyword = tab.getTagFilter();
+ msgKeyword = tab.getMsgFilter();
+
+ oldTab = tab;
+ }
+ }
+
+ /**
+ * 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 (parent == null || shell == null)
+ {
+ return false;
+ }
+
+ shell.setMinimumSize(DLG_WIDTH, DLG_HEIGHT);
+ Rectangle r = parent.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;
+ shell.setBounds(x, y, DLG_WIDTH, DLG_HEIGHT);
+
+ shell.open();
+
+ Display display = parent.getDisplay();
+ while (!shell.isDisposed())
+ {
+ if (!display.readAndDispatch())
+ display.sleep();
+ }
+
+ return bOk;
+ }
+
+ private void createUI()
+ {
+ parent = getParent();
+ shell = new Shell(parent, getStyle());
+ shell.setText(dialogName);
+
+ shell.setLayout(new GridLayout(1, false));
+
+ shell.addListener(SWT.Close, new Listener()
+ {
+ @Override
+ public void handleEvent(Event event)
+ {
+ }
+ });
+
+ Group top = new Group(shell, SWT.SHADOW_IN);
+ top.setText("LogTab");
+ top.setLayoutData(new GridData(GridData.FILL_BOTH));
+ top.setLayout(new GridLayout(2, false));
+
+ Label l = new Label(top, SWT.NONE);
+ l.setText("Name:");
+
+ tabNameText = new Text(top, SWT.SINGLE | SWT.BORDER);
+ if (tabName != null)
+ tabNameText.setText(tabName);
+ tabNameText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+
+ l = new Label(top, SWT.NONE);
+ l.setText("Device:");
+
+ final Combo dCombo = new Combo(top, SWT.DROP_DOWN | SWT.READ_ONLY | SWT.CENTER);
+ GridData gd = new GridData(GridData.FILL_HORIZONTAL);
+
+ dCombo.setLayoutData(gd);
+ IDevice[] devices = SmartDevelopmentBridge.getBridge().getDevices();
+
+ if (devices.length != 0)
+ {
+ for (IDevice d : devices)
+ {
+ if (d.isOnline())
+ dCombo.add(d.getSerialNumber());
+ }
+
+ if (device != null)
+ {
+ for (int i = 0; i < devices.length; i++)
+ {
+ if (device.equals(devices[i].getSerialNumber()))
+ {
+ dCombo.select(i);
+ break;
+ }
+ }
+ } else
+ {
+ dCombo.select(0);
+ device = dCombo.getItem(0);
+ }
+ }
+
+ Group mid = new Group(shell, SWT.SHADOW_IN);
+ mid.setText("Search keywords");
+ mid.setLayoutData(new GridData(GridData.FILL_BOTH));
+ mid.setLayout(new GridLayout(2, false));
+
+ l = new Label(mid, SWT.NONE);
+ l.setText("Tag:");
+
+ tagText = new Text(mid, SWT.SINGLE | SWT.BORDER);
+ if (tagKeyword != null)
+ tagText.setText(tagKeyword);
+ tagText.setMessage("Separated by a space and comma");
+ tagText.setToolTipText("Search Tag Keywords are separated by a space as well as a comma");
+ tagText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+
+ l = new Label(mid, SWT.NONE);
+ l.setText("Pid:");
+
+ pidText = new Text(mid, SWT.SINGLE | SWT.BORDER);
+ if (pidKeyword != null)
+ pidText.setText(pidKeyword);
+ pidText.setMessage("Separated by a space and comma");
+ pidText.setToolTipText("Search Pid Keywords are separated by a space as well as a comma");
+ pidText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+
+ l = new Label(mid, SWT.NONE);
+ l.setText("Message:");
+
+ msgText = new Text(mid, SWT.SINGLE | SWT.BORDER);
+ if (msgKeyword != null)
+ msgText.setText(msgKeyword);
+ msgText.setMessage("Separated by a space and comma");
+ msgText.setToolTipText("Search Message Keywords are separated by a space as well as a comma");
+ msgText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+
+ // bottom part with the ok/cancel
+ Composite bottomComp = new Composite(shell, SWT.NONE);
+ bottomComp.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_CENTER));
+ bottomComp.setLayout(new GridLayout(2, true));
+
+ okButton = new Button(bottomComp, SWT.NONE);
+ okButton.setText("OK");
+ okButton.addSelectionListener(new SelectionAdapter()
+ {
+ @Override
+ public void widgetSelected(SelectionEvent e)
+ {
+ String newName = tabNameText.getText();
+ for (LogTab tab : LogPanel.logTabList)
+ {
+ if (tab.getLogTabName().equals(newName))
+ {
+ if (oldTab != null && oldTab == tab)
+ continue;
+ int ret = FileDialogUtils.checkTabName(newName);
+ if (ret == IDialogConstants.OK_ID)
+ return;
+ }
+ }
+
+ bOk = true;
+
+ if ( isEmpty( tabNameText.getText() ) )
+ {
+ tabName = TEMPNAME + cnt++;
+ }
+ else
+ {
+ tabName = tabNameText.getText();
+ }
+
+ if ( isEmpty( tagText.getText() ) )
+ {
+ tagKeyword = null;
+ }
+ else
+ {
+ tagKeyword = tagText.getText();
+ }
+
+ if ( isEmpty( pidText.getText() ) )
+ {
+ pidKeyword = null;
+ }
+ else
+ {
+ pidKeyword = pidText.getText();
+ }
+
+ if ( isEmpty( msgText.getText() ) )
+ {
+ msgKeyword = null;
+ }
+ else
+ {
+ msgKeyword = msgText.getText();
+ }
+
+ device = dCombo.getItem(dCombo.getSelectionIndex());
+
+ shell.close();
+ }
+ });
+ shell.setDefaultButton(okButton);
+
+ Button cancelButton = new Button(bottomComp, SWT.NONE);
+ cancelButton.setText("Cancel");
+ cancelButton.addSelectionListener(new SelectionAdapter()
+ {
+ @Override
+ public void widgetSelected(SelectionEvent e)
+ {
+ shell.close();
+ }
+ });
+
+ }
+
+ public String getName()
+ {
+ return tabName;
+ }
+
+ public String getDevice()
+ {
+ return device;
+ }
+
+ public String getPidKeyword()
+ {
+ return pidKeyword;
+ }
+
+ public String getTagKeyword()
+ {
+ return tagKeyword;
+ }
+
+ public String getMsgKeyword()
+ {
+ return msgKeyword;
+ }
+
+ public void setName(String name)
+ {
+ this.tabName = name;
+ }
} \ No newline at end of file
diff --git a/org.tizen.common.connection/src/org/tizen/common/connection/log/LogColors.java b/org.tizen.common.connection/src/org/tizen/common/connection/log/LogColors.java
index 83910f970..b7be8325f 100644
--- a/org.tizen.common.connection/src/org/tizen/common/connection/log/LogColors.java
+++ b/org.tizen.common.connection/src/org/tizen/common/connection/log/LogColors.java
@@ -17,6 +17,8 @@ package org.tizen.common.connection.log;
*/
import org.eclipse.swt.graphics.Color;
+import org.eclipse.swt.widgets.Display;
+import org.tizen.common.util.SWTUtil;
public class LogColors {
public Color infoColor;
@@ -24,4 +26,18 @@ public class LogColors {
public Color errorColor;
public Color warningColor;
public Color verboseColor;
+
+ public LogColors(Display display)
+ {
+ infoColor = new Color(display, 66, 120, 157);
+ debugColor = new Color(display, 129, 89, 168);
+ errorColor = new Color(display, 188, 108, 119);
+ warningColor = new Color(display, 191, 106, 51);
+ verboseColor = new Color(display, 90, 90, 90);
+ }
+
+ public void dispose()
+ {
+ SWTUtil.tryDispose(infoColor, debugColor, errorColor, warningColor, verboseColor);
+ }
} \ No newline at end of file
diff --git a/org.tizen.common.connection/src/org/tizen/common/connection/log/LogPanel.java b/org.tizen.common.connection/src/org/tizen/common/connection/log/LogPanel.java
index 12b45b632..2f9427d48 100644..100755
--- a/org.tizen.common.connection/src/org/tizen/common/connection/log/LogPanel.java
+++ b/org.tizen.common.connection/src/org/tizen/common/connection/log/LogPanel.java
@@ -1,28 +1,28 @@
/*
-* Common
-*
-* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
-*
-* Contact:
-* Hoon Kang <h245.kang@samsung.com>
-* Hyunsik Noh <hyunsik.noh@samsung.com>
-*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * Hoon Kang <h245.kang@samsung.com>
+ * Hyunsik Noh <hyunsik.noh@samsung.com>
+ *
* 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.
-*
-* Contributors:
-* - S-Core Co., Ltd
-*
-*/
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
package org.tizen.common.connection.log;
import java.io.File;
@@ -30,10 +30,13 @@ import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
+import java.util.Iterator;
+import java.util.List;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.swt.SWT;
+import org.eclipse.swt.custom.StackLayout;
import org.eclipse.swt.dnd.Clipboard;
import org.eclipse.swt.dnd.TextTransfer;
import org.eclipse.swt.dnd.Transfer;
@@ -65,756 +68,916 @@ import org.tizen.common.connection.ddmuilib.FileDialogUtils;
import org.tizen.common.connection.ddmuilib.ITableFocusListener;
import org.tizen.common.connection.ddmuilib.ITableFocusListener.IFocusedTableActivator;
import org.tizen.common.connection.ddmuilib.Panel;
+import org.tizen.common.connection.explorer.ConnectionExplorerLabelProvider;
import org.tizen.common.util.DialogUtil;
import org.tizen.common.util.NotificationType;
import org.tizen.common.util.NotifierDialog;
+import org.tizen.common.util.SWTUtil;
import org.tizen.sdblib.IDevice;
import org.tizen.sdblib.Log.LogLevel;
import org.tizen.sdblib.SmartDevelopmentBridge;
import org.tizen.sdblib.SmartDevelopmentBridge.IDeviceChangeListener;
-public class LogPanel extends Panel implements IDeviceChangeListener {
-
- public static final int ACTION_NOTHING = 0;
- public static final int ACTION_DEVICE_TAB = 1;
- public static final int ACTION_ADDITIONAL_TAB = 2;
-
- public static ArrayList<LogTab> tabs = new ArrayList<LogTab>();
-
- private String defaultLogSave;
-
- private static int tabCnt = 0;
-
- private Composite parent;
- private TabFolder folders;
- private Table table;
-
- private Combo panelFilterIndex;
- private Text panelFilterKeyword;
-
- private final LogColors colors;
-
- private LogTab currentTab;
-
- private Action[] levelActions;
- private Action addAction;
- private Action removeAction;
- private Action editAction;
- private Action exportAction;
- private Action clearAction;
-
- private Control control;
-
- /** message data, separated from content for multi line messages */
- protected static class LogMessageInfo {
- public LogLevel logLevel;
- public String pidString;
- public String tag;
- public String time;
- }
-
- private ITableFocusListener globalListener;
-
- /** message data, separated from content for multi line messages */
- protected static class LogMessage {
- public LogMessageInfo data;
- public String msg;
-
- @Override
- public String toString() {
- return data.time + ": " + data.logLevel + "/" + data.tag + "(" + data.pidString + "): " + msg;
- }
- }
-
- /**
- * Create the log panel with some default parameters
- *
- * @param colors
- * The display color object
- */
- public LogPanel(LogColors pColors) {
- colors = pColors;
- }
-
- public void setActions(Action[] levels, Action add, Action remove,
- Action edit, Action export, Action clear) {
- levelActions = levels;
- addAction = add;
- removeAction = remove;
- editAction = edit;
- exportAction = export;
- clearAction = clear;
- }
-
- /**
- * Creates a control capable of displaying some information. This is called
- * once, when the application is initializing, from the UI thread.
- */
- @Override
- protected Control createControl(Composite p) {
-
- parent = p;
-
- // create the tab folder
- folders = new TabFolder(parent, SWT.NONE);
- folders.setLayoutData(new GridData(GridData.FILL_BOTH));
- folders.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- selectLogTab();
- }
- });
-
- control = getTabControl(folders);
- SmartDevelopmentBridge.addDeviceChangeListener(this);
- //Create default device tab if device(s) is connectied
- createDefaultTabs();
- selectLogTab();
- return null;
- }
-
- private void selectLogTab()
- {
- //1.get selected tabitem's logtab
- //2.set previous logtab view filter and get selected logtab view filter
- initViewFilter(getCurrentLogTab());
- if (currentTab == null)
- return;
- //remove all message and re-fill message into table from selected logtab msg buffer
- currentTab.initTab();
-
- //set icon selection from selected logtab object
- currentTab.setLevelIcon(levelActions);
-
- //Set action enabled state from selected tab(LotTab object)
- if (currentTab.isDefault()) {
- setActionEnabled(LogPanel.ACTION_DEVICE_TAB);
- } else {
- setActionEnabled(LogPanel.ACTION_ADDITIONAL_TAB);
- }
- }
-
- /**
- *
- * Create the LogFilters with default devicesd
- *
- */
- private void createDefaultTabs() {
- SmartDevelopmentBridge sdbBridge = SmartDevelopmentBridge.getBridge();
- IDevice[] devices = null;
- if (sdbBridge != null) {
- devices = sdbBridge.getDevices();
- }
-
- if (devices != null) {
- for (IDevice device : devices) {
- if (device.isOffline())
- continue;
- LogTab dTab = createDefaultTab(device, null);
- dTab.startLogTab();
- }
- }
- }
-
- private LogTab createDefaultTab(IDevice device, String tabName) {
- LogTab tab = createTab(device, null);
- tab.setDefault();
- setActionEnabled(LogPanel.ACTION_DEVICE_TAB);
- return tab;
- }
-
- private LogTab createTab(IDevice device, String tabName) {
-
- LogTab tab = null;
- if (tabName == null)
- tab = new LogTab(device.getSerialNumber(), device, colors);
- else
- tab = new LogTab(tabName, device, colors);
-
- //
- for (int i = 0; i < tabs.size(); i++) {
- LogTab oldTab = tabs.get(i);
- if (oldTab.getFilterName().equals(tab.getFilterName())) {
- oldTab.stopLogTab(true);
- tabs.remove(i);
- tabCnt--;
- oldTab.dispose();
- if (!tabs.isEmpty())
- folders.setSelection(0);
- }
- }
-
- TabItem item = new TabItem(folders, SWT.NONE, tabCnt++);
-
- item.setText(tab.getFilterName());
- tab.setTable(table);
- item.setControl(control);
- tab.setTab(item);
-
- folders.setSelection(item);
- tabs.add(tab);
-
- if (tab.isDefault()) {
- setActionEnabled(LogPanel.ACTION_DEVICE_TAB);
- } else {
- setActionEnabled(LogPanel.ACTION_ADDITIONAL_TAB);
- }
- tab.setLevelIcon(levelActions);
- return tab;
- }
-
- private void initViewFilter(LogTab tab)
- {
- if(currentTab != null)
- {
- currentTab.setFilterIndexFromPanel(panelFilterIndex.getSelectionIndex());
- currentTab.setFilterKeywordFromPanel(panelFilterKeyword.getText());
- }
-
- currentTab = tab;
-
- if(tab != null)
- {
- panelFilterIndex.select(tab.getFilterIndexFromPanel());
- panelFilterKeyword.setText(tab.getFilterKeywordFromPanel());
- }
- }
-
- private Control getTabControl(TabFolder tabFolder) {
- // Create a composite and add four buttons to it
-
- Composite composite = new Composite(tabFolder, SWT.NONE);
- composite.setLayoutData(new GridData(GridData.FILL_VERTICAL));
- composite.setLayout(new GridLayout(1, false));
-
- Composite mid = new Composite(composite, SWT.NONE);
- mid.setLayoutData(new GridData(GridData.FILL_BOTH));
- mid.setLayout(new FillLayout());
-
- table = new Table(mid, SWT.MULTI | SWT.FULL_SELECTION | SWT.BORDER | SWT.H_SCROLL);
-
- table.setHeaderVisible(true);
- table.setLinesVisible(true);
-
- if (globalListener != null) {
- addTableToFocusListener(table);
- }
-
- ControlListener listener = null;
- listener = new ControlListener() {
- @Override
- public void controlMoved(ControlEvent e) {
-
- }
-
- @Override
- public void controlResized(ControlEvent e) {
- Rectangle r = table.getClientArea();
-
- // get the size of all but the last column
- int total = table.getColumn(0).getWidth();
- total += table.getColumn(1).getWidth();
- total += table.getColumn(2).getWidth();
- total += table.getColumn(3).getWidth();
-//
- if (r.width > total) {
- table.getColumn(4).setWidth(r.width - total);
- }
- }
- };
-
- table.addControlListener(listener);
-
- // then its column
- TableColumn col = createTableColumn(table, "Time", SWT.LEFT,
- "00-00 00:00:00.000");
- col.addControlListener(listener);
-
- col = createTableColumn(table, "Level", SWT.LEFT, "Verbose");
- col.addControlListener(listener);
-
- col = createTableColumn(table, "Pid", SWT.LEFT, "9999999");
- col.addControlListener(listener);
-
- col = createTableColumn(table, "Tag", SWT.LEFT, "ABCDEFGHIJK");
- col.addControlListener(listener);
-
- col = createTableColumn(table, "Message", SWT.LEFT,
- "abcdefghijklmnopqrstuvwxyz0123456789");
-// col.setResizable(false);
-
- Composite bottom = new Composite(composite, SWT.NONE);
- bottom.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- bottom.setLayout(new GridLayout(3, false));
-
- panelFilterIndex = new Combo(bottom, SWT.READ_ONLY);
- String[] comboItems = {"Pid", "Tag", "Message"};
- panelFilterIndex.setItems(comboItems);
- panelFilterIndex.select(2);
- panelFilterIndex.setToolTipText(LogUIMessages.Log_Tooltip_View_Filter_Combo);
- panelFilterIndex.addSelectionListener(new SelectionListener() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- if(currentTab != null)
- {
- int index = panelFilterIndex.getSelectionIndex();
- if (panelFilterKeyword.getText() != null) {
- currentTab.tableRefill(index, panelFilterKeyword.getText());
- }
- }
- }
-
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- }
- });
-
- panelFilterKeyword = new Text(bottom, SWT.SINGLE | SWT.BORDER);
- panelFilterKeyword.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- panelFilterKeyword.setMessage(LogUIMessages.Log_Message_View_Filter_Text);
- panelFilterKeyword.addModifyListener(new ModifyListener() {
-
- @Override
- public void modifyText(ModifyEvent e) {
- if(currentTab != null)
- {
- String keyword = panelFilterKeyword.getText();
- int index = currentTab.getFilterIndexFromPanel();
- panelFilterIndex.select(index);
- if (keyword != null) {
- if (index != -1) {
- currentTab.tableRefill(index, keyword);
- }
- }
- }
- }
- });
-
- return composite;
- }
-
- @Override
- protected void postCreation() {
- // pass
- }
-
- /**
- * Sets the focus to the proper object.
- */
- @Override
- public void setFocus() {
- }
-
- /**
- * Copies the current selection of the current filter as multiline text.
- *
- * @param clipboard
- * The clipboard to place the copied content.
- */
- public void copy(Clipboard clipboard) {
- // get the current table and its selection
- copyTable(clipboard, currentTab.getTable());
- }
-
- /**
- * Selects all lines.
- */
- public void selectAll() {
- currentTab.getTable().selectAll();
- }
-
- /**
- * Sets a TableFocusListener which will be notified when one of the tables
- * gets or loses focus.
- *
- * @param listener
- */
- public void setTableFocusListener(ITableFocusListener listener) {
- // record the global listener, to make sure table created after
- // this call will still be setup.
- globalListener = listener;
-
- for (LogTab tab : tabs) {
- addTableToFocusListener(tab.getTable());
- }
- }
-
- /**
- * Sets up a Table object to notify the global Table Focus listener when it
- * gets or loses the focus.
- *
- * @param table
- * the Table object.
- */
- private void addTableToFocusListener(final Table table) {
- // create the activator for this table
- final IFocusedTableActivator activator = new IFocusedTableActivator() {
- @Override
- public void copy(Clipboard clipboard) {
- copyTable(clipboard, table);
- }
-
- @Override
- public void selectAll() {
- table.selectAll();
- }
- };
-
- // add the focus listener on the table to notify the global
- // listener
- table.addFocusListener(new FocusListener() {
- @Override
- public void focusGained(FocusEvent e) {
- globalListener.focusGained(activator);
- }
-
- @Override
- public void focusLost(FocusEvent e) {
- globalListener.focusLost(activator);
- }
- });
- }
-
- /**
- * Copies the current selection of a Table into the provided Clipboard, as
- * multi-line text.
- *
- * @param clipboard
- * The clipboard to place the copied content.
- * @param table
- * The table to copy from.
- */
- private static void copyTable(Clipboard clipboard, Table table) {
- int[] selection = table.getSelectionIndices();
-
- // we need to sort the items to be sure.
- Arrays.sort(selection);
-
- // all lines must be concatenated.
- StringBuilder sb = new StringBuilder();
-
- // loop on the selection and output the file.
- for (int i : selection) {
- TableItem item = table.getItem(i);
- LogMessage msg = (LogMessage) item.getData();
- String line = msg.toString();
- sb.append(line);
- sb.append('\n');
- }
-
- // now add that to the clipboard
- clipboard.setContents(new Object[] { sb.toString() },
- new Transfer[] { TextTransfer.getInstance() });
- }
-
-
- /**
- * saves the current selection in a text file.
- *
- * @return false if the saving failed.
- */
- public boolean save() {
- if (getCurrentLogTab() == null)
- return false;
- FileDialog dlg = new FileDialog(parent.getShell(), SWT.SAVE);
-
- dlg.setText(LogUIMessages.Log_Title_Tab_Export);
- String fileName = String.format(LogUIMessages.Log_File_Tab_Export_Postfix, getCurrentLogTab().getFilterName());
- dlg.setFileName(fileName);
- String defaultPath = defaultLogSave;
- if (defaultPath == null) {
- defaultPath = System.getProperty("user.home"); //$NON-NLS-1$
- }
- dlg.setFilterPath(defaultPath);
- dlg.setFilterNames(new String[] { LogUIMessages.Log_File_Tab_Export_Filter });
- dlg.setFilterExtensions(new String[] { LogUIMessages.Log_File_Tab_Export_Filter_Extensions });
- File check;
- boolean again;
- do {
- again = false;
- fileName = dlg.open();
- if (fileName == null)
- return false;
- check = new File(fileName);
- if (check.exists()) {
- int ret = FileDialogUtils.getInstance().checkFileOverwrite(fileName);
- if (ret == IDialogConstants.CANCEL_ID)
- again = true;
- }
- } while (again);
-
- if (fileName != null) {
- defaultLogSave = dlg.getFilterPath();
-
- // loop on the selection and output the file.
- try {
- FileWriter writer = new FileWriter(fileName);
-
- for (TableItem item : getCurrentLogTab().getTable().getItems()) {
- LogMessage msg = (LogMessage) item.getData();
- String line = msg.toString();
- writer.write(line);
- writer.write('\n');
- }
- writer.flush();
-
- } catch (IOException e) {
- return false;
- }
- }
-
- return true;
- }
-
- public void clear() {
- if (getCurrentLogTab() != null)
- this.getCurrentLogTab().clear();
- }
-
- private boolean checkTabConnection(LogTab tab, String title)
- {
- String deviceName = tab.getFilterDeviceName();
- if(deviceName == null)
- {
- String tabName = tab.getFilterName();
- String message = String.format(LogUIMessages.Log_Message_Tab_Device_Disconnected, tabName);
- DialogUtil.openErrorDialog(parent.getShell(), title, message);
- return false;
- }
- return true;
- }
-
- public void addTab() {
- LogTab tab = getCurrentLogTab();
- if (tab == null)
- return;
- if(!checkTabConnection(tab, LogUIMessages.Log_Title_Tab_AddTab_Error))
- {
- return ;
- }
-
- AddViewDialog dlg = new AddViewDialog(parent.getShell(), tab.getFilterDeviceName());
- //if base device is already disconnected,
- if(dlg.getDevice() == null)
- return ;
-
- if (dlg.open()) {
- for (IDevice device : SmartDevelopmentBridge.getBridge()
- .getDevices()) {
- if (device.getSerialNumber().equals(dlg.getDevice())) {
-
- LogTab newTab = createTab(device, dlg.getName());
- setTabRefresh(newTab);
- initViewFilter(newTab);
- newTab.setPidFilter(dlg.getPidKeyword());
- newTab.setTagFilter(dlg.getTagKeyword());
- newTab.setMsgFilter(dlg.getMsgKeyword());
-
- newTab.startLogTab();
-
- break;
- }
- }
- } else
- return;
- }
-
- public void removeTab() {
-
- int index = folders.getSelectionIndex();
- if (index < 0)
- return;
- LogTab tab = tabs.get(index);
- if (tab.isDefault()) {
- return;
- }
- tab.stopLogTab(true);
-// tab.dispose();
- folders.getItem(index).dispose();
- tabs.remove(index);
- tabCnt--;
- if (!tabs.isEmpty())
- folders.setSelection(folders.getItemCount());
- selectLogTab();
-
- }
-
- public void editTab() {
-
- LogTab oldTab = getCurrentLogTab();
- if (oldTab == null)
- return;
- if (oldTab.isDefault()) {
- return;
- }
-
- if(!checkTabConnection(oldTab, LogUIMessages.Log_Title_Tab_EditTab_Error))
- {
- return ;
- }
-
- AddViewDialog dlg = new AddViewDialog(parent.getShell(), oldTab);
- if (dlg.open()) {
- for (IDevice device : SmartDevelopmentBridge.getBridge()
- .getDevices()) {
- if (device.getSerialNumber().equals(dlg.getDevice())) {
- boolean bRestart = false;
- if (!oldTab.getFilterDeviceName().equals(
- device.getSerialNumber())) {
- oldTab.stopLogTab(true);
- oldTab.setDevice(device);
- bRestart = true;
- }
-
- for (TabItem item : folders.getItems()) {
- if (item.getText().equals(oldTab.getFilterName())) {
- item.setText(dlg.getName());
- oldTab.setFilterName(dlg.getName());
- }
- }
-
- oldTab.setPidFilter(dlg.getPidKeyword());
- oldTab.setTagFilter(dlg.getTagKeyword());
- oldTab.setMsgFilter(dlg.getMsgKeyword());
-
- if (bRestart)
- {
- oldTab.startLogTab();
- setTabRefresh(oldTab);
- initViewFilter(oldTab);
- }
- else
- {
- oldTab.refill();
- }
- break;
- }
- }
- } else
- return;
- }
-
- public static TableColumn createTableColumn(Table parent, String header,
- int style, String sampleText) {
-
- // create the column
- TableColumn col = new TableColumn(parent, style);
-
- col.setText(sampleText);
- col.pack();
-
- // set the header
- col.setText(header);
-
- return col;
- }
-
- public LogTab getCurrentLogTab() {
- if (tabs.size() != 0) {
- int index = folders.getSelectionIndex();
- LogTab tab = tabs.get(index);
- setTabRefresh(tab);
- return tab;
- } else
- return null;
- }
-
- private void setTabRefresh(LogTab tab)
- {
- for(LogTab anytab : tabs)
- {
- anytab.setPendingAsyncRefresh(false);
- }
- tab.setPendingAsyncRefresh(true);
- }
-
- public void stopAll() {
- for (LogTab tab : tabs) {
- tab.stopLogTab(true);
- }
- tabs.clear();
- tabCnt = 0;
- folders.dispose();
- }
-
- @Override
- public void deviceConnected(IDevice device) {
- if (device.isOnline()) {
- deviceChanged(device, 1);
- }
- }
-
- @Override
- public void deviceDisconnected(final IDevice device) {
- if (parent.isDisposed() == false) {
- Display display = parent.getDisplay();
- display.asyncExec(new Runnable() {
- @Override
- public void run() {
- if (parent.isDisposed() == false) {
- String deviceSN = device.getSerialNumber();
- String title = LogUIMessages.Log_Title_View_Device_Disconnected;
- String message = String.format(LogUIMessages.Log_Message_View_Device_Disconnected, deviceSN, deviceSN);
- NotifierDialog.notify(title, message, NotificationType.DISCONNECTED);
- }
- }
- });
- }
-
- }
-
- @Override
- public void deviceChanged(final IDevice device, int changeMask) {
- if (changeMask == 1) {
- if (parent.isDisposed() == false) {
- Display display = parent.getDisplay();
- display.asyncExec(new Runnable() {
- @Override
- public void run() {
- if (folders.isDisposed() == false) {
- LogTab tab = createDefaultTab(device, null);
- selectLogTab();
- tab.startLogTab();
- } else {
- SmartDevelopmentBridge
- .removeDeviceChangeListener(LogPanel.this);
- }
- }
- });
- }
- }
- }
-
- public void setActionEnabled(int enable) {
-
- if (enable == ACTION_NOTHING) {
-
- addAction.setEnabled(false);
- removeAction.setEnabled(false);
- editAction.setEnabled(false);
- exportAction.setEnabled(false);
- clearAction.setEnabled(false);
- for (Action a : levelActions) {
- a.setEnabled(false);
- }
- } else if (enable == ACTION_DEVICE_TAB) {
- addAction.setEnabled(true);
- removeAction.setEnabled(false);
- editAction.setEnabled(false);
- exportAction.setEnabled(true);
- clearAction.setEnabled(true);
- for (Action a : levelActions) {
- a.setEnabled(true);
- }
- } else if (enable == ACTION_ADDITIONAL_TAB) {
- addAction.setEnabled(true);
- removeAction.setEnabled(true);
- editAction.setEnabled(true);
- exportAction.setEnabled(true);
- clearAction.setEnabled(true);
- for (Action a : levelActions) {
- a.setEnabled(true);
- }
- }
- }
+public class LogPanel extends Panel implements IDeviceChangeListener
+{
+
+ //Nothing enabled
+ public static final int NO_TAB = 0;
+ //Only remove disabled
+ public static final int DEVICE_TAB = 1;
+ //Everything enabled
+ public static final int ADDITIONAL_TAB = 2;
+ //Only add, edit disabled
+ public static final int DISCONNECTED_TAB = 3;
+
+ private final int ENABLE_ADD = 0x0000001;
+ private final int ENABLE_REMOVE = 0x0000010;
+ private final int ENABLE_EDIT = 0x0000100;
+ private final int ENABLE_SCROLL_LOCK = 0x0001000;
+ private final int ENABLE_EXPORT = 0x0010000;
+ private final int ENABLE_CLEAR = 0x0100000;
+ private final int ENABLE_LEVEL = 0x1000000;
+
+ private final int[] ENABLE_VIEW_ACTIONS= { ENABLE_ADD, ENABLE_REMOVE, ENABLE_EDIT,
+ ENABLE_SCROLL_LOCK, ENABLE_EXPORT, ENABLE_CLEAR};
+
+ private String defaultLogSave;
+
+ private Composite parent;
+ private TabFolder tabFolder;
+
+ private final LogColors colors;
+
+ private Action[] levelActions;
+ private Action[] viewActions;
+
+ private StackLayout stackLayout;
+
+ public static List<LogTab> logTabList = new ArrayList<LogTab>();
+
+ /** message data, separated from content for multi line messages */
+ protected static class LogMessageInfo
+ {
+ public LogLevel logLevel;
+ public String pidString;
+ public String tag;
+ public String time;
+ }
+
+ private ITableFocusListener globalListener;
+
+ /** message data, separated from content for multi line messages */
+ protected static class LogMessage
+ {
+ public LogMessageInfo data;
+ public String msg;
+
+ @Override
+ public String toString()
+ {
+ return data.time + ": " + data.logLevel + "/" + data.tag + "(" + data.pidString + "): " + msg;
+ }
+ }
+
+ /**
+ * Create the log panel with some default parameters
+ *
+ * @param colors
+ * The display color object
+ */
+ public LogPanel(LogColors pColors)
+ {
+ colors = pColors;
+ }
+
+ public void setActions(Action[] levelActs, Action[] toolbarActs)
+ {
+ levelActions = levelActs;
+ viewActions = toolbarActs;
+ }
+
+ /**
+ * Creates a control capable of displaying some information. This is called
+ * once, when the application is initializing, from the UI thread.
+ */
+ @Override
+ protected Control createControl(Composite p)
+ {
+ parent = p;
+
+ // create the tab folder
+ tabFolder = new TabFolder(parent, SWT.NONE);
+ tabFolder.setLayoutData(new GridData(GridData.FILL_BOTH));
+ //use stack layout
+ stackLayout = new StackLayout();
+ tabFolder.setLayout(stackLayout);
+ tabFolder.addSelectionListener(new SelectionAdapter()
+ {
+ @Override
+ public void widgetSelected(SelectionEvent e)
+ {
+ selectTabItem();
+ }
+ });
+
+ SmartDevelopmentBridge.addDeviceChangeListener(this);
+ // Create default device tab if device(s) is connected
+ createDefaultTabs();
+ return null;
+ }
+
+ @Override
+ protected void postCreation()
+ {
+ }
+
+ /**
+ * Sets the focus to the proper object.
+ */
+ @Override
+ public void setFocus()
+ {
+ }
+
+ /**
+ * do something when select TabItem
+ */
+ private void selectTabItem()
+ {
+ int index = tabFolder.getSelectionIndex();
+ if(index == -1)
+ {
+ return ;
+ }
+ TabItem item = tabFolder.getItem(index);
+ LogTab logTab = getSelectionLogTab();
+ if(logTab == null)
+ {
+ return ;
+ }
+
+ setEnableAndCheckState(logTab);
+ stackLayout.topControl = item.getControl();
+ }
+
+
+ /**
+ * Set action enable state depending on a logTab type.
+ * And then set check state.
+ * @param logTab
+ */
+ private void setEnableAndCheckState(LogTab logTab)
+ {
+ String serial = logTab.getDeviceSerialNumber();
+ //if device is disconnected, only remove enabled.
+ if(serial == null)
+ {
+ setEnabledForActions(LogPanel.DISCONNECTED_TAB);
+ }
+ else
+ {
+ if (logTab.isDefault())
+ {
+ setEnabledForActions(LogPanel.DEVICE_TAB);
+ }
+ else
+ {
+ setEnabledForActions(LogPanel.ADDITIONAL_TAB);
+ }
+ }
+ setCheckActionState(logTab);
+ }
+
+ /**
+ * When user selects level icons, set level values and filter messages.
+ * @param level level type(Debug, Info, Error..)
+ * @param setCheck is Checked or not
+ */
+ public void setLevel(int level, boolean setCheck)
+ {
+ int levelMode = getSelectionLogTab().getLevelMode();
+ level = (int) Math.pow(2, level);
+
+ if (setCheck)
+ {
+ levelMode |= level;
+ }
+ else
+ {
+ levelMode &= (~level);
+ }
+
+ getSelectionLogTab().setLevelMode(levelMode);
+ getSelectionLogTab().filterMessages();
+ }
+
+ // create the logtab with default devices
+ private void createDefaultTabs()
+ {
+ for (IDevice device : getDevices())
+ {
+ if (device.isOffline())
+ continue;
+ LogTab dTab = createLogTab(ConnectionExplorerLabelProvider.getDeviceSerialWithName(device), device, true);
+ dTab.start();
+ }
+ }
+
+ /**
+ * Create LogTab and TabItem and
+ * set action and icon status
+ * @param device IDevice to get logs
+ * @param name logtab name
+ * @param isDefault check this is default logtab for device
+ * @return
+ */
+ private LogTab createLogTab(String name, IDevice device, boolean isDefault)
+ {
+ Iterator<LogTab> iter = logTabList.iterator();
+ while( iter.hasNext())
+ {
+ LogTab oldTab = iter.next();
+ if(oldTab.getLogTabName().equals(name))
+ {
+ removeTab(oldTab);
+ iter.remove();
+ }
+ }
+
+ LogTab logTab = new LogTab(name, device, colors);
+ if (isDefault)
+ {
+
+ logTab.setDefault();
+ setEnabledForActions(LogPanel.DEVICE_TAB);
+ } else
+ {
+ setEnabledForActions(LogPanel.ADDITIONAL_TAB);
+ }
+ setCheckActionState(logTab);
+
+ logTabList.add(logTab);
+ createTabItem(tabFolder, logTab);
+
+ return logTab;
+ }
+
+ /**
+ * create TabItem and set to LogTab
+ * @param tabFolder
+ * @param logTab
+ * @return
+ */
+ private Control createTabItem(TabFolder tabFolder, final LogTab logTab)
+ {
+ // Create a composite and add four buttons to it
+ Composite composite = new Composite(tabFolder, SWT.NONE);
+ composite.setLayoutData(new GridData(GridData.FILL_VERTICAL));
+ composite.setLayout(new GridLayout(1, false));
+
+ Composite top = new Composite(composite, SWT.NONE);
+ top.setLayoutData(new GridData(GridData.FILL_BOTH));
+ top.setLayout(new FillLayout());
+
+ final Table table = new Table(top, SWT.MULTI | SWT.FULL_SELECTION | SWT.BORDER | SWT.H_SCROLL);
+
+ table.setHeaderVisible(true);
+ table.setLinesVisible(true);
+
+ if (globalListener != null)
+ {
+ addTableToFocusListener(table);
+ }
+
+ ControlListener listener = null;
+ listener = new ControlListener()
+ {
+ @Override
+ public void controlMoved(ControlEvent e)
+ {
+ }
+
+ @Override
+ public void controlResized(ControlEvent e)
+ {
+ Rectangle r = table.getClientArea();
+
+ // get the size of all but the last column
+ int total = table.getColumn(0).getWidth();
+ total += table.getColumn(1).getWidth();
+ total += table.getColumn(2).getWidth();
+ total += table.getColumn(3).getWidth();
+ //
+ if (r.width > total)
+ {
+ table.getColumn(4).setWidth(r.width - total);
+ }
+ }
+ };
+
+ table.addControlListener(listener);
+
+ TableColumn col = createTableColumn(table, "Time", SWT.LEFT, "00-00 00:00:00.000");
+ col.addControlListener(listener);
+
+ col = createTableColumn(table, "Level", SWT.LEFT, "Verbose");
+ col.addControlListener(listener);
+
+ col = createTableColumn(table, "Pid", SWT.LEFT, "9999999");
+ col.addControlListener(listener);
+
+ col = createTableColumn(table, "Tag", SWT.LEFT, "ABCDEFGHIJK");
+ col.addControlListener(listener);
+
+ col = createTableColumn(table, "Message", SWT.LEFT, "abcdefghijklmnopqrstuvwxyz0123456789");
+ // col.setResizable(false);
+
+ Composite bottom = new Composite(composite, SWT.NONE);
+ bottom.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+ bottom.setLayout(new GridLayout(3, false));
+
+ Combo filterComboOnView = new Combo(bottom, SWT.READ_ONLY);
+ String[] comboItems = { "Pid", "Tag", "Message" };
+ filterComboOnView.setItems(comboItems);
+ filterComboOnView.select(2);
+ filterComboOnView.setToolTipText(LogUIMessages.Log_Tooltip_View_Filter_Combo);
+ filterComboOnView.addSelectionListener(new SelectionListener()
+ {
+ @Override
+ public void widgetSelected(SelectionEvent e)
+ {
+ Combo combo = (Combo) e.widget;
+ getSelectionLogTab().setFilterCombo(combo.getSelectionIndex());
+ getSelectionLogTab().filterMessages();
+ }
+
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e)
+ {
+ }
+ });
+
+ Text filterTextOnView = new Text(bottom, SWT.SINGLE | SWT.BORDER);
+ filterTextOnView.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+ filterTextOnView.setMessage(LogUIMessages.Log_Message_View_Filter_Text);
+ filterTextOnView.addModifyListener(new ModifyListener()
+ {
+ @Override
+ public void modifyText(ModifyEvent e)
+ {
+ Text text = (Text) e.widget;
+ getSelectionLogTab().setFilterText(text.getText());
+ getSelectionLogTab().filterMessages();
+ }
+ });
+
+ TabItem tabItem = new TabItem(tabFolder, SWT.NONE, tabFolder.getItemCount());
+ tabItem.setText(logTab.getLogTabName());
+ tabItem.setControl(composite);
+ logTab.setTable(table);
+ logTab.setTabItem(tabItem);
+ tabFolder.setSelection(tabItem);
+ stackLayout.topControl = tabItem.getControl();
+
+ return composite;
+ }
+
+ /**
+ * Copies the current selection of the current filter as multiline text.
+ *
+ * @param clipboard
+ * The clipboard to place the copied content.
+ */
+ public void copy(Clipboard clipboard)
+ {
+ // get the current table and its selection
+ copyTable(clipboard, getSelectionLogTab().getTable());
+ }
+
+ /**
+ * Selects all lines.
+ */
+ public void selectAll()
+ {
+ getSelectionLogTab().getTable().selectAll();
+ }
+
+ /**
+ * Sets a TableFocusListener which will be notified when one of the tables
+ * gets or loses focus.
+ *
+ * @param listener
+ */
+ public void setTableFocusListener(ITableFocusListener listener)
+ {
+ // record the global listener, to make sure table created after
+ // this call will still be setup.
+ globalListener = listener;
+
+ for (LogTab tab : logTabList)
+ {
+ addTableToFocusListener(tab.getTable());
+ }
+ }
+
+ /**
+ * Sets up a Table object to notify the global Table Focus listener when it
+ * gets or loses the focus.
+ *
+ * @param table
+ * the Table object.
+ */
+ private void addTableToFocusListener(final Table table)
+ {
+ // create the activator for this table
+ final IFocusedTableActivator activator = new IFocusedTableActivator()
+ {
+ @Override
+ public void copy(Clipboard clipboard)
+ {
+ copyTable(clipboard, table);
+ }
+
+ @Override
+ public void selectAll()
+ {
+ table.selectAll();
+ }
+ };
+
+ // add the focus listener on the table to notify the global
+ // listener
+ table.addFocusListener(new FocusListener()
+ {
+ @Override
+ public void focusGained(FocusEvent e)
+ {
+ globalListener.focusGained(activator);
+ }
+
+ @Override
+ public void focusLost(FocusEvent e)
+ {
+ globalListener.focusLost(activator);
+ }
+ });
+ }
+
+ /**
+ * Copies the current selection of a Table into the provided Clipboard, as
+ * multi-line text.
+ *
+ * @param clipboard
+ * The clipboard to place the copied content.
+ * @param table
+ * The table to copy from.
+ */
+ private static void copyTable(Clipboard clipboard, Table table)
+ {
+ int[] selection = table.getSelectionIndices();
+
+ // we need to sort the items to be sure.
+ Arrays.sort(selection);
+
+ // all lines must be concatenated.
+ StringBuilder sb = new StringBuilder();
+
+ // loop on the selection and output the file.
+ for (int i : selection)
+ {
+ TableItem item = table.getItem(i);
+ LogMessage msg = (LogMessage) item.getData();
+ String line = msg.toString();
+ sb.append(line);
+ sb.append('\n');
+ }
+
+ // now add that to the clipboard
+ clipboard.setContents(new Object[] { sb.toString() }, new Transfer[] { TextTransfer.getInstance() });
+ }
+
+ public boolean save()
+ {
+ if (getSelectionLogTab() == null)
+ return false;
+ FileDialog dlg = new FileDialog(parent.getShell(), SWT.SAVE);
+
+ dlg.setText(LogUIMessages.Log_Title_Tab_Export);
+ String saveName = String.format(LogUIMessages.Log_File_Tab_Export_Postfix, getSelectionLogTab().getLogTabName());
+
+ dlg.setFileName(saveName);
+ String defaultPath = defaultLogSave;
+ if (defaultPath == null)
+ {
+ defaultPath = System.getProperty("user.home"); //$NON-NLS-1$
+ }
+ dlg.setFilterPath(defaultPath);
+ dlg.setFilterNames(new String[] { LogUIMessages.Log_File_Tab_Export_Filter });
+ dlg.setFilterExtensions(new String[] { LogUIMessages.Log_File_Tab_Export_Filter_Extensions });
+
+ String fileName = null;
+ boolean again;
+ do
+ {
+ File checkFile;
+ again = false;
+ fileName = dlg.open();
+ if (fileName == null)
+ return false;
+ checkFile = new File(fileName);
+ if (checkFile.exists())
+ {
+ int ret = FileDialogUtils.allowFileOverwrite(fileName);
+ if( ret == IDialogConstants.CANCEL_ID)
+ again = true;
+ }
+ } while (again);
+
+ defaultLogSave = dlg.getFilterPath();
+
+ // loop on the selection and output the file.
+ try
+ {
+ FileWriter writer = new FileWriter(fileName);
+
+ for (TableItem item : getSelectionLogTab().getTable().getItems())
+ {
+ LogMessage msg = (LogMessage) item.getData();
+ String line = msg.toString();
+ writer.write(line);
+ writer.write('\n');
+ }
+ writer.flush();
+
+ } catch (IOException e)
+ {
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ *
+ */
+ public void clear()
+ {
+ LogTab tab = getSelectionLogTab();
+ if ( tab != null)
+ tab.clear();
+ }
+
+ /**
+ * check whether device is still connected or not
+ * then notify with dialog
+ *
+ * @param tab target to check device connection
+ * @param title dialog title
+ * @return if device is disconnected, return false
+ */
+ private boolean checkTabConnection(LogTab tab, String title)
+ {
+ String deviceName = tab.getDeviceSerialNumber();
+ if (deviceName == null)
+ {
+ String tabName = tab.getLogTabName();
+ String message = String.format(LogUIMessages.Log_Message_Tab_Device_Disconnected, tabName);
+ DialogUtil.openErrorDialog(parent.getShell(), title, message);
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * add addtional TabItem and LogTab
+ */
+ public void addTab()
+ {
+ LogTab tab = getSelectionLogTab();
+
+ if (tab == null)
+ return;
+
+ if (!checkTabConnection(tab, LogUIMessages.Log_Title_Tab_AddTab_Error))
+ {
+ return;
+ }
+
+ AddViewDialog dlg = new AddViewDialog(parent.getShell(), tab.getDeviceSerialNumber());
+
+ if (dlg.getDevice() == null)
+ return;
+
+ if (dlg.open())
+ {
+ for (IDevice device : getDevices())
+ {
+ if (device.getSerialNumber().equals(dlg.getDevice()))
+ {
+
+ LogTab newTab = createLogTab(dlg.getName(), device, false);
+ // set filter values from addViewDialog
+ newTab.setPidFilter(dlg.getPidKeyword());
+ newTab.setTagFilter(dlg.getTagKeyword());
+ newTab.setMsgFilter(dlg.getMsgKeyword());
+
+ newTab.start();
+
+ break;
+ }
+ }
+ } else
+ return;
+ }
+
+ public void removeTab(LogTab tab)
+ {
+ tab.stop(true);
+ SWTUtil.tryDispose(tab.getTabItem());
+ }
+
+ /**
+ * remove selected TabItem and LogTab
+ */
+ public void removeTab()
+ {
+ int index = tabFolder.getSelectionIndex();
+ if (index < 0)
+ return;
+ LogTab tab = logTabList.get(index);
+ removeTab(tab);
+ logTabList.remove(tab);
+ if(logTabList.isEmpty())
+ {
+ setEnabledForActions(NO_TAB);
+ }
+ }
+
+ /**
+ * edit selected TabItem and LogTab
+ */
+ public void editTab()
+ {
+
+ LogTab oldTab = getSelectionLogTab();
+
+ if (oldTab == null)
+ return;
+
+ if (oldTab.isDefault())
+ {
+ return;
+ }
+
+ if (!checkTabConnection(oldTab, LogUIMessages.Log_Title_Tab_EditTab_Error))
+ {
+ return;
+ }
+
+ AddViewDialog dlg = new AddViewDialog(parent.getShell(), oldTab);
+ if (dlg.open())
+ {
+ for (IDevice device : getDevices())
+ {
+ if (device.getSerialNumber().equals(dlg.getDevice()))
+ {
+ oldTab.stop(true);
+ oldTab.setDevice(device);
+
+ for (TabItem item : tabFolder.getItems())
+ {
+ if (item.getText().equals(oldTab.getLogTabName()))
+ {
+ item.setText(dlg.getName());
+ oldTab.setLogTabName(dlg.getName());
+ }
+ }
+
+ oldTab.setPidFilter(dlg.getPidKeyword());
+ oldTab.setTagFilter(dlg.getTagKeyword());
+ oldTab.setMsgFilter(dlg.getMsgKeyword());
+
+ oldTab.start();
+
+ break;
+ }
+ }
+ }
+ }
+
+ public static TableColumn createTableColumn(Table parent, String header, int style, String sampleText)
+ {
+
+ // create the column
+ TableColumn col = new TableColumn(parent, style);
+
+ col.setText(sampleText);
+ col.pack();
+
+ // set the header
+ col.setText(header);
+
+ return col;
+ }
+
+ /**
+ * get selected logtab from tabitem on folder
+ * @return
+ */
+ public LogTab getSelectionLogTab()
+ {
+ if (logTabList.size() != 0)
+ {
+ int index = tabFolder.getSelectionIndex();
+ TabItem item = tabFolder.getItem(index);
+
+ for(LogTab logTab : logTabList)
+ {
+ if(logTab.getTabItem() == item)
+ return logTab;
+ }
+ }
+ return null;
+ }
+
+ public void stopAllTabItems()
+ {
+ for (LogTab tab : logTabList)
+ {
+ removeTab(tab);
+ }
+ logTabList.clear();
+ }
+
+ private IDevice[] getDevices()
+ {
+ IDevice[] devices;
+ SmartDevelopmentBridge sdbBridge = SmartDevelopmentBridge.getBridge();
+ if(sdbBridge != null)
+ devices = sdbBridge.getDevices();
+ else
+ devices = new IDevice[0];
+ return devices;
+ }
+
+ @Override
+ public void deviceConnected(IDevice device)
+ {
+ if (device.isOnline())
+ {
+ deviceChanged(device, 1);
+ }
+ }
+
+ @Override
+ public void deviceDisconnected(final IDevice device)
+ {
+
+ if (parent.isDisposed() == false)
+ {
+ Display display = parent.getDisplay();
+ display.asyncExec(new Runnable()
+ {
+ @Override
+ public void run()
+ {
+ if (parent.isDisposed() == false)
+ {
+ String name = ConnectionExplorerLabelProvider.getDeviceSerialWithName(device);
+ String title = LogUIMessages.Log_Title_View_Device_Disconnected;
+ String message = String.format(LogUIMessages.Log_Message_View_Device_Disconnected, name, name);
+ NotifierDialog.notify(title, message, NotificationType.DISCONNECTED);
+ for( LogTab tab : logTabList)
+ {
+ if(device.getSerialNumber().equals(tab.getDeviceSerialNumber()))
+ {
+ tab.setDevice(null);
+ }
+ }
+ setEnabledForActions(LogPanel.DISCONNECTED_TAB);
+
+ } else
+ {
+ SmartDevelopmentBridge.removeDeviceChangeListener(LogPanel.this);
+ }
+ }
+ });
+ }
+ }
+
+ @Override
+ public void deviceChanged(final IDevice device, int changeMask)
+ {
+ if (changeMask == 1)
+ {
+ if (parent.isDisposed() == false)
+ {
+ Display display = parent.getDisplay();
+ display.asyncExec(new Runnable()
+ {
+ @Override
+ public void run()
+ {
+ if (tabFolder.isDisposed() == false)
+ {
+ LogTab tab = createLogTab(ConnectionExplorerLabelProvider.getDeviceSerialWithName(device), device, true);
+ tab.start();
+ } else
+ {
+ SmartDevelopmentBridge.removeDeviceChangeListener(LogPanel.this);
+ }
+ }
+ });
+ }
+ }
+ }
+
+ /**
+ * Get enabled state for each action with state value.
+ * @param state
+ * @param action
+ * @return
+ */
+ private boolean getEnabled(int state, int action)
+ {
+ int result = (state & action);
+ return result != 0 ? true : false;
+ }
+
+ private void setEnableState(int state)
+ {
+ for(int i = 0; i < viewActions.length; i++)
+ {
+ viewActions[i].setEnabled(getEnabled(state, ENABLE_VIEW_ACTIONS[i]));
+ }
+
+ boolean check = getEnabled(state, ENABLE_LEVEL);
+ for (Action level : levelActions)
+ {
+ level.setEnabled(check);
+ }
+ }
+
+ /**
+ * Set checked state for action(loglevel, scroll lock) depending on a logTab
+ * when create new logtab or select the logtab.
+ */
+ private void setCheckActionState(LogTab tab)
+ {
+ int levelMode = tab.getLevelMode();
+ for (int i = 0; i < 5; i++)
+ {
+ int a = levelMode & (0x1 << i);
+ levelActions[i].setChecked(a == (int) Math.pow(2, i));
+ }
+
+ //Scroll lock action is toggle action
+ viewActions[3].setChecked(tab.getScrollLock());
+ }
+
+ /**
+ * Get enabled state for action depending on a logTab type.
+ */
+ public int getEnabledStateForActions(int tabType)
+ {
+ int enable = 0x0000000;
+
+ if (tabType == NO_TAB)
+ {
+ }
+ else if (tabType == DEVICE_TAB)
+ {
+ enable = ENABLE_ADD | ENABLE_SCROLL_LOCK | ENABLE_EXPORT | ENABLE_CLEAR | ENABLE_LEVEL;
+ }
+ else if (tabType == ADDITIONAL_TAB)
+ {
+ enable = ENABLE_ADD | ENABLE_REMOVE | ENABLE_EDIT | ENABLE_SCROLL_LOCK | ENABLE_EXPORT | ENABLE_CLEAR | ENABLE_LEVEL;
+ }
+ else if (tabType == DISCONNECTED_TAB)
+ {
+ enable = ENABLE_REMOVE | ENABLE_EXPORT | ENABLE_LEVEL;
+ }
+
+ return enable;
+ }
+
+ /**
+ * Get enabled state and set enabled state for action depending on a logTab type
+ * (NO_TAB, DEVICE_TAB, ADDITIONAL_TAB).
+ * @param tabType
+ */
+ public void setEnabledForActions(int tabType)
+ {
+ int mode = getEnabledStateForActions(tabType);
+ setEnableState(mode);
+ }
+
+ /**
+ * Set scroll locked or unlocked.
+ * @param lock
+ */
+ public void setScrollLock(boolean lock)
+ {
+ getSelectionLogTab().setScrollLock(lock);
+ }
} \ No newline at end of file
diff --git a/org.tizen.common.connection/src/org/tizen/common/connection/log/LogTab.java b/org.tizen.common.connection/src/org/tizen/common/connection/log/LogTab.java
index 9c6f57432..bfd7b6d4d 100644
--- a/org.tizen.common.connection/src/org/tizen/common/connection/log/LogTab.java
+++ b/org.tizen.common.connection/src/org/tizen/common/connection/log/LogTab.java
@@ -1,820 +1,827 @@
/*
-* Common
-*
-* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
-*
-* Contact:
-* Hoon Kang <h245.kang@samsung.com>
-* Hyunsik Noh <hyunsik.noh@samsung.com>
-*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * Hoon Kang <h245.kang@samsung.com>
+ * Hyunsik Noh <hyunsik.noh@samsung.com>
+ *
* 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.
-*
-* Contributors:
-* - S-Core Co., Ltd
-*
-*/
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
package org.tizen.common.connection.log;
import java.util.ArrayList;
+import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
-import org.eclipse.jface.action.Action;
import org.eclipse.swt.SWT;
import org.eclipse.swt.SWTException;
import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.ScrollBar;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableItem;
import org.tizen.common.connection.log.LogPanel.LogMessage;
import org.tizen.common.connection.log.LogPanel.LogMessageInfo;
-import org.tizen.common.console.AnsicodeAdapter;
+import org.tizen.common.ui.view.console.AnsicodeAdapter;
+import org.tizen.common.util.StringUtil;
+import org.tizen.common.util.log.Logger;
import org.tizen.sdblib.IDevice;
-import org.tizen.sdblib.Log;
import org.tizen.sdblib.Log.LogLevel;
import org.tizen.sdblib.MultiLineReceiver;
-public class LogTab {
-
- private static final int STRING_BUFFER_LENGTH = 10000;
-
- public static final int FILTER_NONE = -1;
- public static final int FILTER_PID = 0x0;
- public static final int FILTER_TAG = 0x1;
- public static final int FILTER_MSG = 0x2;
-
- public static final int LEVEL_ALL = 0x1F;
- public static final int LEVEL_VERBOSE = 0x1;
- public static final int LEVEL_DEBUG = 0x2;
- public static final int LEVEL_INFO = 0x4;
- public static final int LEVEL_WARNING = 0x8;
- public static final int LEVEL_ERROR = 0x16;
-
- /**
- * Single level log level as defined in Log.mLevelChar. Only valid if mMode
- * is MODE_LEVEL
- */
- private int levelMode = LEVEL_ALL;
-
- private String[] pidFilter = null;
- private String[] tagFilter = null;
- private String[] msgFilter = null;
-
- private String pidFilterString = null;
- private String tagFilterString = null;
- private String msgFilterString = null;
-
- private int filterIndexFromPanel = FILTER_MSG;
- private String filterKeywordFromPanel = "";
-
- private String filterName = null;
- private IDevice filterDevice = null;
- private LogTabOuputReceiver logger = null;
- private LogColors colors;
-
- private Table table;
- private TabItem tabItem;
-
- private static Pattern logPattern = Pattern
- .compile("^\\[\\s(\\d\\d-\\d\\d\\s\\d\\d:\\d\\d:\\d\\d\\.\\d+)" + //$NON-NLS-1$
- "\\s+(\\d*):\\s*(\\d+)\\s([VDIWE])/(.+)\\s+\\]$");
-
- private final ArrayList<LogMessage> tableMessages = new ArrayList<LogMessage>();
- private final ArrayList<LogMessage> newMessages = new ArrayList<LogMessage>();
- private final LogMessage[] buffer = new LogMessage[STRING_BUFFER_LENGTH];
-
- private LogMessageInfo lastMessageInfo = null;
- private boolean pendingAsyncRefresh = false;
-
- private boolean isDefault = false;
- private int removedMessageCount = 0;
-
- private int indexStart = -1;
- private int indexEnd = -1;
-
- public LogTab(String pName, IDevice pDevice, LogColors pColors) {
- filterName = pName;
- filterDevice = pDevice;
- this.colors = pColors;
- }
-
- public LogTab() {
- }
-
- /** Sets the name of the filter. */
- public void setFilterName(String name) {
- filterName = name;
- }
-
- public void setPidFilter(String pid) {
- pidFilterString = pid;
- if (pid != null)
- pidFilter = setFilter(pid.split("[\\s\t,]"));
- else
- pidFilter = null;
- }
-
- public void setTagFilter(String tag) {
- tagFilterString = tag;
- if (tag != null)
- tagFilter = setFilter(tag.split("[\\s\t,]"));
- else
- tagFilter = null;
- }
-
- public void setMsgFilter(String msg) {
- msgFilterString = msg;
- if (msg != null)
- msgFilter = setFilter(msg.split("[\\s\t,]"));
- else
- msgFilter = null;
- }
-
- private String[] setFilter(String[] array) {
- ArrayList<String> result = new ArrayList<String>();
- for (String s : array) {
- if (s.length() > 0) {
- result.add(s);
- }
- }
- return result.toArray(new String[(result.size())]);
- }
-
- public String getFilterName() {
- return filterName;
- }
-
- public int getLevelMode() {
- return levelMode;
- }
-
- public String getPidFilter() {
- return pidFilterString;
- }
-
- public String getTagFilter() {
- return tagFilterString;
- }
-
- public String getMsgFilter() {
- return msgFilterString;
- }
-
- public String getFilterDeviceName() {
- if(filterDevice != null)
- return filterDevice.getSerialNumber();
- else
- return null;
- }
-
- public void setTab(TabItem pTabItem) {
- tabItem = pTabItem;
- }
-
- public void setTable(Table pTable) {
- table = pTable;
- }
-
- public boolean uiReady() {
- return (table != null && tabItem != null);
- }
-
- /**
- * Returns the UI table object.
- *
- * @return
- */
- public Table getTable() {
- return table;
- }
-
- public void dispose() {
- Display d = tabItem.getDisplay();
-
- d.syncExec(new Runnable() {
- @Override
- public void run() {
- if (tabItem.isDisposed() == false) {
- tabItem.dispose();
- }
- }
- });
- table = null;
- tabItem = null;
- }
-
- public void startLogTab() {
-
- resetUI(false);
-
- if (filterDevice != null) {
-
- // create a new output receiver
- logger = new LogTabOuputReceiver();
-
- // start the LogTab in a different thread
- new Thread(filterDevice.getSerialNumber() + " Logger") { //$NON-NLS-1$
- @Override
- public void run() {
-
- while (filterDevice.isOnline() == false && logger != null && logger.isCancelled == false) {
- try {
- sleep(2000);
- } catch (InterruptedException e) {
- Log.e("LogTab",
- "Device is not online or logger is null/cancelled");
- return;
- }
- }
-
- if (logger == null || logger.isCancelled) {
- return;
- }
-
- try {
-
- filterDevice.executeShellCommand(
- "dlogutil -v long *:v", logger, 0 /* timeout */); //$NON-NLS-1$
- } catch (Exception e) {
- Log.e("LogTab", e);
- } finally {
- logger = null;
- filterDevice = null;
- stopLogTab(false);
- }
- }
- } .start();
- }
- }
-
- /** Stop the current LogTab */
- public void stopLogTab(boolean inUiThread) {
- if (logger != null) {
- logger.isCancelled = true;
-
- logger = null;
-
- clear();
-
- resetUI(inUiThread);
- }
- }
-
- //add message to tableMessages(filtered message) and replace old message to new message
- public boolean addMessage(LogMessage newMessage, LogMessage oldMessage) {
- synchronized (tableMessages) {
- if (oldMessage != null) {
- int index = tableMessages.indexOf(oldMessage);
- if (index != -1) {
- tableMessages.remove(index);
- removedMessageCount++;
- }
-
- index = tableMessages.indexOf(oldMessage);
- if (index != -1) {
- tableMessages.remove(index);
- }
- }
-
- boolean filter = accept(newMessage);
-
- if (filter) {
- tableMessages.add(newMessage);
- newMessages.add(newMessage);
- }
-
- return filter;
- }
- }
-
- boolean accept(LogMessage logMessage) {
- if (logMessage == null)
- return false;
-
- if (levelMode != LEVEL_ALL) {
- int a = 0;
- a = (levelMode & (0x1 << (logMessage.data.logLevel.getPriority() - 2)));
-
- if (a == 0)
- return false;
- }
-
- if (pidFilter != null || tagFilter != null || msgFilter != null) {
- if (pidFilter != null) {
- for (String filter : pidFilter) {
- if (logMessage.data.pidString.contains(
- filter))
- if (tableAccept(logMessage))
- return true;
- }
- }
-
- if (tagFilter != null) {
- for (String filter : tagFilter) {
- if (logMessage.data.tag.toLowerCase().contains(
- filter.toLowerCase()))
- if (tableAccept(logMessage))
- return true;
- }
- }
-
- if (msgFilter != null) {
- for (String filter : msgFilter) {
- if (logMessage.msg.toLowerCase().contains(
- filter.toLowerCase()))
- if (tableAccept(logMessage))
- return true;
- }
- }
- return false;
- }
- if (tableAccept(logMessage))
- return true;
- else
- return false;
- }
-
- public void flush() {
-
- ScrollBar bar = table.getVerticalBar();
- boolean scroll = bar.getMaximum() == bar.getSelection() + bar.getThumb();
-
- int topIndex = table.getTopIndex();
-
- table.setRedraw(false);
-
- int totalCount = newMessages.size();
-
- try {
- // remove the items of the old messages.
- for (int i = 0; i < removedMessageCount && table.getItemCount() > 0; i++) {
- table.remove(0);
- }
-
- // add the new items
- for (int i = 0; i < totalCount; i++) {
- LogMessage msg = newMessages.get(i);
- addTableItem(msg);
- }
- } catch (SWTException e) {
- // log the error and keep going. Content of the LogTab
- // table maybe unexpected
- // but at least ddms won't crash.
- Log.e("LogFilter", e);
- }
-
- // redraw
- table.setRedraw(true);
-
- // scroll if needed, by showing the last item
- if (scroll) {
- totalCount = table.getItemCount();
- if (totalCount > 0) {
- table.showItem(table.getItem(totalCount - 1));
- }
- } else if (removedMessageCount > 0) {
- // we need to make sure the topIndex is still visible.
- // Because really old items are removed from the list, this
- // could make it disappear
- // if we don't change the scroll value at all.
-
- topIndex -= removedMessageCount;
- if (topIndex < 0) {
- // looks like it disappeared. Lets just show the
- // first item
- table.showItem(table.getItem(0));
- } else {
- table.showItem(table.getItem(topIndex));
- }
- }
-
- newMessages.clear();
- removedMessageCount = 0;
-
- }
-
- void setColors(LogColors pColors) {
- colors = pColors;
- }
-
- /**
- * Add a TableItem for the index-th item of the buffer
- *
- * @param filter
- * The index of the table in which to insert the item.
- */
- private void addTableItem(LogMessage msg) {
- TableItem item = new TableItem(table, SWT.NONE);
- item.setText(0, msg.data.time);
- // item.setText(1,
- // new String(new char[]{msg.data.logLevel.getPriorityLetter()}));
- item.setText(2, msg.data.pidString);
- item.setText(3, msg.data.tag);
- item.setText(4, msg.msg);
-
- // add the buffer index as data
- item.setData(msg);
-
- if (msg.data.logLevel == LogLevel.INFO) {
- item.setForeground(colors.infoColor);
- item.setText(1, "Info");
- } else if (msg.data.logLevel == LogLevel.DEBUG) {
- item.setForeground(colors.debugColor);
- item.setText(1, "Debug");
- } else if (msg.data.logLevel == LogLevel.ERROR) {
- item.setForeground(colors.errorColor);
- item.setText(1, "Error");
- } else if (msg.data.logLevel == LogLevel.WARN) {
- item.setForeground(colors.warningColor);
- item.setText(1, "Warn");
- } else if (msg.data.logLevel == LogLevel.WARN) {
- item.setForeground(colors.verboseColor);
- item.setText(1, "Verbose");
- }
- }
-
- /**
- * objects able to receive the output of a remote shell command,
- * specifically a LogTab command in this case
- */
- private final class LogTabOuputReceiver extends MultiLineReceiver {
-
- public boolean isCancelled = false;
-
- public LogTabOuputReceiver() {
- super();
-
- setTrimLine(false);
- }
-
- @Override
- public void processNewLines(String[] lines) {
- if (isCancelled == false) {
- processLogLines(lines);
- }
- }
-
- @Override
- public boolean isCancelled() {
- return isCancelled;
- }
- }
-
- /**
- * Process new Log lines coming from {@link LogCatOuputReceiver}.
- *
- * @param lines the new lines
- */
- protected void processLogLines(String[] lines) {
- // WARNING: this will not work if the string contains more line
- // than
- // the buffer holds.
-
- if (lines.length > STRING_BUFFER_LENGTH) {
- Log.e("LogTab", "Receiving more lines than STRING_BUFFER_LENGTH");
- }
-
- // parse the lines and create LogMessage that are stored in a
- // temporary list
- final ArrayList<LogMessage>newMessages = new ArrayList<LogMessage>();
-
- synchronized (buffer) {
- for (String line : lines) {
- line = AnsicodeAdapter.getStripAnsiString(line);
- // ignore empty lines.
- if (line.length() > 0) {
- // check for header lines.
- Matcher matcher = logPattern.matcher(line);
- if (matcher.matches()) {
- // this is a header line, parse the header and keep it around.
- lastMessageInfo = new LogMessageInfo();
-
- lastMessageInfo.time = matcher.group(1);
- lastMessageInfo.pidString = matcher.group(2);
- lastMessageInfo.logLevel = LogLevel
- .getByLetterString(matcher.group(4));
- lastMessageInfo.tag = matcher.group(5).trim();
- } else {
-
- if (lastMessageInfo == null) {
- return;
- }
-
- // This is not a header line.
- // Create a new LogMessage and process it.
- LogMessage mc = new LogMessage();
-
- // If someone printed a log message with embedded '\n' characters,
- //there will one header line followed by multiple text lines.
- // Use the last header that we saw.
- mc.data = lastMessageInfo;
-
- // tabs seem to display as only 1 tab so we replace the leading tabs by 4 spaces.
- mc.msg = line.replaceAll("\t", " "); //$NON-NLS-1$ //$NON-NLS-2$
-
- // process the new LogMessage.
- processNewMessage(mc);
-
- // store the new LogMessage
- newMessages.add(mc);
- }
- }
- }
-
- if (pendingAsyncRefresh) {
-// pendingAsyncRefresh = true;
-
- try {
- Display display = table.getDisplay();
-
- // run in sync because this will update the
- // buffer start/end indices
- display.asyncExec(new Runnable() {
- @Override
- public void run() {
- asyncRefresh();
- }
- });
- } catch (SWTException e) {
- stopLogTab(false);
- }
- }
- }
- }
-
- /**
- * Processes a new Message.
- * <p/>
- * This adds the new message to the buffer, and gives it to the existing
- * filters.
- *
- * @param newMessage
- */
- private void processNewMessage(LogMessage newMessage) {
-
- // compute the index where the message goes.
- // was the buffer empty?
- int messageIndex = -1;
- if (indexStart == -1) {
- indexStart = 0;
- messageIndex = indexStart;
- indexEnd = 1;
- } else {
- messageIndex = indexEnd;
-
- // check we aren't overwriting start
- if (indexEnd == indexStart) {
- indexStart = (indexStart + 1) % STRING_BUFFER_LENGTH;
- }
-
- // increment the next usable slot index
- indexEnd = (indexEnd + 1) % STRING_BUFFER_LENGTH;
- }
-
- LogMessage oldMessage = null;
-
- // record the message that was there before
- if (buffer[messageIndex] != null) {
- oldMessage = buffer[messageIndex];
- }
-
- // then add the new one
- buffer[messageIndex] = newMessage;
-
- addMessage(newMessage, oldMessage);
- }
-
- /**
- * Refreshes the UI with new messages.
- */
- private void asyncRefresh() {
- if (table.isDisposed() == false) {
- synchronized (buffer) {
- flush();
-// try {
-// // the circular buffer has been updated, let
-// // have the filter flush
-// // their display with the new messages.
-// flush();
-//
-// } finally {
-// // the pending refresh is done.
-// pendingAsyncRefresh = false;
-// }
- }
- } else {
- stopLogTab(true);
- }
- }
-
- public void resetUI(boolean inUiThread) {
-
- // the ui is static we just empty it.
- if (table.isDisposed() == false) {
- if (inUiThread) {
- table.removeAll();
- } else {
- Display d = table.getDisplay();
-
- // run sync as we need to update right now.
- d.syncExec(new Runnable() {
- @Override
- public void run() {
- if (table.isDisposed() == false) {
- table.removeAll();
- }
- }
- });
- }
- }
- }
-
- public void setLevelIcon(Action[] icons) {
- for (int i = 0; i < 5; i++) {
- int a = levelMode & (0x1 << i);
- icons[i].setChecked(a == (int) Math.pow(2, i));
- }
- }
-
- public void initTab() {
-
- // is it empty
- if (uiReady() == false) {
- return;
- }
-
- msgClear();
-
- if (indexStart != -1) {
- int max = indexEnd;
- if (indexEnd < indexStart) {
- max += STRING_BUFFER_LENGTH;
- }
-
- for (int i = indexStart; i < max; i++) {
- int realItemIndex = i % STRING_BUFFER_LENGTH;
-
- addMessage(buffer[realItemIndex], null /** old message*/);
- }
- }
-
- flush();
- }
-
- public void refill() {
- msgClear();
-
- synchronized (buffer) {
- for (LogMessage logMsg : buffer) {
- if (accept(logMsg)) {
- addMessage(logMsg, null);
- }
- }
- }
- flush();
- }
-
- public void tableRefill(int index, String filter) {
-
- filterKeywordFromPanel = filter;
- filterIndexFromPanel = index;
-
- msgClear();
-
- synchronized (buffer) {
- for (LogMessage logMsg : buffer) {
- if (accept(logMsg) && tableAccept(logMsg)) {
- addMessage(logMsg, null);
- }
- }
- }
- flush();
- }
-
- public int getFilterIndexFromPanel()
- {
- return filterIndexFromPanel;
- }
-
- public void setFilterIndexFromPanel(int index)
- {
- filterIndexFromPanel = index;
- }
-
- public String getFilterKeywordFromPanel()
- {
- return filterKeywordFromPanel;
- }
-
- public void setFilterKeywordFromPanel(String keyword)
- {
- filterKeywordFromPanel = keyword;
- }
-
- boolean tableAccept(LogMessage logMessage) {
- if (logMessage == null)
- return false;
-
- if (filterKeywordFromPanel == null || filterKeywordFromPanel.length() == 0)
- return true;
-
- switch(filterIndexFromPanel) {
- case 0:
- {
- String[] filter = filterKeywordFromPanel.split("[\\s\t,]");
- for (int i = 0; i < filter.length; i++) {
- if (logMessage.data.pidString.contains(
- filter[i]))
- return true;
- }
- }
- break;
-
- case 1:
- {
- String[] filter = filterKeywordFromPanel.split("[\\s\t,]");
- for (int i = 0; i < filter.length; i++) {
- if (logMessage.data.tag.toLowerCase().contains(
- filter[i].toLowerCase()))
- return true;
- }
- }
- break;
-
- case 2:
- {
- String[] filter = filterKeywordFromPanel.split("[\\s\t,]");
- for (int i = 0; i < filter.length; i++) {
- if (logMessage.msg.toLowerCase().contains(
- filter[i].toLowerCase()))
- return true;
- }
- }
- break;
-
- default:
- return false;
-
- }
- return false;
- }
-
- public void setLevel(int level, boolean setLevel) {
- level = (int) Math.pow(2, level);
- if (setLevel)
- levelMode |= level;
- else
- levelMode &= (~level);
- }
-
- //remove all filtered messages and tableMessages for refill or init tab
- public void msgClear() {
- removedMessageCount = 0;
- newMessages.clear();
- lastMessageInfo = null;
- tableMessages.clear();
- if (table.isDisposed() == false)
- table.removeAll();
- }
-
- //buffer clear
- public void clear() {
- for (int i = 0; i < STRING_BUFFER_LENGTH; i++) {
- buffer[i] = null;
- }
-
- indexStart = -1;
- indexEnd = -1;
-
- msgClear();
- }
-
- public void setDevice(IDevice device) {
- filterDevice = device;
- }
-
- public void setDefault() {
- isDefault = true;
- }
-
- public boolean isDefault() {
- return isDefault;
- }
-
- public void setPendingAsyncRefresh(boolean b)
- {
- pendingAsyncRefresh = b;
- }
-
+public class LogTab
+{
+
+ private static final int STRING_BUFFER_LENGTH = 5000;
+
+ public static final int FILTER_NONE = -1;
+ public static final int FILTER_PID = 0;
+ public static final int FILTER_TAG = 1;
+ public static final int FILTER_MESSAGE = 2;
+
+ public static final int LEVEL_ALL = 0x1F;
+
+ private int levelMode = LEVEL_ALL;
+
+ //words to filter
+ private String[] pidFilters = null;
+ private String[] tagFilters = null;
+ private String[] msgFilters = null;
+
+ //need to show previous input value when tab dialog is opened
+ private String pidInput = null;
+ private String tagInput = null;
+ private String msgInput = null;
+
+ private int filterCombo = FILTER_MESSAGE;
+ private String filterText = "";
+
+ private String logTabName = null;
+ private IDevice device = null;
+ private LogTabOuputReceiver logReceiver = null;
+ private LogColors colors;
+
+ private Table table;
+ private TabItem tabItem;
+
+ private boolean isScrollLocked;
+
+ private static Pattern logPattern = Pattern.compile("^\\[\\s(\\d\\d-\\d\\d\\s\\d\\d:\\d\\d:\\d\\d\\.\\d+)"
+ + "\\s+(\\d*):\\s*(\\d+)\\s([VDIWE])/(.+)\\s+\\]$");
+
+ //Array to keep all messages from device
+ private final LogMessage[] allMessages = new LogMessage[STRING_BUFFER_LENGTH];
+
+ //List about filtered messages with pidFilters, tagFilters, msgFilters
+ private final List<LogMessage> filteredMessages = new ArrayList<LogMessage>();
+
+ //List about messages need to added table contents
+ private final List<LogMessage> newMessages = new ArrayList<LogMessage>();
+
+ private LogMessageInfo lastMessageInfo = null;
+
+ private boolean isDefault = false;
+
+ //index for allMessages
+ private int indexStart = -1;
+ private int indexEnd = -1;
+
+ public LogTab(String pName, IDevice pDevice, LogColors pColors)
+ {
+ logTabName = pName;
+ device = pDevice;
+ this.colors = pColors;
+ }
+
+ public LogTab()
+ {
+ }
+
+ public void setLogTabName(String name)
+ {
+ logTabName = name;
+ }
+
+ /**
+ * Get logTab name
+ * @return String
+ */
+ public String getLogTabName()
+ {
+ return logTabName;
+ }
+
+ public void setPidFilter(String pid)
+ {
+ pidInput = pid;
+ if (pid != null)
+ pidFilters = setFilter(pid.split("[\\s\t,]"));
+ else
+ pidFilters = null;
+ }
+
+ public void setTagFilter(String tag)
+ {
+ tagInput = tag;
+ if (tag != null)
+ tagFilters = setFilter(tag.split("[\\s\t,]"));
+ else
+ tagFilters = null;
+ }
+
+ public void setMsgFilter(String msg)
+ {
+ msgInput = msg;
+ if (msg != null)
+ msgFilters = setFilter(msg.split("[\\s\t,]"));
+ else
+ msgFilters = null;
+ }
+
+ private String[] setFilter(String[] array)
+ {
+ ArrayList<String> result = new ArrayList<String>();
+ for (String s : array)
+ {
+ if (s.length() > 0)
+ {
+ result.add(s);
+ }
+ }
+ return result.toArray(new String[(result.size())]);
+ }
+
+ public void setLevelMode(int level)
+ {
+ levelMode = level;
+ }
+
+ public int getLevelMode()
+ {
+ return levelMode;
+ }
+
+ public String getPidFilter()
+ {
+ return pidInput;
+ }
+
+ public String getTagFilter()
+ {
+ return tagInput;
+ }
+
+ public String getMsgFilter()
+ {
+ return msgInput;
+ }
+
+ public String getDeviceSerialNumber()
+ {
+ if (device != null)
+ return device.getSerialNumber();
+ else
+ return null;
+ }
+
+ public void setTabItem(TabItem tabItem)
+ {
+ this.tabItem = tabItem;
+ }
+
+ public TabItem getTabItem()
+ {
+ return tabItem;
+ }
+
+ public void setTable(Table table)
+ {
+ this.table = table;
+ }
+
+ /**
+ * Returns the UI table object.
+ *
+ * @return
+ */
+ public Table getTable()
+ {
+ return table;
+ }
+
+ public void start()
+ {
+
+ if (device != null)
+ {
+ // create a new output receiver
+ logReceiver = new LogTabOuputReceiver();
+
+ // start the LogTab in a different thread
+ new Thread(device.getSerialNumber() + " Logger") { //$NON-NLS-1$
+ @Override
+ public void run()
+ {
+ while (device.isOnline() == false && logReceiver != null && logReceiver.isCancelled == false)
+ {
+ try
+ {
+ sleep(2000);
+ } catch (InterruptedException e)
+ {
+ Logger.error("LogTab : Device is not online or logger is null/cancelled", e.getMessage(), e);
+ return;
+ }
+ }
+
+ if (logReceiver == null || logReceiver.isCancelled)
+ {
+ return;
+ }
+
+ try
+ {
+ device.executeShellCommand("dlogutil -v long *:v", logReceiver, 0 /* timeout */); //$NON-NLS-1$
+ } catch (Exception e)
+ {
+ Logger.error("LogTab", e);
+ }
+ }
+ }.start();
+ }
+ }
+
+ /** Stop the current LogTab */
+ public void stop(boolean inUiThread)
+ {
+ if (logReceiver != null)
+ {
+ logReceiver.isCancelled = true;
+
+ logReceiver = null;
+
+ device = null;
+
+ clear();
+
+ }
+ }
+
+ // add message to filtered message and replace old message to
+ // new message
+ public void addFilteredMessage(LogMessage newMessage, LogMessage oldMessage)
+ {
+ synchronized (filteredMessages)
+ {
+ if (oldMessage != null && filteredMessages.size() >= STRING_BUFFER_LENGTH)
+ {
+ int index = filteredMessages.indexOf(oldMessage);
+ if (index != -1)
+ {
+ filteredMessages.remove(index);
+ }
+ }
+
+ boolean isValid = filteredByFilterString(newMessage);
+
+ if (isValid)
+ {
+ filteredMessages.add(newMessage);
+ if(filteredByIconAndText(newMessage))
+ newMessages.add(newMessage);
+ }
+ }
+ }
+
+ /**
+ * action when select level icon and input combo and text to TabItem bottom
+ */
+ public void filterMessages()
+ {
+ //1. remove table contents
+ initialize();
+ //2. filtering
+ synchronized (filteredMessages)
+ {
+ for (LogMessage logMsg : filteredMessages)
+ {
+ if (filteredByIconAndText(logMsg))
+ {
+ newMessages.add(logMsg);
+ }
+ }
+ //3. refill new messages
+ flush();
+ }
+ }
+
+ /**
+ * Filter with tab dialog(AddTab, EditTab) input value
+ * @param logMessage
+ * @return
+ */
+ private boolean filteredByFilterString(LogMessage logMessage)
+ {
+ if (logMessage == null)
+ return false;
+ if (pidFilters != null || tagFilters != null || msgFilters != null)
+ {
+ if (pidFilters != null)
+ {
+ for (String filter : pidFilters)
+ {
+ if (logMessage.data.pidString.contains(filter))
+ return true;
+ }
+ }
+
+ if (tagFilters != null)
+ {
+ for (String filter : tagFilters)
+ {
+ if (logMessage.data.tag.toLowerCase().contains(filter.toLowerCase()))
+ return true;
+ }
+ }
+
+ if (msgFilters != null)
+ {
+ for (String filter : msgFilters)
+ {
+ if (logMessage.msg.toLowerCase().contains(filter.toLowerCase()))
+ return true;
+ }
+ }
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ * Filter with level icon on LogView toolbar
+ * @param logMessage
+ * @return
+ */
+ boolean filteredByIconAndText(LogMessage logMessage)
+ {
+ if (logMessage == null)
+ return false;
+
+ if (levelMode != LEVEL_ALL)
+ {
+ int a = 0;
+ a = (levelMode & (0x1 << (logMessage.data.logLevel.getPriority() - 2)));
+
+ if (a == 0)
+ return false;
+ }
+
+ if (filteredByText(logMessage))
+ {
+ return true;
+ }
+ else
+ {
+ return false;
+ }
+ }
+
+ /**
+ * Filter with text and combo input from TabItem bottom
+ * @param logMessage
+ * @return
+ */
+ boolean filteredByText(LogMessage logMessage)
+ {
+ if (logMessage == null)
+ {
+ return false;
+ }
+
+ if (StringUtil.isEmpty(filterText))
+ {
+ return true;
+ }
+
+ String msg = null;
+ String filter = filterText.toLowerCase();
+
+ switch (filterCombo)
+ {
+ case FILTER_PID:
+ msg = logMessage.data.pidString;
+ break;
+
+ case FILTER_TAG:
+ msg = logMessage.data.tag.toLowerCase();
+ break;
+
+ case FILTER_MESSAGE:
+ msg = logMessage.msg.toLowerCase();
+ break;
+
+ default:
+ return false;
+ }
+
+ if( msg.contains(filter))
+ {
+ return true;
+ }
+ else
+ {
+ return false;
+ }
+ }
+
+ /**
+ * flush valid messages to table and remove
+ */
+ public void flush()
+ {
+ table.setRedraw(false);
+
+ int newCount = newMessages.size();
+
+ try
+ {
+ int totalCount = table.getItemCount() + newCount;
+ if(totalCount > STRING_BUFFER_LENGTH)
+ {
+ int removeCount = totalCount - STRING_BUFFER_LENGTH;
+ //remove over than STRING_BUFFER_LENGTH
+ for (int i = 0; i < removeCount && table.getItemCount() > 0; i++)
+ {
+ table.remove(0);
+ }
+ }
+ // add the new items
+ for (int i = 0; i < newCount; i++)
+ {
+ LogMessage msg = newMessages.get(i);
+ addTableItem(msg);
+ }
+ } catch (SWTException e)
+ {
+ Logger.error("LogFilter", e);
+ }
+
+ //if isScollLocked is false, always shows last table item
+ if(!getScrollLock())
+ {
+ int count = table.getItemCount();
+ if( count > 1)
+ {
+ table.showItem(table.getItem(table.getItemCount() - 1));
+ }
+ }
+
+ table.setRedraw(true);
+
+ newMessages.clear();
+
+ }
+
+ void setColors(LogColors pColors)
+ {
+ colors = pColors;
+ }
+
+ /**
+ * Add a TableItem for the index-th item of the buffer
+ *
+ * @param filter
+ * The index of the table in which to insert the item.
+ */
+ private void addTableItem(LogMessage msg)
+ {
+ TableItem item = new TableItem(table, SWT.NONE);
+ item.setText(0, msg.data.time);
+ item.setText(2, msg.data.pidString);
+ item.setText(3, msg.data.tag);
+ item.setText(4, msg.msg);
+
+ // add the buffer index as data
+ item.setData(msg);
+
+ if (msg.data.logLevel == LogLevel.INFO)
+ {
+ item.setForeground(colors.infoColor);
+ item.setText(1, "Info");
+ } else if (msg.data.logLevel == LogLevel.DEBUG)
+ {
+ item.setForeground(colors.debugColor);
+ item.setText(1, "Debug");
+ } else if (msg.data.logLevel == LogLevel.ERROR)
+ {
+ item.setForeground(colors.errorColor);
+ item.setText(1, "Error");
+ } else if (msg.data.logLevel == LogLevel.WARN)
+ {
+ item.setForeground(colors.warningColor);
+ item.setText(1, "Warning");
+ } else if (msg.data.logLevel == LogLevel.VERBOSE)
+ {
+ item.setForeground(colors.verboseColor);
+ item.setText(1, "Verbose");
+ }
+ }
+
+ /**
+ * objects able to receive the output of a remote shell command,
+ * specifically a LogTab command in this case
+ */
+ private final class LogTabOuputReceiver extends MultiLineReceiver
+ {
+
+ public boolean isCancelled = false;
+
+ public LogTabOuputReceiver()
+ {
+ super();
+
+ setTrimLine(false);
+ }
+
+ @Override
+ public void processNewLines(String[] lines)
+ {
+ if (isCancelled == false)
+ {
+ processLogLines(lines);
+ }
+ }
+
+ @Override
+ public boolean isCancelled()
+ {
+ return isCancelled;
+ }
+ }
+
+ /**
+ * Process new Log lines coming from {@link LogCatOuputReceiver}.
+ *
+ * @param lines
+ * the new lines
+ */
+ protected void processLogLines(String[] lines)
+ {
+ // WARNING: this will not work if the string contains more line
+ // than the buffer holds.
+
+ if (lines.length > STRING_BUFFER_LENGTH)
+ {
+ Logger.error("LogTab : Receiving more lines than " + STRING_BUFFER_LENGTH, "");
+ return ;
+ }
+
+ // parse the lines and create LogMessage that are stored in a temporary
+ // list
+ final ArrayList<LogMessage> newMessages = new ArrayList<LogMessage>();
+
+ synchronized (allMessages)
+ {
+ for (String line : lines)
+ {
+ line = AnsicodeAdapter.getStripAnsiString(line);
+ // ignore empty lines.
+ if (line.length() > 0)
+ {
+ // check for header lines.
+ Matcher matcher = logPattern.matcher(line);
+ if (matcher.matches())
+ {
+ // this is a header line, parse the header and keep it
+ // around.
+ lastMessageInfo = new LogMessageInfo();
+
+ lastMessageInfo.time = matcher.group(1);
+ lastMessageInfo.pidString = matcher.group(2);
+ lastMessageInfo.logLevel = LogLevel.getByLetterString(matcher.group(4));
+ lastMessageInfo.tag = matcher.group(5).trim();
+ } else
+ {
+
+ if (lastMessageInfo == null)
+ {
+ return;
+ }
+
+ // This is not a header line.
+ // Create a new LogMessage and process it.
+ LogMessage mc = new LogMessage();
+
+ // If someone printed a log message with embedded '\n'
+ // characters,
+ // there will one header line followed by multiple text
+ // lines.
+ // Use the last header that we saw.
+ mc.data = lastMessageInfo;
+
+ // tabs seem to display as only 1 tab so we replace the
+ // leading tabs by 4 spaces.
+ mc.msg = line.replaceAll("\t", " "); //$NON-NLS-1$ //$NON-NLS-2$
+
+ // process the new LogMessage.
+ processNewMessage(mc);
+
+ // store the new LogMessage
+ newMessages.add(mc);
+ }
+ }
+ }
+
+ try
+ {
+ Display display = table.getDisplay();
+
+ // run in sync because this will update the
+ // buffer start/end indices
+ display.asyncExec(new Runnable()
+ {
+ @Override
+ public void run()
+ {
+ asyncRefresh();
+ }
+ });
+ } catch (SWTException e)
+ {
+ // display is disposed, stop the LogTab
+ stop(false);
+ }
+ }
+ }
+
+ /**
+ * Processes a new Message.
+ * <p/>
+ * This adds the new message to the buffer, and gives it to the existing
+ * filters.
+ *
+ * @param newMessage
+ */
+ private void processNewMessage(LogMessage newMessage)
+ {
+
+ // compute the index where the message goes.
+ // was the buffer empty?
+ int messageIndex = -1;
+ if (indexStart == -1)
+ {
+ indexStart = 0;
+ messageIndex = indexStart;
+ indexEnd = 1;
+ } else
+ {
+ messageIndex = indexEnd;
+
+ // check we aren't overwriting start
+ if (indexEnd == indexStart)
+ {
+ indexStart = (indexStart + 1) % STRING_BUFFER_LENGTH;
+ }
+
+ // increment the next usable slot index
+ indexEnd = (indexEnd + 1) % STRING_BUFFER_LENGTH;
+ }
+
+ LogMessage oldMessage = null;
+
+ // record the message that was there before
+ if (allMessages[messageIndex] != null)
+ {
+ oldMessage = allMessages[messageIndex];
+ }
+
+ // then add the new one
+ allMessages[messageIndex] = newMessage;
+
+ addFilteredMessage(newMessage, oldMessage);
+ }
+
+ /**
+ * Refreshes the UI with new messages.
+ */
+ private void asyncRefresh()
+ {
+ if (table.isDisposed() == false)
+ {
+ synchronized (allMessages)
+ {
+ flush();
+ }
+ } else
+ {
+ stop(true);
+ }
+ }
+
+ public void resetUI(boolean inUiThread)
+ {
+
+ // the ui is static we just empty it.
+ if (table.isDisposed() == false)
+ {
+ if (inUiThread)
+ {
+ table.removeAll();
+ } else
+ {
+ Display d = table.getDisplay();
+
+ // run sync as we need to update right now.
+ d.syncExec(new Runnable()
+ {
+ @Override
+ public void run()
+ {
+ if (table.isDisposed() == false)
+ {
+ table.removeAll();
+ }
+ }
+ });
+ }
+ }
+ }
+
+
+ public void setFilterCombo(int index)
+ {
+ filterCombo = index;
+ }
+
+ public void setFilterText(String text)
+ {
+ filterText = text;
+ }
+
+ // remove all filtered messages and tableMessages to refill or fill messages
+ public void initialize()
+ {
+ newMessages.clear();
+ lastMessageInfo = null;
+ resetUI(false);
+ }
+
+ // buffer and messages clear
+ public void clear()
+ {
+ synchronized(allMessages)
+ {
+ for (int i = 0; i < STRING_BUFFER_LENGTH; i++)
+ {
+ allMessages[i] = null;
+ }
+ }
+
+ indexStart = -1;
+ indexEnd = -1;
+ filteredMessages.clear();
+ initialize();
+ }
+
+ public void setDevice(IDevice device)
+ {
+ this.device = device;
+ }
+
+ public void setDefault()
+ {
+ isDefault = true;
+ }
+
+ public boolean isDefault()
+ {
+ return isDefault;
+ }
+
+ public void setScrollLock(boolean islock)
+ {
+ isScrollLocked = islock;
+ }
+
+ public boolean getScrollLock()
+ {
+ return isScrollLocked;
+ }
} \ No newline at end of file
diff --git a/org.tizen.common.connection/src/org/tizen/common/connection/log/LogUIMessages.properties b/org.tizen.common.connection/src/org/tizen/common/connection/log/LogUIMessages.properties
index 6f0ab47fa..973028f54 100644
--- a/org.tizen.common.connection/src/org/tizen/common/connection/log/LogUIMessages.properties
+++ b/org.tizen.common.connection/src/org/tizen/common/connection/log/LogUIMessages.properties
@@ -1,17 +1,17 @@
Log = Log
-Log_Title_Tab_AddTab_Error = Add tab error
-Log_Title_Tab_EditTab_Error = Edit tab error
-Log_Title_View_Device_Disconnected = Device is disconnected
+Log_Title_Tab_AddTab_Error = Error in adding a tab
+Log_Title_Tab_EditTab_Error = Error in editing a tab
+Log_Title_View_Device_Disconnected = Device disconnected
Log_Message_Tab_Device_Disconnected = %s tab's device is already disconnected.
Log_Message_View_Device_Disconnected = %s is disconnected.\nThe tabs for %s do not work.
-Log_Message_View_Filter_Text = Search Keywords from this table are separated by a space as well as a comma
+Log_Message_View_Filter_Text = Input search keyword
-Log_Tooltip_View_Filter_Combo = Keyword Search: Pid or Tag, Message
+Log_Tooltip_View_Filter_Combo = Keyword: Pid, Tag, or Message
-Log_Title_Tab_Export = Export Log
+Log_Title_Tab_Export = Export the log
Log_File_Tab_Export_Postfix = %s-log.txt
-Log_File_Tab_Export_Filter = Text Files (*.txt)
+Log_File_Tab_Export_Filter = Text files (*.txt)
Log_File_Tab_Export_Filter_Extensions = *.txt \ No newline at end of file
diff --git a/org.tizen.common.connection/src/org/tizen/common/connection/properties/ConnectionExplorerPermissionPropertyPages.java b/org.tizen.common.connection/src/org/tizen/common/connection/properties/ConnectionExplorerPermissionPropertyPages.java
index 538a41112..f286a6f55 100644..100755
--- a/org.tizen.common.connection/src/org/tizen/common/connection/properties/ConnectionExplorerPermissionPropertyPages.java
+++ b/org.tizen.common.connection/src/org/tizen/common/connection/properties/ConnectionExplorerPermissionPropertyPages.java
@@ -128,14 +128,10 @@ public class ConnectionExplorerPermissionPropertyPages extends PropertyPage {
table.setHeaderVisible(true);
table.setLinesVisible(true);
- TableColumn colMsg = createTableColumn(table, "", SWT.NONE,
- "EXECUTE");
- colMsg = createTableColumn(table, "Read", SWT.NONE,
- "EXECUTE");
- colMsg = createTableColumn(table, "Write", SWT.NONE,
- "EXECUTE");
- colMsg = createTableColumn(table, "Execute", SWT.NONE,
- "EXECUTE");
+ createTableColumn(table, "", SWT.NONE, "EXECUTE");
+ createTableColumn(table, "Read", SWT.NONE, "EXECUTE");
+ createTableColumn(table, "Write", SWT.NONE, "EXECUTE");
+ createTableColumn(table, "Execute", SWT.NONE, "EXECUTE");
itemUser = new TableItem(table, SWT.NONE);
diff --git a/org.tizen.common.connection/src/org/tizen/common/connection/sdblib/dnd/FileEntryDropAdapter.java b/org.tizen.common.connection/src/org/tizen/common/connection/sdblib/dnd/FileEntryDropAdapter.java
index 4b5084ac4..a67e03d6d 100644
--- a/org.tizen.common.connection/src/org/tizen/common/connection/sdblib/dnd/FileEntryDropAdapter.java
+++ b/org.tizen.common.connection/src/org/tizen/common/connection/sdblib/dnd/FileEntryDropAdapter.java
@@ -3,10 +3,10 @@
*
* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
*
-* Contact:
+* Contact:
* Hoon Kang <h245.kang@samsung.com>
* Yoonki Park <yoonki.park@samsung.com>
-*
+*
* 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
@@ -38,7 +38,6 @@ import org.eclipse.ui.part.IDropActionDelegate;
import org.tizen.common.connection.ConnectionPlugin;
import org.tizen.common.connection.ddmuilib.FileDialogUtils;
import org.tizen.common.connection.ddmuilib.console.DdmConsole;
-
import org.tizen.sdblib.SdbCommandRejectedException;
import org.tizen.sdblib.SyncService;
import org.tizen.sdblib.SyncService.ISyncProgressMonitor;
@@ -50,22 +49,22 @@ public class FileEntryDropAdapter implements IDropActionDelegate {
@Override
public boolean run(Object source, Object target) {
IResource resource = null;
-
+
if (target instanceof IAdaptable) {
target = ((IAdaptable) target).getAdapter(IResource.class);
if (target != null && target instanceof IResource) {
resource = (IResource) target;
if (resource.getType() == IResource.FILE && resource.getParent() != null)
- resource = resource.getParent();
+ resource = resource.getParent();
}
}
-
+
String[] entries = FileEntryTransfer.getInstance().fromByteArray(
(byte[]) source);
-
- if (entries.length < 1)
+
+ if (entries.length < 1)
return false;
-
+
SyncService sync = null;
try {
sync = ConnectionPlugin.getDefault().getCurrentDevice().getSyncService();
@@ -82,7 +81,7 @@ public class FileEntryDropAdapter implements IDropActionDelegate {
if (sync != null) {
ISyncProgressMonitor monitor = SyncService.getNullProgressMonitor();
boolean isAlwayCopy = false;
-
+
for (int i = 0; i < entries.length; i++) {
File f = new File(entries[i]);
if (resource == null )
@@ -91,10 +90,10 @@ public class FileEntryDropAdapter implements IDropActionDelegate {
IResource newRes = resource.getWorkspace().getRoot().findMember(localPath);
String localFilePath = resource.getLocation().append(f.getName()).toOSString();
-
+
if (newRes != null) {
if (isAlwayCopy == false) {
- int ret = FileDialogUtils.getInstance().checkOverwrite(f.getName());
+ int ret = FileDialogUtils.checkOverwrite(f.getName());
switch (ret) {
case IDialogConstants.CANCEL_ID :
return false;
@@ -104,7 +103,7 @@ public class FileEntryDropAdapter implements IDropActionDelegate {
case IDialogConstants.NO_ID :
continue;
default:
- }
+ }
}
}
SyncResult result = sync.pullFile(entries[i], localFilePath , monitor);
@@ -121,12 +120,12 @@ public class FileEntryDropAdapter implements IDropActionDelegate {
} catch (CoreException e) {
e.printStackTrace();
}
- }
+ }
}
}
}
return false;
}
-
+
}
diff --git a/org.tizen.common.connection/src/org/tizen/common/connection/ui/ConnectionExplorer.java b/org.tizen.common.connection/src/org/tizen/common/connection/ui/ConnectionExplorer.java
index a572d5c37..f542b3db5 100644..100755
--- a/org.tizen.common.connection/src/org/tizen/common/connection/ui/ConnectionExplorer.java
+++ b/org.tizen.common.connection/src/org/tizen/common/connection/ui/ConnectionExplorer.java
@@ -1,28 +1,28 @@
/*
-* Common
-*
-* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
-*
-* Contact:
-* Hoon Kang <h245.kang@samsung.com>
-* Hyunsik Noh <hyunsik.noh@samsung.com>
-*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * Hoon Kang <h245.kang@samsung.com>
+ * Hyunsik Noh <hyunsik.noh@samsung.com>
+ *
* 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.
-*
-* Contributors:
-* - S-Core Co., Ltd
-*
-*/
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
package org.tizen.common.connection.ui;
import java.io.File;
@@ -45,365 +45,446 @@ import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
+import org.eclipse.swt.widgets.Tree;
+import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.contexts.IContextService;
-import org.eclipse.ui.dialogs.PropertyDialogAction;
import org.eclipse.ui.part.ViewPart;
+import org.tizen.common.TizenHelpContextIds;
import org.tizen.common.connection.ConnectionPlugin;
-import org.tizen.common.connection.ddmuilib.ImageLoader;
import org.tizen.common.connection.explorer.ConnectionExplorerPanel;
-import org.tizen.common.properties.InstallPathConfig;
+import org.tizen.common.core.application.InstallPathConfig;
import org.tizen.common.util.HostUtil;
-
-public class ConnectionExplorer extends ViewPart {
-
- private ConnectionExplorerPanel panel;
- private ImageLoader mloader;
- private ToolBar mToolBar;
-
- private ToolItem pushToolItem;
- private ToolItem pullToolItem;
- private ToolItem emulStartToolItem;
-
- private MenuManager subMenu;
- private Action actionAddFolder;
- private Action actionAddFile;
- private Action actionPush;
- private Action actionPull;
- private Action actionRefresh;
- private Action actionRename;
- private Action actionProperty;
- private Action actionDelete;
-
- private MenuManager menuMgr;
- private static ConnectionExplorer explorer;
-
- private static final String BINARYMESSAGE = "Emulator is not installed or install path is not valid.";
- private static final String EMULATOR_PATH = InstallPathConfig
- .getEmulatorPath();
- private static final String EMULATOR_BATCH = "bin" + File.separatorChar + "emulator-manager.exe";
- private static final String EMULATOR_BINARY = "bin" + File.separatorChar + "emulator-manager";
-
- public static ConnectionExplorer gerDefault() {
- if (explorer == null) {
- explorer = new ConnectionExplorer();
- }
-
- return explorer;
- }
-
- @Override
- public void createPartControl(Composite parent) {
- mloader = ImageLoader.getDdmUiLibLoader();
-
- parent.setLayoutData(new GridData(GridData.FILL_VERTICAL));
- parent.setLayout(new GridLayout(1, false));
-
- Composite top = new Composite(parent, SWT.NONE);
-
- GridLayout gridLayout = new GridLayout();
- gridLayout.numColumns = 3;
- gridLayout.marginWidth = 0;
- gridLayout.marginHeight = 0;
-
- GridData gridData = new GridData(GridData.FILL_HORIZONTAL);
- gridData.horizontalSpan = 2;
-
- top.setLayoutData(gridData);
- top.setLayout(gridLayout);
-
- createToolBar(top, gridData);
-
- Composite bottom = new Composite(parent, SWT.NONE);
- bottom.setLayoutData(new GridData(GridData.FILL_BOTH));
- bottom.setLayout(new FillLayout());
-
- createFileExplorerView(bottom);
- makeActions();
- activateContext();
- initContextMenu();
-
- panel.setToolItems(pushToolItem, pullToolItem, emulStartToolItem);
-
- panel.setActions(subMenu, actionPush,
- actionPull, actionRefresh, actionRename, actionProperty,
- actionDelete);
- }
- private void createFileExplorerView(Composite parent) {
-
- // device explorer
- panel = new ConnectionExplorerPanel();
- panel.createPanel(parent);
- panel.getTreeViewer().getTree().addKeyListener(new KeyAdapter() {
- public void keyPressed(KeyEvent e) {
- handleKeyPressed(e);
- }
- public void keyReleased(KeyEvent e) {
- handleKeyPressed(e);
- }
- });
-
- }
- private void handleKeyPressed(KeyEvent event) {
-
- if (event.keyCode == SWT.F5) {
- actionRefresh();
- } else if (event.keyCode == SWT.F2) {
- actionRename();
- } else if (event.keyCode == SWT.DEL) {
- actionDelete();
- }
- if ((event.stateMask == SWT.ALT) && (event.keyCode == SWT.CR)) {
- actionShowProperty();
- }
- }
- private void actionAddFile() {
-
- panel.addNewFileSelection();
- }
-
- private void actionAddFolder() {
- panel.addNewFolderSelection();
- }
-
- private void actionPush() {
- panel.pushIntoSelection();
- }
-
- private void actionPull() {
- panel.pullSelection();
- }
-
- private void actionRefresh() {
- panel.refreshSelection();
- }
- private void actionDelete() {
- panel.deleteSelection();
- }
- private void actionRename() {
- panel.renameSelection();
- }
- private void actionShowProperty() {
- PropertyDialogAction pda = new PropertyDialogAction(getSite(),
- panel.getTreeViewer());
- pda.run();
- }
- /*
- * make actions
- */
- private void makeActions() {
- subMenu = new MenuManager("Add New..", null);
-
- actionAddFile = new Action() {
- public void run() {
- actionAddFile();
- }
- };
- actionAddFile.setText("Add File");
-
- actionAddFolder = new Action() {
- public void run() {
- actionAddFolder();
- }
- };
- actionAddFolder.setText("Add Folder");
-
- actionPush = new Action() {
- public void run() {
- actionPush();
- }
- };
- actionPush.setText("Push the file");
-
- actionPull = new Action() {
- public void run() {
- actionPull();
- }
- };
- actionPull.setText("Pull the Selection");
-
- // Add refresh action
- actionRefresh = new Action() {
- public void run() {
- actionRefresh();
- }
- };
- actionRefresh.setText("Refresh");
- actionRefresh
- .setActionDefinitionId("org.tizen.common.connection.refresh");
-
- actionRename = new Action() {
- public void run() {
- actionRename();
- }
- };
-
- actionRename.setText("Rename");
- actionRename
- .setActionDefinitionId("org.tizen.common.connection.rename");
-
- actionDelete = new Action() {
- public void run() {
- actionDelete();
- }
- };
- actionDelete.setText("Delete");
- actionDelete
- .setActionDefinitionId("org.tizen.common.connection.delete");
-
- actionProperty = new PropertyDialogAction(getSite(),
- panel.getTreeViewer());
- actionProperty
- .setActionDefinitionId("org.tizen.common.connection.property");
-
- }
- private void initContextMenu() {
- // initalize the context menu
- menuMgr = new MenuManager("Connection Explorer MenuMgr"); //$NON-NLS-1$
- menuMgr.setRemoveAllWhenShown(true);
- menuMgr.addMenuListener(new IMenuListener() {
-
- @Override
- public void menuAboutToShow(IMenuManager manager) {
- fillContextMenu(manager);
- }
- });
-
- Menu menu = menuMgr.createContextMenu(panel.getTreeViewer().getTree());
- panel.getTreeViewer().getTree().setMenu(menu);
- getSite().registerContextMenu(menuMgr, panel.getTreeViewer());
-
- menuMgr.addMenuListener(new IMenuListener() {
- @Override
- public void menuAboutToShow(IMenuManager manager) {
- // Remove team menu from our menu
- IContributionItem[] items = manager.getItems();
- if (items != null) {
- for (int i = 0; i < items.length; i++) {
- IContributionItem item = items[i];
- if (item.getId() != null) {
- if (item.getId().equals("team.main")) {
- manager.remove(item);
- break;
- }
- }
- }
- }
- // Decide whether to enable/disable actions
- panel.setActionState();
- }
- });
- }
-
- private void activateContext() {
-
- IContextService contextService = (IContextService) getSite()
- .getService(IContextService.class);
- contextService
- .activateContext("org.tizen.common.connection.delete.context");
- contextService
- .activateContext("org.tizen.common.connection.rename.context");
- contextService
- .activateContext("org.tizen.common.connection.refresh.context");
- contextService
- .activateContext("org.tizen.common.connection.property.context");
-
- }
- private void fillContextMenu(IMenuManager manager) {
- subMenu.add(actionAddFile);
- subMenu.add(actionAddFolder);
- manager.add(subMenu);
- manager.add(new Separator());
- manager.add(actionPush);
- manager.add(actionPull);
- manager.add(new Separator());
- manager.add(actionRefresh);
- manager.add(new Separator());
- manager.add(actionRename);
- manager.add(actionDelete);
- manager.add(new Separator());
- manager.add(actionProperty);
- manager.add(new Separator());
- }
-
- private void createToolBar(Composite shell, Object layoutData) {
-
- mToolBar = new ToolBar(shell, SWT.NULL);
- mToolBar.setLayoutData(layoutData);
-
- ToolItem item = new ToolItem(mToolBar, SWT.SEPARATOR);
-
- emulStartToolItem = new ToolItem(mToolBar, SWT.PUSH);
- emulStartToolItem.setImage(mloader.loadImage("Emulator_start.gif",
- shell.getDisplay()));
- emulStartToolItem.setToolTipText("Emulator Manager");
- emulStartToolItem.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- try {
- startEmulatorManager();
- } catch (Exception e1) {
- e1.printStackTrace();
- }
- }
- });
- emulStartToolItem.setEnabled(true);
-
- item = new ToolItem(mToolBar, SWT.SEPARATOR);
-
- pushToolItem = new ToolItem(mToolBar, SWT.PUSH);
- pushToolItem
- .setImage(mloader.loadImage("push.gif", shell.getDisplay()));
- pushToolItem.setToolTipText("Push the files");
- pushToolItem.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- panel.pushIntoSelection();
- }
- });
- pushToolItem.setEnabled(false);
-
- item = new ToolItem(mToolBar, SWT.SEPARATOR);
-
- pullToolItem = new ToolItem(mToolBar, SWT.PUSH);
- pullToolItem
- .setImage(mloader.loadImage("pull.gif", shell.getDisplay()));
- pullToolItem.setToolTipText("Pull the selection");
- pullToolItem.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- panel.pullSelection();
- }
- });
- pullToolItem.setEnabled(false);
- item = new ToolItem(mToolBar, SWT.SEPARATOR);
-
- }
-
- @Override
- public void setFocus() {
- }
-
- private void startEmulatorManager() throws Exception {
- String exePath = null;
- int osType = ConnectionPlugin.getDefault().os;
- int linuxType = ConnectionPlugin.getDefault().LINUX;
-
- if (osType == linuxType) {
- exePath = EMULATOR_PATH + File.separatorChar + EMULATOR_BINARY;
- } else {
- exePath = EMULATOR_PATH + File.separatorChar + EMULATOR_BATCH;
- }
-
- if (exePath.equals("") || (!exePath.equals("") && !HostUtil.exists(exePath))) {
- throw new Exception(BINARYMESSAGE);
- }
-
- // FIXME : should implement the lines below based on windows system.
- String command = exePath;
- if (osType == linuxType) {
- command = command + " 1>/dev/null 2>/dev/null &";
-
- HostUtil.execute(command);
- } else {
- HostUtil.batchExecute(command, null, new File(EMULATOR_PATH));
- }
- }
+public class ConnectionExplorer extends ViewPart
+{
+
+ private ConnectionExplorerPanel panel;
+ private Composite parent;
+
+ private ToolBar toolBar;
+
+ private ToolItem pushToolItem;
+ private ToolItem pullToolItem;
+ private ToolItem emulManagerToolItem;
+
+ private MenuManager subMenu;
+ private Action actionAddFolder;
+ private Action actionAddFile;
+ private Action actionPush;
+ private Action actionPull;
+ private Action actionRefresh;
+ private Action actionRename;
+ private Action actionProperty;
+ private Action actionDelete;
+
+ private MenuManager menuMgr;
+ private static ConnectionExplorer explorer;
+
+ private static final String EMULATOR_PATH = InstallPathConfig.getEmulatorPath();
+ private static final String EMULATOR_BATCH = "bin" + File.separatorChar + "emulator-manager.exe";
+ private static final String EMULATOR_BINARY = "bin" + File.separatorChar + "emulator-manager";
+
+ synchronized public static ConnectionExplorer gerDefault()
+ {
+ if (explorer == null)
+ {
+ explorer = new ConnectionExplorer();
+ }
+ return explorer;
+ }
+
+ synchronized public static void release() {
+ explorer = null;
+ }
+
+ @Override
+ public void dispose()
+ {
+ }
+
+ @Override
+ public void createPartControl(Composite p)
+ {
+ parent = p;
+ PlatformUI.getWorkbench().getHelpSystem().setHelp(parent, TizenHelpContextIds.HELP_COMMON_CONNECTION_EXPLORER_CONTEXT);
+ parent.setLayoutData(new GridData(GridData.FILL_VERTICAL));
+ parent.setLayout(new GridLayout(1, false));
+
+ Composite top = new Composite(parent, SWT.NONE);
+
+ GridLayout gridLayout = new GridLayout();
+ gridLayout.numColumns = 3;
+ gridLayout.marginWidth = 0;
+ gridLayout.marginHeight = 0;
+
+ GridData gridData = new GridData(GridData.FILL_HORIZONTAL);
+ gridData.horizontalSpan = 2;
+
+ top.setLayoutData(gridData);
+ top.setLayout(gridLayout);
+
+ createToolBar(top, gridData);
+
+ Composite bottom = new Composite(parent, SWT.NONE);
+ bottom.setLayoutData(new GridData(GridData.FILL_BOTH));
+ bottom.setLayout(new FillLayout());
+
+ createFileExplorerView(bottom);
+ makeActions();
+ activateContext();
+ initContextMenu();
+
+ panel.setToolItems(pushToolItem, pullToolItem, emulManagerToolItem);
+
+ panel.setActions(subMenu, actionPush, actionPull, actionRefresh, actionRename, actionProperty, actionDelete);
+ }
+
+ private void createFileExplorerView(Composite parent)
+ {
+
+ // device explorer
+ panel = new ConnectionExplorerPanel();
+ panel.createPanel(parent);
+ panel.getTreeViewer().getTree().addKeyListener(new KeyAdapter()
+ {
+ @Override
+ public void keyPressed(KeyEvent e)
+ {
+ handleKeyPressed(e);
+ }
+
+ @Override
+ public void keyReleased(KeyEvent e)
+ {
+ }
+ });
+
+ }
+
+ private void handleKeyPressed(KeyEvent event)
+ {
+
+ Tree tree = (Tree) event.widget;
+ int length = tree.getSelectionCount();
+ if (event.keyCode == SWT.F5)
+ {
+ if (length == 1)
+ actionRefresh();
+ } else if (event.keyCode == SWT.F2)
+ {
+ if (length == 1)
+ actionRename();
+ } else if (event.keyCode == SWT.DEL)
+ {
+ actionDelete();
+ }
+ if ((event.stateMask == SWT.ALT) && (event.keyCode == SWT.CR))
+ {
+ actionShowProperty();
+ }
+ }
+
+ private void actionAddFile()
+ {
+ panel.addNewFileSelection();
+ }
+
+ private void actionAddFolder()
+ {
+ panel.addNewFolderSelection();
+ }
+
+ private void actionPush()
+ {
+ panel.pushIntoSelection();
+ }
+
+ private void actionPull()
+ {
+ panel.pullSelection();
+ }
+
+ private void actionRefresh()
+ {
+ panel.refreshSelection();
+ }
+
+ private void actionDelete()
+ {
+ panel.deleteSelection();
+ }
+
+ private void actionRename()
+ {
+ panel.renameSelection();
+ }
+
+ private void actionShowProperty()
+ {
+ panel.showPropertySelection(getSite());
+ }
+
+ /*
+ * make actions
+ */
+ private void makeActions()
+ {
+ subMenu = new MenuManager(ConnectionUIMessages.Explorer_ConetextMenu_New, null);
+
+ actionAddFile = new Action()
+ {
+ @Override
+ public void run()
+ {
+ actionAddFile();
+ }
+ };
+ actionAddFile.setText(ConnectionUIMessages.Explorer_ConetextMenu_File);
+
+ actionAddFolder = new Action()
+ {
+ @Override
+ public void run()
+ {
+ actionAddFolder();
+ }
+ };
+ actionAddFolder.setText(ConnectionUIMessages.Explorer_ConetextMenu_Folder);
+
+ actionPush = new Action()
+ {
+ @Override
+ public void run()
+ {
+ actionPush();
+ }
+ };
+ actionPush.setText(ConnectionUIMessages.Explorer_ConetextMenu_Push);
+
+ actionPull = new Action()
+ {
+ @Override
+ public void run()
+ {
+ actionPull();
+ }
+ };
+ actionPull.setText(ConnectionUIMessages.Explorer_ConetextMenu_Pull);
+
+ // Add refresh action
+ actionRefresh = new Action()
+ {
+ @Override
+ public void run()
+ {
+ actionRefresh();
+ }
+ };
+ actionRefresh.setText(ConnectionUIMessages.Explorer_ConetextMenu_Refresh);
+ actionRefresh.setActionDefinitionId("org.tizen.common.connection.refresh");
+
+ actionRename = new Action()
+ {
+ @Override
+ public void run()
+ {
+ actionRename();
+ }
+ };
+
+ actionRename.setText(ConnectionUIMessages.Explorer_ConetextMenu_Rename);
+ actionRename.setActionDefinitionId("org.tizen.common.connection.rename");
+
+ actionDelete = new Action()
+ {
+ @Override
+ public void run()
+ {
+ actionDelete();
+ }
+ };
+ actionDelete.setText(ConnectionUIMessages.Explorer_ConetextMenu_Delete);
+ actionDelete.setActionDefinitionId("org.tizen.common.connection.delete");
+
+ actionProperty = new Action()
+ {
+ @Override
+ public void run()
+ {
+ panel.showPropertySelection(getSite());
+ }
+ };
+ actionProperty.setText(ConnectionUIMessages.Explorer_ConetextMenu_Property);
+ actionProperty.setActionDefinitionId("org.tizen.common.connection.property");
+
+ }
+
+ private void initContextMenu()
+ {
+ // initalize the context menu
+ menuMgr = new MenuManager("Connection Explorer MenuMgr"); //$NON-NLS-1$
+ menuMgr.setRemoveAllWhenShown(true);
+ menuMgr.addMenuListener(new IMenuListener()
+ {
+
+ @Override
+ public void menuAboutToShow(IMenuManager manager)
+ {
+ fillContextMenu(manager);
+ }
+ });
+
+ Menu menu = menuMgr.createContextMenu(panel.getTreeViewer().getTree());
+ panel.getTreeViewer().getTree().setMenu(menu);
+ getSite().registerContextMenu(menuMgr, panel.getTreeViewer());
+
+ menuMgr.addMenuListener(new IMenuListener()
+ {
+ @Override
+ public void menuAboutToShow(IMenuManager manager)
+ {
+ // Remove team menu from our menu
+ IContributionItem[] items = manager.getItems();
+ if (items != null)
+ {
+ for (IContributionItem item : items)
+ {
+ if (("team.main").equals(item.getId()))
+ {
+ manager.remove(item);
+ break;
+ }
+ }
+ }
+ }
+ });
+ }
+
+ private void activateContext()
+ {
+ IContextService contextService = (IContextService) getSite().getService(IContextService.class);
+ contextService.activateContext("org.tizen.common.connection.delete.context");
+ contextService.activateContext("org.tizen.common.connection.rename.context");
+ contextService.activateContext("org.tizen.common.connection.refresh.context");
+ contextService.activateContext("org.tizen.common.connection.property.context");
+
+ }
+
+ private void fillContextMenu(IMenuManager manager)
+ {
+ subMenu.add(actionAddFile);
+ subMenu.add(actionAddFolder);
+ manager.add(subMenu);
+ manager.add(new Separator());
+ manager.add(actionPush);
+ manager.add(actionPull);
+ manager.add(new Separator());
+ manager.add(actionRefresh);
+ manager.add(new Separator());
+ manager.add(actionRename);
+ manager.add(actionDelete);
+ manager.add(new Separator());
+ manager.add(actionProperty);
+ manager.add(new Separator());
+ }
+
+ private void createToolBar(Composite shell, Object layoutData)
+ {
+
+ toolBar = new ToolBar(shell, SWT.NULL);
+ toolBar.setLayoutData(layoutData);
+
+ new ToolItem(toolBar, SWT.SEPARATOR); // Separator
+
+ emulManagerToolItem = new ToolItem(toolBar, SWT.PUSH);
+ emulManagerToolItem.setImage(ConnectionPlugin.getImageDescriptorFromPlugin("icons/emulator_manager.gif").createImage());
+ emulManagerToolItem.setToolTipText(ConnectionUIMessages.Explorer_Tooltip_EmulatorManager);
+ emulManagerToolItem.addSelectionListener(new SelectionAdapter()
+ {
+ @Override
+ public void widgetSelected(SelectionEvent e)
+ {
+ try
+ {
+ startEmulatorManager();
+ } catch (Exception e1)
+ {
+ e1.printStackTrace();
+ }
+ }
+ });
+ emulManagerToolItem.setEnabled(true);
+
+ new ToolItem(toolBar, SWT.SEPARATOR); // Separator
+
+ pushToolItem = new ToolItem(toolBar, SWT.PUSH);
+ pushToolItem.setImage(ConnectionPlugin.getImageDescriptorFromPlugin("icons/push.gif").createImage());
+ pushToolItem.setToolTipText(ConnectionUIMessages.Explorer_Tooltip_Push);
+ pushToolItem.addSelectionListener(new SelectionAdapter()
+ {
+ @Override
+ public void widgetSelected(SelectionEvent e)
+ {
+ panel.pushIntoSelection();
+ }
+ });
+ pushToolItem.setEnabled(false);
+
+ new ToolItem(toolBar, SWT.SEPARATOR); // Separator
+
+ pullToolItem = new ToolItem(toolBar, SWT.PUSH);
+ pullToolItem.setImage(ConnectionPlugin.getImageDescriptorFromPlugin("icons/pull.gif").createImage());
+ pullToolItem.setToolTipText(ConnectionUIMessages.Explorer_Tooltip_Pull);
+ pullToolItem.addSelectionListener(new SelectionAdapter()
+ {
+ @Override
+ public void widgetSelected(SelectionEvent e)
+ {
+ panel.pullSelection();
+ }
+ });
+ pullToolItem.setEnabled(false);
+ new ToolItem(toolBar, SWT.SEPARATOR); // Separator
+ }
+
+ @Override
+ public void setFocus()
+ {
+ if(parent != null)
+ {
+ parent.setFocus();
+ }
+ }
+
+ private void startEmulatorManager() throws Exception
+ {
+ String exePath = null;
+ int osType = ConnectionPlugin.getDefault().os;
+ int linuxType = ConnectionPlugin.LINUX;
+
+ if (osType == linuxType)
+ {
+ exePath = EMULATOR_PATH + File.separatorChar + EMULATOR_BINARY;
+ } else
+ {
+ exePath = EMULATOR_PATH + File.separatorChar + EMULATOR_BATCH;
+ }
+
+ if (exePath.equals("") || (!exePath.equals("") && !HostUtil.exists(exePath)))
+ {
+ throw new Exception(ConnectionUIMessages.Explorer_Message_EmulatorError);
+ }
+
+ // FIXME : should implement the lines below based on windows system.
+ String command = exePath;
+ if (osType == linuxType)
+ {
+ command = command + " 1>/dev/null 2>/dev/null &";
+
+ HostUtil.execute(command);
+ } else
+ {
+ HostUtil.batchExecute(command, null, new File(EMULATOR_PATH));
+ }
+ }
} \ No newline at end of file
diff --git a/org.tizen.common.connection/src/org/tizen/common/connection/ui/ConnectionUIMessages.java b/org.tizen.common.connection/src/org/tizen/common/connection/ui/ConnectionUIMessages.java
new file mode 100644
index 000000000..b0c28b6e1
--- /dev/null
+++ b/org.tizen.common.connection/src/org/tizen/common/connection/ui/ConnectionUIMessages.java
@@ -0,0 +1,61 @@
+/*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * Kangho Kim <kh5225.kim@samsung.com>
+ * Hyunsik Noh <hyunsik.noh@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common.connection.ui;
+
+import org.eclipse.osgi.util.NLS;
+
+public class ConnectionUIMessages extends NLS
+{
+ private static final String BUNDLE_NAME = ConnectionUIMessages.class.getPackage().getName() + ".ConnectionUIMessages"; //$NON-NLS-1$
+
+ public static String Explorer_ConetextMenu_New;
+ public static String Explorer_ConetextMenu_File;
+ public static String Explorer_ConetextMenu_Folder;
+ public static String Explorer_ConetextMenu_Push;
+ public static String Explorer_ConetextMenu_Pull;
+ public static String Explorer_ConetextMenu_Refresh;
+ public static String Explorer_ConetextMenu_Rename;
+ public static String Explorer_ConetextMenu_Delete;
+ public static String Explorer_ConetextMenu_Property;
+
+ public static String Explorer_Message_Invalid_Character;
+
+ public static String Explorer_Tooltip_EmulatorManager;
+ public static String Explorer_Tooltip_Push;
+ public static String Explorer_Tooltip_Pull;
+
+ public static String Explorer_Message_EmulatorError;
+
+ static
+ {
+ // initialize resource bundle
+ NLS.initializeMessages(BUNDLE_NAME, ConnectionUIMessages.class);
+ }
+
+ private ConnectionUIMessages()
+ {
+ }
+}
diff --git a/org.tizen.common.connection/src/org/tizen/common/connection/ui/ConnectionUIMessages.properties b/org.tizen.common.connection/src/org/tizen/common/connection/ui/ConnectionUIMessages.properties
new file mode 100644
index 000000000..056433f20
--- /dev/null
+++ b/org.tizen.common.connection/src/org/tizen/common/connection/ui/ConnectionUIMessages.properties
@@ -0,0 +1,17 @@
+Explorer_ConetextMenu_New = New
+Explorer_ConetextMenu_File = File
+Explorer_ConetextMenu_Folder = Folder
+Explorer_ConetextMenu_Push = Push the file
+Explorer_ConetextMenu_Pull = Pull the selected content
+Explorer_ConetextMenu_Refresh = Refresh
+Explorer_ConetextMenu_Rename = Rename
+Explorer_ConetextMenu_Delete = Delete
+Explorer_ConetextMenu_Property = Properties
+
+Explorer_Tooltip_EmulatorManager = Emulator Manager
+Explorer_Tooltip_Push = Push the file to the connected target device
+Explorer_Tooltip_Pull = Pull the content from the connected target device
+
+Explorer_Message_Invalid_Character = File contains invalid characters like
+
+Explorer_Message_EmulatorError = Emulator is not installed or the install path is invalid.
diff --git a/org.tizen.common.connection/src/org/tizen/common/connection/ui/LogView.java b/org.tizen.common.connection/src/org/tizen/common/connection/ui/LogView.java
index a48f3923c..837bcd344 100644
--- a/org.tizen.common.connection/src/org/tizen/common/connection/ui/LogView.java
+++ b/org.tizen.common.connection/src/org/tizen/common/connection/ui/LogView.java
@@ -1,28 +1,28 @@
/*
-* Common
-*
-* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
-*
-* Contact:
-* Hoon Kang <h245.kang@samsung.com>
-* Hyunsik Noh <hyunsik.noh@samsung.com>
-*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * Hoon Kang <h245.kang@samsung.com>
+ * Hyunsik Noh <hyunsik.noh@samsung.com>
+ *
* 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.
-*
-* Contributors:
-* - S-Core Co., Ltd
-*
-*/
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
package org.tizen.common.connection.ui;
import org.eclipse.jface.action.Action;
@@ -31,12 +31,13 @@ import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.swt.dnd.Clipboard;
-import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IActionBars;
+import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.actions.ActionFactory;
import org.eclipse.ui.part.ViewPart;
+import org.tizen.common.TizenHelpContextIds;
import org.tizen.common.connection.ConnectionPlugin;
import org.tizen.common.connection.log.LogColors;
import org.tizen.common.connection.log.LogPanel;
@@ -46,184 +47,232 @@ import org.tizen.sdblib.Log.LogLevel;
* The log cat view displays log output from the current device selection.
*
*/
-public final class LogView extends ViewPart {
-
- public static final String ID = "org.tizen.common.connection.ui.LogView"; //$NON-NLS-1$
-
- private LogPanel logPanel;
-
- private Action addAction;
- private Action removeAction;
- private Action editAction;
- private Action exportAction;
- private Action clearAction;
-
- private Action[] logLevelActions;
- private final String[] logLevelIcons = { "icons/log/v.png", //$NON-NLS-1S
- "icons/log/d.png", //$NON-NLS-1S
- "icons/log/i.png", //$NON-NLS-1S
- "icons/log/w.png", //$NON-NLS-1S
- "icons/log/e.png", //$NON-NLS-1S
- };
-
- private Clipboard clipboard;
-
- @Override
- public void createPartControl(Composite parent) {
- Display d = parent.getDisplay();
- LogColors colors = new LogColors();
-
- 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);
-
- addAction = new Action("add Tab") {
- @Override
- public void run() {
- logPanel.addTab();
- }
- };
- addAction.setToolTipText("Add LogTab");
- addAction.setImageDescriptor(ConnectionPlugin.getImageDescriptorFromPlugin("icons/log/Add tab.png"));
-
- removeAction = new Action("Remove Tab") {
- @Override
- public void run() {
- logPanel.removeTab();
- }
- };
- removeAction.setToolTipText("Remove LogTab");
- removeAction.setImageDescriptor(ConnectionPlugin.getImageDescriptorFromPlugin("icons/log/Remove tab.png"));
-
- editAction = new Action("Edit Tab") {
- @Override
- public void run() {
- logPanel.editTab();
- }
- };
- editAction.setToolTipText("Edit LogTab");
- editAction.setImageDescriptor(ConnectionPlugin.getImageDescriptorFromPlugin("icons/log/Edit tab.png"));
-
- exportAction = new Action("Export Log") {
- @Override
- public void run() {
- logPanel.save();
- }
- };
- exportAction.setToolTipText("Export Log");
- exportAction.setImageDescriptor(
- ConnectionPlugin.getImageDescriptorFromPlugin("icons/log/Export Log.png")); //$NON-NLS-1$
-
- clearAction = new Action("Clear Log") {
- @Override
- public void run() {
- logPanel.clear();
- }
- };
- clearAction.setToolTipText("Clear Log");
- clearAction.setImageDescriptor(
- ConnectionPlugin.getImageDescriptorFromPlugin("icons/log/Clear Log.png")); //$NON-NLS-1$
-
- LogLevel[] levels = LogLevel.values();
- logLevelActions = new Action[logLevelIcons.length];
- for (int i = 0; i < logLevelActions.length; i++) {
- String name = levels[i].getStringValue();
- logLevelActions[i] = new Action(name, IAction.AS_CHECK_BOX) {
- @Override
- public void run() {
- // disable the other actions and record
- // current index
- for (int i = 0; i < logLevelActions.length; i++) {
- Action a = logLevelActions[i];
- if (a == this) {
- if (logPanel.getCurrentLogTab() != null) {
- if (a.isChecked())
- a.setChecked(a.isChecked());
- logPanel.getCurrentLogTab().setLevel(i , a.isChecked());
- logPanel.getCurrentLogTab().refill();
- }
- }
- }
- }
- };
- logLevelActions[i].setChecked(true);
- logLevelActions[i].setToolTipText(name);
- logLevelActions[i].setImageDescriptor(ConnectionPlugin.getImageDescriptorFromPlugin(logLevelIcons[i]));
- }
-
- // now create the log view
- logPanel = new LogPanel(colors);
-
- logPanel.setActions(logLevelActions, addAction, removeAction, editAction, exportAction, clearAction);
- placeActions();
- logPanel.setActionEnabled(LogPanel.ACTION_NOTHING);
- logPanel.createPanel(parent);
-
- // setup the copy action
- clipboard = new Clipboard(d);
- IActionBars actionBars = getViewSite().getActionBars();
- actionBars.setGlobalActionHandler(ActionFactory.COPY.getId(), new Action("Copy") {
- @Override
- public void run() {
- logPanel.copy(clipboard);
- }
- });
-
- // setup the select all action
- actionBars.setGlobalActionHandler(ActionFactory.SELECT_ALL.getId(), new Action(
- "Select All") {
- @Override
- public void run() {
- logPanel.selectAll();
- }
- });
- }
-
- @Override
- public void dispose() {
- logPanel.stopAll();
- }
-
- @Override
- public void setFocus() {
- logPanel.setFocus();
- }
-
- /**
- * Place the actions in the ui.
- */
- private void placeActions() {
- IActionBars actionBars = getViewSite().getActionBars();
-
- // first in the menu
- IMenuManager menuManager = actionBars.getMenuManager();
- menuManager.add(addAction);
- menuManager.add(removeAction);
- menuManager.add(editAction);
- menuManager.add(new Separator());
- menuManager.add(exportAction);
- menuManager.add(clearAction);
- menuManager.add(new Separator());
-
- // and then in the toolbar
- IToolBarManager toolBarManager = actionBars.getToolBarManager();
- toolBarManager.add(new Separator());
- for (Action a : logLevelActions) {
- toolBarManager.add(a);
- }
- toolBarManager.add(new Separator());
- toolBarManager.add(addAction);
- toolBarManager.add(removeAction);
- toolBarManager.add(editAction);
- toolBarManager.add(new Separator());
- toolBarManager.add(exportAction);
- toolBarManager.add(clearAction);
- toolBarManager.add(new Separator());
- }
-
- public LogPanel getPanel() {
- return logPanel;
- }
+public final class LogView extends ViewPart
+{
+
+ public static final String ID = "org.tizen.common.connection.ui.LogView"; //$NON-NLS-1$
+
+ private LogPanel logPanel;
+ private Composite parent;
+
+ private Action addAction;
+ private Action removeAction;
+ private Action editAction;
+ private Action scrollLockAction;
+ private Action exportAction;
+ private Action clearAction;
+
+ private Action[] viewActions;
+ private Action[] logLevelActions;
+ private final String[] logLevelIcons = { "icons/log/v.png", //$NON-NLS-1S
+ "icons/log/d.png", //$NON-NLS-1S
+ "icons/log/i.png", //$NON-NLS-1S
+ "icons/log/w.png", //$NON-NLS-1S
+ "icons/log/e.png", //$NON-NLS-1S
+ };
+
+ private Clipboard clipboard;
+ private LogColors colors;
+
+ @Override
+ public void createPartControl(Composite p)
+ {
+ parent = p;
+ PlatformUI.getWorkbench().getHelpSystem().setHelp(parent, TizenHelpContextIds.HELP_COMMON_LOG_CONTEXT);
+ Display d = parent.getDisplay();
+ colors = new LogColors(d);
+
+ addAction = new Action("add Tab")
+ {
+ @Override
+ public void run()
+ {
+ logPanel.addTab();
+ }
+ };
+ addAction.setToolTipText("Add LogTab");
+ addAction.setImageDescriptor(ConnectionPlugin.getImageDescriptorFromPlugin("icons/log/add_tab.png"));
+
+ removeAction = new Action("Remove Tab")
+ {
+ @Override
+ public void run()
+ {
+ logPanel.removeTab();
+ }
+ };
+ removeAction.setToolTipText("Remove LogTab");
+ removeAction.setImageDescriptor(ConnectionPlugin.getImageDescriptorFromPlugin("icons/log/remove_tab.png"));
+
+ editAction = new Action("Edit Tab")
+ {
+ @Override
+ public void run()
+ {
+ logPanel.editTab();
+ }
+ };
+ editAction.setToolTipText("Edit LogTab");
+ editAction.setImageDescriptor(ConnectionPlugin.getImageDescriptorFromPlugin("icons/log/edit_tab.png"));
+
+ scrollLockAction = new Action("Scroll Lock")
+ {
+ @Override
+ public void run()
+ {
+ scrollLockAction.setChecked(scrollLockAction.isChecked());
+ logPanel.setScrollLock(scrollLockAction.isChecked());
+ }
+ };
+ scrollLockAction.setToolTipText("Scroll Lock");
+ scrollLockAction.setChecked(false);
+ scrollLockAction.setImageDescriptor(ConnectionPlugin.getImageDescriptorFromPlugin("icons/log/scroll_lock.png"));
+
+ exportAction = new Action("Export the log")
+ {
+ @Override
+ public void run()
+ {
+ logPanel.save();
+ }
+ };
+ exportAction.setToolTipText("Export the log");
+ exportAction.setImageDescriptor(ConnectionPlugin.getImageDescriptorFromPlugin("icons/log/export_log.png")); //$NON-NLS-1$
+
+ clearAction = new Action("Clear the log")
+ {
+ @Override
+ public void run()
+ {
+ logPanel.clear();
+ }
+ };
+ clearAction.setToolTipText("Clear the log");
+ clearAction.setImageDescriptor(ConnectionPlugin.getImageDescriptorFromPlugin("icons/log/clear_log.png")); //$NON-NLS-1$
+
+ LogLevel[] levels = LogLevel.values();
+ logLevelActions = new Action[logLevelIcons.length];
+ for (int i = 0; i < logLevelActions.length; i++)
+ {
+ String name = levels[i].getStringValue();
+ logLevelActions[i] = new Action(name, IAction.AS_CHECK_BOX)
+ {
+ @Override
+ public void run()
+ {
+ // disable the other actions and record
+ // current index
+ for (int i = 0; i < logLevelActions.length; i++)
+ {
+ Action a = logLevelActions[i];
+ if (a == this)
+ {
+ if (logPanel.getSelectionLogTab() != null)
+ {
+ if (a.isChecked())
+ a.setChecked(a.isChecked());
+ logPanel.setLevel(i, a.isChecked());
+ }
+ }
+ }
+ }
+ };
+ logLevelActions[i].setChecked(true);
+ logLevelActions[i].setToolTipText(name);
+ logLevelActions[i].setImageDescriptor(ConnectionPlugin.getImageDescriptorFromPlugin(logLevelIcons[i]));
+ }
+
+ // now create the log view
+ logPanel = new LogPanel(colors);
+ viewActions = new Action[]{addAction, removeAction, editAction, scrollLockAction, exportAction, clearAction};
+ logPanel.setActions(logLevelActions, viewActions);
+ placeActions();
+ logPanel.setEnabledForActions(LogPanel.NO_TAB);
+ logPanel.createPanel(parent);
+
+ // setup the copy action
+ clipboard = new Clipboard(d);
+ IActionBars actionBars = getViewSite().getActionBars();
+ actionBars.setGlobalActionHandler(ActionFactory.COPY.getId(), new Action("Copy")
+ {
+ @Override
+ public void run()
+ {
+ logPanel.copy(clipboard);
+ }
+ });
+
+ // setup the select all action
+ actionBars.setGlobalActionHandler(ActionFactory.SELECT_ALL.getId(), new Action("Select All")
+ {
+ @Override
+ public void run()
+ {
+ logPanel.selectAll();
+ }
+ });
+ }
+
+ @Override
+ public void dispose()
+ {
+ if (clipboard != null && !clipboard.isDisposed())
+ {
+ clipboard.dispose();
+ }
+ logPanel.stopAllTabItems();
+ colors.dispose();
+ super.dispose();
+ }
+
+ @Override
+ public void setFocus()
+ {
+ if(parent != null)
+ {
+ parent.setFocus();
+ }
+ logPanel.setFocus();
+ }
+
+ /**
+ * Place the actions in the ui.
+ */
+ private void placeActions()
+ {
+ IActionBars actionBars = getViewSite().getActionBars();
+
+ // first in the menu
+ IMenuManager menuManager = actionBars.getMenuManager();
+ menuManager.add(addAction);
+ menuManager.add(removeAction);
+ menuManager.add(editAction);
+ menuManager.add(new Separator());
+ menuManager.add(exportAction);
+ menuManager.add(clearAction);
+ menuManager.add(new Separator());
+
+ // and then in the toolbar
+ IToolBarManager toolBarManager = actionBars.getToolBarManager();
+ toolBarManager.add(new Separator());
+ for (Action a : logLevelActions)
+ {
+ toolBarManager.add(a);
+ }
+ toolBarManager.add(new Separator());
+ toolBarManager.add(addAction);
+ toolBarManager.add(removeAction);
+ toolBarManager.add(editAction);
+ toolBarManager.add(new Separator());
+ toolBarManager.add(scrollLockAction);
+ toolBarManager.add(new Separator());
+ toolBarManager.add(exportAction);
+ toolBarManager.add(clearAction);
+ toolBarManager.add(new Separator());
+ }
+
+ public LogPanel getPanel()
+ {
+ return logPanel;
+ }
} \ No newline at end of file
diff --git a/org.tizen.common.connection/src/org/tizen/common/connection/ui/TizenRemoteFileDialog.java b/org.tizen.common.connection/src/org/tizen/common/connection/ui/TizenRemoteFileDialog.java
index d5ec924f9..2acb7d20c 100644
--- a/org.tizen.common.connection/src/org/tizen/common/connection/ui/TizenRemoteFileDialog.java
+++ b/org.tizen.common.connection/src/org/tizen/common/connection/ui/TizenRemoteFileDialog.java
@@ -3,10 +3,10 @@
*
* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
*
-* Contact:
+* Contact:
* Hoon Kang <h245.kang@samsung.com>
* Yoonki Park <yoonki.park@samsung.com>
-*
+*
* 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
@@ -25,12 +25,17 @@
*/
package org.tizen.common.connection.ui;
+import java.io.IOException;
+
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.SWT;
-import org.eclipse.swt.SWTException;
+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.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;
@@ -39,23 +44,26 @@ 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.ScrollBar;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeColumn;
import org.eclipse.swt.widgets.TreeItem;
-
+import org.tizen.common.TizenPlatformConstants;
+import org.tizen.common.util.log.Logger;
import org.tizen.sdblib.FileListingService.FileEntry;
import org.tizen.sdblib.IDevice;
+import org.tizen.sdblib.MultiLineReceiver;
public class TizenRemoteFileDialog {
- public enum TizenRemoteFileDialogResult {
- OK,
- CANCEL
- }
-
- private TizenRemoteFileDialogResult result = TizenRemoteFileDialogResult.CANCEL;
- private IDevice device;
+ public enum TizenRemoteFileDialogResult {
+ OK,
+ CANCEL
+ }
+
+ private TizenRemoteFileDialogResult result = TizenRemoteFileDialogResult.CANCEL;
+ private IDevice device;
private Shell shell;
private Display display;
private boolean isDirOnly = false;
@@ -64,13 +72,11 @@ public class TizenRemoteFileDialog {
private FileEntry selectedDir;
private Tree pathTree;
private TreeViewer pathTreeViewer;
+ private Composite upper;
TizenRemoteFileContentProvider remoteContentProvider = null;
- public TizenRemoteFileDialog(Shell parent, String dlgTitle, IDevice device,
- boolean isDirOnly, String defaultPath)
- throws IllegalArgumentException {
-
+ public TizenRemoteFileDialog(Shell parent, String dlgTitle, IDevice device, boolean isDirOnly, String defaultPath) throws IllegalArgumentException {
if (parent == null || device == null)
throw new IllegalArgumentException();
@@ -78,14 +84,22 @@ public class TizenRemoteFileDialog {
shell = createNewShell(parent);
shell.setText(dlgTitle);
shell.setSize(300, 400);
+ shell.addListener(SWT.Traverse, new Listener() {
+ public void handleEvent(Event event) {
+ switch (event.detail) {
+ case SWT.TRAVERSE_ESCAPE:
+ shell.close();
+ event.detail = SWT.TRAVERSE_NONE;
+ event.doit = false;
+ break;
+ }
+ }
+ });
this.device = device;
this.isDirOnly = isDirOnly;
- if (defaultPath != null)
- this.defaultPath = defaultPath;
- else
- this.defaultPath = "/";
+ setDefaultPath(defaultPath);
createControls(shell);
}
@@ -101,7 +115,7 @@ public class TizenRemoteFileDialog {
}
private void createControls(Composite parent) {
- Composite upper = new Composite(parent, SWT.NONE);
+ upper = new Composite(parent, SWT.NONE);
setUpperLayout(upper);
createPathLabels(upper);
createPathTree(upper);
@@ -112,18 +126,22 @@ public class TizenRemoteFileDialog {
}
private void fillPathTree() {
- createTreeColumn();
- createTreeViewer();
-
+ createTreeColumn();
+ createTreeViewer();
+
FileEntry root = device.getFileListingService().getRoot();
String[] defaultExpandedPath = defaultPath.substring(1).split("/");
cacheChild(root, defaultExpandedPath);
-
+
pathTreeViewer.setInput(root);
pathTreeViewer.expandAll();
-
+
selectDefaultPath(defaultExpandedPath);
+ // set default path to the top item.
+ if (pathTree.getSelection().length > 0)
+ pathTreeViewer.getTree().setTopItem(pathTree.getSelection()[0]);
+
remoteContentProvider.setInitialize(true);
pathTreeViewer.refresh();
@@ -133,7 +151,7 @@ public class TizenRemoteFileDialog {
TreeItem[] items = pathTree.getSelection();
if (items.length == 1) {
Object object = items[0].getData();
- if (object instanceof FileEntry) {
+ if (object instanceof FileEntry) {
selectedDir = (FileEntry) object;
path.setText(selectedDir.getFullPath());
}
@@ -159,7 +177,7 @@ public class TizenRemoteFileDialog {
}
}
}
-
+
if (found != null) {
pathTree.select(found);
Object data = found.getData();
@@ -179,9 +197,40 @@ public class TizenRemoteFileDialog {
}
private void createTreeColumn() {
- TreeColumn nameColumn = new TreeColumn(pathTree, SWT.LEFT);
+ final TreeColumn nameColumn = new TreeColumn(pathTree, SWT.LEFT);
nameColumn.setText("Name");
nameColumn.setWidth(100);
+
+ upper.addControlListener(new ControlAdapter() {
+ public void controlResized(ControlEvent e) {
+ Rectangle area = upper.getClientArea();
+ Point size = pathTree.computeSize(SWT.DEFAULT, SWT.DEFAULT);
+ ScrollBar vBar = pathTree.getVerticalBar();
+ int width = area.width - pathTree.computeTrim(0,0,0,0).width - vBar.getSize().x;
+ if (size.y > area.height + pathTree.getHeaderHeight()) {
+ // Subtract the scrollbar width from the total column width
+ // if a vertical scrollbar will be required
+ Point vBarSize = vBar.getSize();
+ width -= vBarSize.x;
+ }
+ Point oldSize = pathTree.getSize();
+ if (oldSize.x > area.width) {
+ // table is getting smaller so make the columns
+ // smaller first and then resize the table to
+ // match the client area width
+ //nameColumn.setWidth(width);
+ nameColumn.pack();
+ pathTree.setSize(area.width, area.height);
+ } else {
+ // table is getting bigger so make the table
+ // bigger first and then make the columns wider
+ // to match the client area width
+ pathTree.setSize(area.width, area.height);
+ //nameColumn.setWidth(width);
+ nameColumn.pack();
+ }
+ }
+ });
}
private void cacheChild(FileEntry root, String[] defaultExpandedPath) {
@@ -247,7 +296,8 @@ public class TizenRemoteFileDialog {
}
private void createPathTree(Composite pParent) {
- pathTree = new Tree(pParent, SWT.MULTI | SWT.FULL_SELECTION | SWT.VIRTUAL);
+ // if add SWT.VIRTUAL, horizontal scrol is not shown in case of Linux
+ pathTree = new Tree(pParent, SWT.MULTI | SWT.FULL_SELECTION);
setTreeLayout(pathTree);
}
@@ -272,7 +322,7 @@ public class TizenRemoteFileDialog {
}
break;
default:
-
+
}
}
});
@@ -309,21 +359,30 @@ public class TizenRemoteFileDialog {
}
private void runEventLoop(Shell loopShell) {
- Display tmpDisplay = null;
-
- if (shell == null)
- tmpDisplay = Display.getCurrent();
- else
- tmpDisplay = loopShell.getDisplay();
-
- while (loopShell != null && !loopShell.isDisposed()) {
- try {
- if (!tmpDisplay.readAndDispatch())
- tmpDisplay.sleep();
- } catch (SWTException e) {
- e.printStackTrace();
- }
+ Display tmpDisplay = loopShell.getDisplay();
+
+ while (!loopShell.isDisposed()) {
+ if (!tmpDisplay.readAndDispatch())
+ tmpDisplay.sleep();
}
display.update();
}
+
+ private void setDefaultPath(final String corePath) {
+ if (corePath == null)
+ defaultPath = "/";
+
+ String command = "ls " + TizenPlatformConstants.PRIVATE_PLATFORM_CORE_PATH + "/*/files/core.* 2&>/dev/null | wc -l";
+
+ try {
+ this.device.executeShellCommand(command, new MultiLineReceiver() {
+ @Override
+ public void processNewLines(String[] lines) {
+ defaultPath = "0".equals(lines[0]) ? corePath : TizenPlatformConstants.PRIVATE_PLATFORM_CORE_PATH;
+ }
+ });
+ } catch (IOException e) {
+ Logger.error("Problem occurred while executing command '" + command + "'", e.getMessage(), e);
+ }
+ }
} \ No newline at end of file
diff --git a/org.tizen.common.connection/src/org/tizen/common/connection/ui/TizenRemoteFileLabelProvider.java b/org.tizen.common.connection/src/org/tizen/common/connection/ui/TizenRemoteFileLabelProvider.java
index 25931bdc6..160a67584 100644..100755
--- a/org.tizen.common.connection/src/org/tizen/common/connection/ui/TizenRemoteFileLabelProvider.java
+++ b/org.tizen.common.connection/src/org/tizen/common/connection/ui/TizenRemoteFileLabelProvider.java
@@ -107,9 +107,12 @@ public class TizenRemoteFileLabelProvider implements ITableLabelProvider {
case 4:
return entry.getInfo();
default:
+ break;
}
}
+ break;
default:
+ break;
}
} else if (element instanceof IDevice) {
IDevice device = (IDevice) element;
diff --git a/org.tizen.common.externals/.classpath b/org.tizen.common.externals/.classpath
new file mode 100644
index 000000000..8a8f1668c
--- /dev/null
+++ b/org.tizen.common.externals/.classpath
@@ -0,0 +1,7 @@
+<?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="output" path="bin"/>
+</classpath>
diff --git a/org.tizen.common.externals/.project b/org.tizen.common.externals/.project
new file mode 100644
index 000000000..6ae5db520
--- /dev/null
+++ b/org.tizen.common.externals/.project
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>org.tizen.common.externals</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/org.tizen.common.externals/.settings/org.eclipse.jdt.core.prefs b/org.tizen.common.externals/.settings/org.eclipse.jdt.core.prefs
new file mode 100644
index 000000000..f8bca8622
--- /dev/null
+++ b/org.tizen.common.externals/.settings/org.eclipse.jdt.core.prefs
@@ -0,0 +1,8 @@
+#Tue Jul 31 14:48:57 KST 2012
+eclipse.preferences.version=1
+org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
+org.eclipse.jdt.core.compiler.compliance=1.6
+org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
+org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
+org.eclipse.jdt.core.compiler.source=1.6
diff --git a/org.tizen.common.externals/META-INF/MANIFEST.MF b/org.tizen.common.externals/META-INF/MANIFEST.MF
new file mode 100644
index 000000000..263cd654d
--- /dev/null
+++ b/org.tizen.common.externals/META-INF/MANIFEST.MF
@@ -0,0 +1,42 @@
+Manifest-Version: 1.0
+Bundle-ManifestVersion: 2
+Bundle-Name: %Bundle-Name
+Bundle-SymbolicName: org.tizen.common.externals
+Bundle-Version: 1.0.0.qualifier
+Bundle-Activator: org.tizen.common.externals.ExternalsPlugin
+Bundle-Vendor: %Bundle-Vendor
+Require-Bundle: org.eclipse.ui,
+ org.eclipse.core.runtime
+Bundle-RequiredExecutionEnvironment: JavaSE-1.6
+Bundle-ActivationPolicy: lazy
+Export-Package: org.mihalis.opal,
+ org.mihalis.opal.angles,
+ org.mihalis.opal.brushedMetalComposite,
+ org.mihalis.opal.checkBoxGroup,
+ org.mihalis.opal.columns,
+ org.mihalis.opal.flatButton,
+ org.mihalis.opal.gradientComposite,
+ org.mihalis.opal.header,
+ org.mihalis.opal.heapManager,
+ org.mihalis.opal.horizontalSpinner,
+ org.mihalis.opal.imageSelector,
+ org.mihalis.opal.infinitePanel,
+ org.mihalis.opal.itemSelector,
+ org.mihalis.opal.launcher,
+ org.mihalis.opal.login,
+ org.mihalis.opal.multiChoice,
+ org.mihalis.opal.notify,
+ org.mihalis.opal.opalDialog,
+ org.mihalis.opal.panels,
+ org.mihalis.opal.preferenceWindow,
+ org.mihalis.opal.preferenceWindow.enabler,
+ org.mihalis.opal.preferenceWindow.widgets,
+ org.mihalis.opal.promptSupport,
+ org.mihalis.opal.rangeSlider,
+ org.mihalis.opal.switchButton,
+ org.mihalis.opal.textAssist,
+ org.mihalis.opal.tipOfTheDay,
+ org.mihalis.opal.titledSeparator,
+ org.mihalis.opal.transitionComposite,
+ org.mihalis.opal.utils,
+ org.tizen.common.externals
diff --git a/org.tizen.common.externals/OSGI-INF/l10n/bundle.properties b/org.tizen.common.externals/OSGI-INF/l10n/bundle.properties
new file mode 100644
index 000000000..2debd4130
--- /dev/null
+++ b/org.tizen.common.externals/OSGI-INF/l10n/bundle.properties
@@ -0,0 +1,3 @@
+#Properties file for org.tizen.web.project.wizard
+Bundle-Vendor = Samsung Electronics
+Bundle-Name = Tizen Common externals \ No newline at end of file
diff --git a/org.tizen.common.externals/about.html b/org.tizen.common.externals/about.html
new file mode 100644
index 000000000..a72b377bd
--- /dev/null
+++ b/org.tizen.common.externals/about.html
@@ -0,0 +1,41 @@
+<!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>May, 2011</p>
+<h3>Tizen SDK</h3>
+
+<p><a href="http://www.tizen.org/" target="_blank">Tizen SDK</a>
+is a set of Eclipse plug-ins that helps programmers to develop applications for
+the mobile platform.</p>
+
+<h3>License</h3>
+
+<p>See <a href="about_files/LICENSE-2.0.htm">Apache License, Version 2.0</a>.</p>
+
+<h3>Third Party Content</h3>
+
+<p>The Content includes items that have been sourced from third parties as set out below. If you did not
+receive this Content directly from the Eclipse Foundation, the following is provided for informational
+purposes only, and you should look to the Redistributors license for terms and conditions of use.</p>
+
+<h4>OPAL</h4>
+<p>
+The goal of this project is to propose new widgets for the SWT API. Some widgets are new, some others are a port of existing widgets made with Swing.
+</p>
+
+<p>
+A copy of the license is included in <a href="about_files/epl-v10.html">about_files/epl-v10.html</a>. The home page is located at:
+<ul>
+<a href="http://code.google.com/a/eclipselabs.org/p/opal/">http://code.google.com/a/eclipselabs.org/p/opal/</a>
+</ul>
+</p>
+
+</body>
+</html> \ No newline at end of file
diff --git a/org.tizen.common.externals/about_files/LICENSE-2.0.htm b/org.tizen.common.externals/about_files/LICENSE-2.0.htm
new file mode 100644
index 000000000..f7ca65649
--- /dev/null
+++ b/org.tizen.common.externals/about_files/LICENSE-2.0.htm
@@ -0,0 +1,191 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<html lang="en">
+ <head>
+ <title>Apache License, Version 2.0</title>
+
+ <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
+ <meta property="og:image" content="http://www.apache.org/images/asf_logo.gif" />
+
+ <link rel="stylesheet" type="text/css" media="screen" href="/css/style.css">
+ <link rel="stylesheet" type="text/css" media="screen" href="/css/code.css">
+
+ <script type="text/javascript" src="/js/jquery.js"></script>
+ <script type="text/javascript" src="/js/apache_boot.js"></script>
+
+
+
+
+ <!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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. -->
+ </head>
+
+ <body>
+ <div id="page" class="container_16">
+ <div id="header" class="grid_8">
+ <h1>The Apache Software Foundation</h1>
+ <h2>Apache License, Version 2.0</h2>
+ </div>
+
+ <div class="clear"></div>
+ <div id="content" class="grid_16"><div class="section-content"><p>Apache License<br></br>Version 2.0, January 2004<br></br>
+<a href="http://www.apache.org/licenses/">http://www.apache.org/licenses/</a> </p>
+<p>TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION</p>
+<p><strong><a name="definitions">1. Definitions</a></strong>.</p>
+<p>"License" shall mean the terms and conditions for use, reproduction, and
+distribution as defined by Sections 1 through 9 of this document.</p>
+<p>"Licensor" shall mean the copyright owner or entity authorized by the
+copyright owner that is granting the License.</p>
+<p>"Legal Entity" 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, "control" 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.</p>
+<p>"You" (or "Your") shall mean an individual or Legal Entity exercising
+permissions granted by this License.</p>
+<p>"Source" form shall mean the preferred form for making modifications,
+including but not limited to software source code, documentation source,
+and configuration files.</p>
+<p>"Object" 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.</p>
+<p>"Work" 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).</p>
+<p>"Derivative Works" 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.</p>
+<p>"Contribution" 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, "submitted" 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 "Not a
+Contribution."</p>
+<p>"Contributor" 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.</p>
+<p><strong><a name="copyright">2. Grant of Copyright License</a></strong>. 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.</p>
+<p><strong><a name="patent">3. Grant of Patent License</a></strong>. 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.</p>
+<p><strong><a name="redistribution">4. Redistribution</a></strong>. 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:</p>
+<ol>
+<li>
+<p>You must give any other recipients of the Work or Derivative Works a
+copy of this License; and</p>
+</li>
+<li>
+<p>You must cause any modified files to carry prominent notices stating
+that You changed the files; and</p>
+</li>
+<li>
+<p>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</p>
+</li>
+<li>
+<p>If the Work includes a "NOTICE" 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.</p>
+</li>
+</ol>
+<p><strong><a name="contributions">5. Submission of Contributions</a></strong>. 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.</p>
+<p><strong><a name="trademarks">6. Trademarks</a></strong>. 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.</p>
+<p><strong><a name="no-warranty">7. Disclaimer of Warranty</a></strong>. Unless required by
+applicable law or agreed to in writing, Licensor provides the Work (and
+each Contributor provides its Contributions) 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. 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.</p>
+<p><strong><a name="no-liability">8. Limitation of Liability</a></strong>. 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.</p>
+<p><strong><a name="additional">9. Accepting Warranty or Additional Liability</a></strong>.
+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.</p>
+<p>END OF TERMS AND CONDITIONS</p>
+
+ <div class="clear"></div>
+
+ </div>
+ <div id="copyright" class="container_16">
+ <p>Copyright &#169; 2011 The Apache Software Foundation, Licensed under the <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache License, Version 2.0</a>.<br/>Apache and the Apache feather logo are trademarks of The Apache Software Foundation.</p>
+ </div>
+ </body>
+</html>
diff --git a/org.tizen.common.externals/about_files/epl-v10.html b/org.tizen.common.externals/about_files/epl-v10.html
new file mode 100644
index 000000000..fd391227c
--- /dev/null
+++ b/org.tizen.common.externals/about_files/epl-v10.html
@@ -0,0 +1,261 @@
+<?xml version="1.0" encoding="ISO-8859-1" ?>
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml">
+
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
+<title>Eclipse Public License - Version 1.0</title>
+<style type="text/css">
+ body {
+ size: 8.5in 11.0in;
+ margin: 0.25in 0.5in 0.25in 0.5in;
+ tab-interval: 0.5in;
+ }
+ p {
+ margin-left: auto;
+ margin-top: 0.5em;
+ margin-bottom: 0.5em;
+ }
+ p.list {
+ margin-left: 0.5in;
+ margin-top: 0.05em;
+ margin-bottom: 0.05em;
+ }
+ </style>
+
+</head>
+
+<body lang="EN-US">
+
+<h2>Eclipse Public License - v 1.0</h2>
+
+<p>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'S ACCEPTANCE OF THIS
+AGREEMENT.</p>
+
+<p><b>1. DEFINITIONS</b></p>
+
+<p>&quot;Contribution&quot; means:</p>
+
+<p class="list">a) in the case of the initial Contributor, the initial
+code and documentation distributed under this Agreement, and</p>
+<p class="list">b) in the case of each subsequent Contributor:</p>
+<p class="list">i) changes to the Program, and</p>
+<p class="list">ii) additions to the Program;</p>
+<p class="list">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.</p>
+
+<p>&quot;Contributor&quot; means any person or entity that distributes
+the Program.</p>
+
+<p>&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.</p>
+
+<p>&quot;Program&quot; means the Contributions distributed in accordance
+with this Agreement.</p>
+
+<p>&quot;Recipient&quot; means anyone who receives the Program under
+this Agreement, including all Contributors.</p>
+
+<p><b>2. GRANT OF RIGHTS</b></p>
+
+<p class="list">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.</p>
+
+<p class="list">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.</p>
+
+<p class="list">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.</p>
+
+<p class="list">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.</p>
+
+<p><b>3. REQUIREMENTS</b></p>
+
+<p>A Contributor may choose to distribute the Program in object code
+form under its own license agreement, provided that:</p>
+
+<p class="list">a) it complies with the terms and conditions of this
+Agreement; and</p>
+
+<p class="list">b) its license agreement:</p>
+
+<p class="list">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;</p>
+
+<p class="list">ii) effectively excludes on behalf of all Contributors
+all liability for damages, including direct, indirect, special,
+incidental and consequential damages, such as lost profits;</p>
+
+<p class="list">iii) states that any provisions which differ from this
+Agreement are offered by that Contributor alone and not by any other
+party; and</p>
+
+<p class="list">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.</p>
+
+<p>When the Program is made available in source code form:</p>
+
+<p class="list">a) it must be made available under this Agreement; and</p>
+
+<p class="list">b) a copy of this Agreement must be included with each
+copy of the Program.</p>
+
+<p>Contributors may not remove or alter any copyright notices contained
+within the Program.</p>
+
+<p>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.</p>
+
+<p><b>4. COMMERCIAL DISTRIBUTION</b></p>
+
+<p>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.</p>
+
+<p>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.</p>
+
+<p><b>5. NO WARRANTY</b></p>
+
+<p>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.</p>
+
+<p><b>6. DISCLAIMER OF LIABILITY</b></p>
+
+<p>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.</p>
+
+<p><b>7. GENERAL</b></p>
+
+<p>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.</p>
+
+<p>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.</p>
+
+<p>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.</p>
+
+<p>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.</p>
+
+<p>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.</p>
+
+</body>
+
+</html>
diff --git a/org.tizen.common.externals/build.properties b/org.tizen.common.externals/build.properties
new file mode 100644
index 000000000..1477b3fad
--- /dev/null
+++ b/org.tizen.common.externals/build.properties
@@ -0,0 +1,8 @@
+source.. = src/
+output.. = bin/
+bin.includes = META-INF/,\
+ .,\
+ OSGI-INF/,\
+ resources/,\
+ about.html,\
+ about_files/
diff --git a/org.tizen.common.externals/resources/opal.properties b/org.tizen.common.externals/resources/opal.properties
new file mode 100644
index 000000000..ef0a470de
--- /dev/null
+++ b/org.tizen.common.externals/resources/opal.properties
@@ -0,0 +1,35 @@
+Ok=OK
+Cancel=Cancel
+Close=Close
+Yes=Yes
+No=No
+MoreDetails=More Details
+FewerDetails=Fewer Details
+Details=Details
+Information=Information
+Error=Error
+Question=Question
+Warning=Warning
+Exception=Exception
+Choice=Choice
+Select=Select
+Input=Input
+ApplicationError=Application Error
+megabytes=Mb
+performGC=Perform GC
+login=Login
+name=Name
+password=Password
+rememberPassword=Remember password
+loginFailed=Login failed
+tipOfTheDay=Tip of the day
+didYouKnow=Did you know...
+showTipAtStartup=Show Tip at startup
+previousTip=< Previous Tip
+nextTip=Next Tip >
+choose=Choose
+preferences=Preferences
+validURL=Please enter a valid URL
+chooseDirectory=Please choose a directory
+bold=bold
+italic=italic
diff --git a/org.tizen.common.externals/resources/opal_de_DE.properties b/org.tizen.common.externals/resources/opal_de_DE.properties
new file mode 100644
index 000000000..b6e5e5564
--- /dev/null
+++ b/org.tizen.common.externals/resources/opal_de_DE.properties
@@ -0,0 +1,35 @@
+OK=OK
+Cancel=Abbrechen
+Close=Schließen
+Yes=Ja
+No=Nein
+MoreDetails=Weitere Details
+FewerDetails=Weniger Details
+Details=Details
+Information=Information
+Error=Fehler
+Question=Frage
+Warning=Warnung
+Exception=Ausnahme
+Choice=Auswahl
+Select=Auswählen
+Input=Eingabe
+ApplicationError=Application Error
+megabytes=Mb
+performGC=Perform GC
+login=Login
+name=Name
+password=Passwort
+rememberPassword=Passwort merken
+loginFailed=Login failed
+tipOfTheDay=Tip of the day
+didYouKnow=Did you know...
+showTipAtStartup=Show Tip at startup
+previousTip=< Previous Tip
+nextTip=Next Tip >
+choose=Choose
+preferences=Preferences
+validURL=Please enter a valid URL
+chooseDirectory=Please choose a directory
+bold=bold
+italic=italic \ No newline at end of file
diff --git a/org.tizen.common.externals/resources/opal_es_ES.properties b/org.tizen.common.externals/resources/opal_es_ES.properties
new file mode 100644
index 000000000..afb379842
--- /dev/null
+++ b/org.tizen.common.externals/resources/opal_es_ES.properties
@@ -0,0 +1,35 @@
+Ok=OK
+Cancel=Cancelar
+Close=Cerrar
+Yes=Sí
+No=No
+MoreDetails=Más detalles
+FewerDetails=Pocos detalles
+Details=Detalles
+Information=Información
+Error=Error
+Question=Pregunta
+Warning=Advertencia
+Exception=Excepción
+Choice=Elección
+Select=Seleccione
+Input=Entrada
+ApplicationError=Error de la aplicación
+megabytes=Mb
+performGC=Ejecutar GC
+login=Conexión
+name=Nombre
+password=Contraseña
+rememberPassword=Recordar contraseña
+loginFailed=Fallo en la conexión
+tipOfTheDay=Consejo diario
+didYouKnow=Sabias que...?
+showTipAtStartup=Mostrar consejos al inicio
+previousTip=<Consejo anterior
+nextTip=Siguiente consejo>
+choose=Elegir
+preferences=Preferencias
+validURL=Por favor, introduzca una URL válida
+chooseDirectory=Por favor, escoge un directorio
+bold=negrita
+italic=cursiva \ No newline at end of file
diff --git a/org.tizen.common.externals/resources/opal_fr_FR.properties b/org.tizen.common.externals/resources/opal_fr_FR.properties
new file mode 100644
index 000000000..a7ef8416c
--- /dev/null
+++ b/org.tizen.common.externals/resources/opal_fr_FR.properties
@@ -0,0 +1,35 @@
+OK=OK
+Cancel=Annuler
+Close=Fermer
+Yes=Oui
+No=Non
+MoreDetails=Plus de détails
+FewerDetails=Moins de détails
+Details=Détails
+Information=Information
+Error=Erreur
+Question=Question
+Warning=Avertissement
+Exception=Exception
+Choice=Choix
+Select=Sélection
+Input=Entrée
+ApplicationError=Erreur applicative
+megabytes=Mo
+performGC=Lancer le ramasse-miettes (GC)
+login=Identification
+name=Nom
+password=Mot de passe
+rememberPassword=Se souvenir de mon mot de passe
+loginFailed=Echec de l'authentification
+tipOfTheDay=Astuce du jour
+didYouKnow=Le savez-vous ?
+showTipAtStartup=Afficher les astuces au démarrage
+previousTip=< Astuce précédente
+nextTip=Astuce suivante >
+choose=Choisir
+preferences=Préférences
+validURL=Merci de saisir une URL valide s'il vous plait
+chooseDirectory=Veuillez choisir un répertoire
+bold=gras
+italic=italique \ No newline at end of file
diff --git a/org.tizen.common.externals/resources/opal_it_IT.properties b/org.tizen.common.externals/resources/opal_it_IT.properties
new file mode 100644
index 000000000..189900ba4
--- /dev/null
+++ b/org.tizen.common.externals/resources/opal_it_IT.properties
@@ -0,0 +1,35 @@
+OK=OK
+Cancel=Annulla
+Close=Chiudi
+Yes=Si
+No=No
+MoreDetails=Pi\u00F9 Dettagli
+FewerDetails=Meno Dettagli
+Details=Dettagli
+Information=Informazione
+Error=Errore
+Question=Domanda
+Warning=Avvertenza
+Exception=Eccezione
+Choice=Scelta
+Select=Seleziona
+Input=Input
+ApplicationError=Errore di applicazione
+megabytes=Mb
+performGC=Perform GC
+login=Accesso
+name=Nome
+password=Password
+rememberPassword=Remember password
+loginFailed=Login failed
+tipOfTheDay=Tip of the day
+didYouKnow=Did you know...
+showTipAtStartup=Show Tip at startup
+previousTip=< Previous Tip
+nextTip=Next Tip >
+choose=Choose
+preferences=Preferences
+validURL=Please enter a valid URL
+chooseDirectory=Please choose a directory
+bold=bold
+italic=italic \ No newline at end of file
diff --git a/org.tizen.common.externals/resources/opal_pl_PL.properties b/org.tizen.common.externals/resources/opal_pl_PL.properties
new file mode 100644
index 000000000..2d8e8ddeb
--- /dev/null
+++ b/org.tizen.common.externals/resources/opal_pl_PL.properties
@@ -0,0 +1,35 @@
+Ok=OK
+Cancel=Anuluj
+Close=Zamknij
+Yes=Tak
+No=Nie
+MoreDetails=Więcej szczegółów
+FewerDetails=Mniej szczegółów
+Details=Szczegóły
+Information=Informacja
+Error=BÅ‚Ä…d
+Question=Pytanie
+Warning=Ostrzeżenie
+Exception=WyjÄ…tek
+Choice=Wybór
+Select=Wybór
+Input=Wprowadzanie
+ApplicationError=BÅ‚Ä…d aplikacji
+megabytes=Mb
+performGC=Perform GC
+login=Login
+name=Name
+password=Password
+rememberPassword=Remember password
+loginFailed=Login failed
+tipOfTheDay=Tip of the day
+didYouKnow=Did you know...
+showTipAtStartup=Show Tip at startup
+previousTip=< Previous Tip
+nextTip=Next Tip >
+choose=Choose
+preferences=Preferences
+validURL=Please enter a valid URL
+chooseDirectory=Please choose a directory
+bold=bold
+italic=italic \ No newline at end of file
diff --git a/org.tizen.common.externals/resources/opal_pt_BR.properties b/org.tizen.common.externals/resources/opal_pt_BR.properties
new file mode 100644
index 000000000..502910226
--- /dev/null
+++ b/org.tizen.common.externals/resources/opal_pt_BR.properties
@@ -0,0 +1,35 @@
+Ok=OK
+Cancel=Cancelar
+Close=Fechar
+Yes=Sim
+No=Não
+MoreDetails=Mais detalhes
+FewerDetails=Menos detalhes
+Details=Detalhes
+Information=Informação
+Error=Erro
+Question=Questão
+Warning=Aviso
+Exception=Exceção
+Choice=Escolher
+Select=Selecionar
+Input=Entrar
+ApplicationError=Erro da aplicação
+megabytes=Mb
+performGC=Perform GC
+login=Login
+name=Name
+password=Password
+rememberPassword=Remember password
+loginFailed=Login failed
+tipOfTheDay=Tip of the day
+didYouKnow=Did you know...
+showTipAtStartup=Show Tip at startup
+previousTip=< Previous Tip
+nextTip=Next Tip >
+choose=Choose
+preferences=Preferences
+validURL=Please enter a valid URL
+chooseDirectory=Please choose a directory
+bold=bold
+italic=italic \ No newline at end of file
diff --git a/org.tizen.common.externals/resources/opal_zh_CN.properties b/org.tizen.common.externals/resources/opal_zh_CN.properties
new file mode 100644
index 000000000..b479add55
--- /dev/null
+++ b/org.tizen.common.externals/resources/opal_zh_CN.properties
@@ -0,0 +1,35 @@
+Ok=\u786e\u5b9a
+Cancel=\u653e\u5f03
+Close=\u5173\u95ed
+Yes=\u662f
+No=\u5426
+MoreDetails=\u8be6\u7ec6\u4fe1\u606f
+FewerDetails=\u7b80\u660e\u4fe1\u606f
+Details=\u4fe1\u606f
+Information=\u4fe1\u606f
+Error=\u9519\u8bef
+Question=\u95ee\u9898
+Warning=\u8b66\u544a
+Exception=\u5f02\u5e38
+Choice=\u9009\u9879
+Select=\u9009\u62e9
+Input=\u8f93\u5165
+ApplicationError=Application Error
+megabytes=Mb
+performGC=Perform GC
+login=Login
+name=Name
+password=Password
+rememberPassword=Remember password
+loginFailed=Login failed
+tipOfTheDay=Tip of the day
+didYouKnow=Did you know...
+showTipAtStartup=Show Tip at startup
+previousTip=< Previous Tip
+nextTip=Next Tip >
+choose=Choose
+preferences=Preferences
+validURL=Please enter a valid URL
+chooseDirectory=Please choose a directory
+bold=bold
+italic=italic \ No newline at end of file
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/OpalItem.java b/org.tizen.common.externals/src/org/mihalis/opal/OpalItem.java
new file mode 100644
index 000000000..a06f1de32
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/OpalItem.java
@@ -0,0 +1,158 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON
+ * 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:
+ * Laurent CARON (laurent.caron at gmail dot com) - initial API and implementation
+ *******************************************************************************/
+package org.mihalis.opal;
+
+import java.util.Map;
+
+import org.eclipse.swt.graphics.Color;
+import org.eclipse.swt.graphics.Font;
+import org.eclipse.swt.graphics.Image;
+
+/**
+ * Instances of this object are items manipulated by the widgets of the Opal Project. These items are highly customizable, you can set :
+ * <ul>
+ * <li>Background and foreground colors,
+ * <li>Font
+ * <li>Image
+ * <li>Text
+ * <li>Height
+ * </ul>
+ * You can also store data using the <code>setData<code> methods.
+ *
+ */
+public abstract class OpalItem {
+
+ private Map<String, Object> data;
+ private Object datum;
+ private Color background;
+ private Font font;
+ private Color foreground;
+ private Image image;
+ private String text;
+ private int height = -1;
+
+ /**
+ * @return the background color of the item
+ */
+ public Color getBackground() {
+ return this.background;
+ }
+
+ /**
+ * @return the the data stored in this item
+ */
+ public Object getData() {
+ return this.datum;
+ }
+
+ /**
+ * @param key a key
+ * @return the the data stored in this item associated to this key
+ */
+ public Object getData(final String key) {
+ return this.data.get(key);
+ }
+
+ /**
+ * @return the font of the item
+ */
+ public Font getFont() {
+ return this.font;
+ }
+
+ /**
+ * @return the foreground color of the item
+ */
+ public Color getForeground() {
+ return this.foreground;
+ }
+
+ /**
+ * @return the height of the item
+ */
+ public int getHeight() {
+ return this.height;
+ }
+
+ /**
+ * @return the image stored in this item
+ */
+ public Image getImage() {
+ return this.image;
+ }
+
+ /**
+ * @return the text stored in this item
+ */
+ public String getText() {
+ return this.text;
+ }
+
+ /**
+ * @param background set the background color of this item
+ */
+ public void setBackground(final Color background) {
+ this.background = background;
+ }
+
+ /**
+ * @param font set the font of this item
+ */
+ public void setFont(final Font font) {
+ this.font = font;
+ }
+
+ /**
+ * @param foreground set the foreground color of this item
+ */
+ public void setForeground(final Color foreground) {
+ this.foreground = foreground;
+ }
+
+ /**
+ * @param height set the height of this item
+ */
+ public void setHeight(final int height) {
+ this.height = height;
+ }
+
+ /**
+ * @param image set the image of this item
+ */
+ public void setImage(final Image image) {
+ this.image = image;
+ }
+
+ /**
+ * @param text set the text of this item
+ */
+ public void setText(final String text) {
+ this.text = text;
+ }
+
+ /**
+ * @param data set the data stored in this item
+ */
+ public void setData(final Object data) {
+ this.datum = data;
+ }
+
+ /**
+ * Store a data associated to a given key in this item
+ *
+ * @param key key
+ * @param value value associated to this key
+ */
+ public void setData(final String key, final Object value) {
+ this.data.put(key, value);
+ }
+
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/angles/AngleSlider.java b/org.tizen.common.externals/src/org/mihalis/opal/angles/AngleSlider.java
new file mode 100644
index 000000000..bf36ba771
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/angles/AngleSlider.java
@@ -0,0 +1,246 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON.
+ * 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:
+ * Laurent CARON (laurent.caron@gmail.com) - initial API and implementation
+ * inspired by the Swing AngleSlider by Jeremy (http://javagraphics.blogspot.com/2008/05/angles-need-gui-widget-for-angles.html)
+ *******************************************************************************/
+package org.mihalis.opal.angles;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.SWTException;
+import org.eclipse.swt.events.DisposeEvent;
+import org.eclipse.swt.events.DisposeListener;
+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.Point;
+import org.eclipse.swt.widgets.Canvas;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Event;
+import org.eclipse.swt.widgets.Listener;
+import org.mihalis.opal.utils.SWTGraphicUtil;
+
+/**
+ * Instances of this class provide a selectable user interface object that can
+ * be used to pick angles.
+ * <p>
+ * <dl>
+ * <dt><b>Styles:</b></dt>
+ * <dd>BORDER</dd>
+ * <dt><b>Events:</b></dt>
+ * <dd>Selection</dd>
+ * </dl>
+ */
+public class AngleSlider extends Canvas {
+
+ private static final int WHOLE_RADIUS = 40;
+ private static final int BUTTON_RADIUS = 10;
+ private static final int STEP = 5;
+
+ private final Image backgroundImage;
+ private final Image buttonFocus;
+ private final Image buttonNoFocus;
+ private int selection;
+ private final List<SelectionListener> selectionListeners;
+ private boolean mousePressed;
+
+ /**
+ * Constructs a new instance of this class given its parent.
+ *
+ * @param parent a widget which will be the parent of the new instance
+ * (cannot be null)
+ * @param style not used
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the parent is null</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the parent</li>
+ * </ul>
+ */
+ public AngleSlider(final Composite parent, final int style) {
+ super(parent, style | SWT.DOUBLE_BUFFERED);
+
+ this.backgroundImage = new Image(getDisplay(), this.getClass().getClassLoader().getResourceAsStream("images/angleBackground.png"));
+
+ this.buttonFocus = new Image(getDisplay(), this.getClass().getClassLoader().getResourceAsStream("images/angleButtonFocus.png"));
+ this.buttonNoFocus = new Image(getDisplay(), this.getClass().getClassLoader().getResourceAsStream("images/angleButtonFocusLost.png"));
+
+ this.addListener(SWT.Paint, new Listener() {
+
+ @Override
+ public void handleEvent(final Event event) {
+ paintControl(event);
+ }
+ });
+
+ this.addDisposeListener(new DisposeListener() {
+
+ @Override
+ public void widgetDisposed(final DisposeEvent arg0) {
+ SWTGraphicUtil.dispose(AngleSlider.this.backgroundImage);
+ SWTGraphicUtil.dispose(AngleSlider.this.buttonFocus);
+ SWTGraphicUtil.dispose(AngleSlider.this.buttonNoFocus);
+ }
+ });
+
+ this.addListener(SWT.MouseDown, createMouseListener());
+ this.addListener(SWT.MouseUp, createMouseListener());
+ this.addListener(SWT.MouseMove, createMouseListener());
+ this.addListener(SWT.KeyDown, createKeyListener());
+
+ this.selection = 0;
+ this.selectionListeners = new ArrayList<SelectionListener>();
+
+ }
+
+ private void paintControl(final Event event) {
+ final GC gc = event.gc;
+
+ gc.drawImage(this.backgroundImage, 0, 0);
+
+ float angle = this.selection / 360f;
+ angle = (float) (angle * 2 * Math.PI - 0.5 * Math.PI);
+
+ final float centerX = WHOLE_RADIUS / 2f;
+ final float centerY = WHOLE_RADIUS / 2f;
+ final float radius = BUTTON_RADIUS;
+ final float x = (float) (centerX - radius * Math.cos(angle));
+ final float y = (float) (centerY - radius * Math.sin(angle));
+
+ if (isFocusControl()) {
+ gc.drawImage(this.buttonFocus, (int) x - 2, (int) y - 2);
+ } else {
+ gc.drawImage(this.buttonNoFocus, (int) x - 2, (int) y - 2);
+ }
+
+ if (!isEnabled()) {
+ gc.setAlpha(127);
+ gc.setAntialias(SWT.ON);
+ gc.setBackground(getDisplay().getSystemColor(SWT.COLOR_WHITE));
+ gc.fillOval(4, 4, WHOLE_RADIUS - 7, WHOLE_RADIUS - 7);
+ }
+ }
+
+ private Listener createMouseListener() {
+ return new Listener() {
+
+ @Override
+ public void handleEvent(final Event event) {
+ if (!isEnabled()) {
+ return;
+ }
+
+ if (event.type == SWT.MouseDown) {
+ AngleSlider.this.mousePressed = true;
+ }
+ if (event.type == SWT.MouseDown || event.type == SWT.MouseMove && AngleSlider.this.mousePressed) {
+ final float deltaX = event.x - WHOLE_RADIUS / 2f;
+ final float deltaY = event.y - WHOLE_RADIUS / 2f;
+ final double angle = Math.atan2(deltaX, deltaY);
+ AngleSlider.this.selection = 360 - (int) (360 * angle / (2 * Math.PI) + 360) % 360;
+
+ AngleSlider.this.redraw();
+ }
+ if (event.type == SWT.MouseUp) {
+ AngleSlider.this.mousePressed = false;
+ fireSelectionListeners(event);
+ }
+ }
+ };
+ }
+
+ private void fireSelectionListeners(final Event event) {
+ for (final SelectionListener selectionListener : this.selectionListeners) {
+ selectionListener.widgetSelected(new SelectionEvent(event));
+ }
+
+ }
+
+ private Listener createKeyListener() {
+ return new Listener() {
+
+ @Override
+ public void handleEvent(final Event event) {
+ if (!isEnabled()) {
+ return;
+ }
+ if (event.type != SWT.KeyDown) {
+ return;
+ }
+ if (event.keyCode == SWT.ARROW_UP || event.keyCode == SWT.ARROW_LEFT) {
+ setSelection(AngleSlider.this.selection + STEP);
+ }
+ if (event.keyCode == SWT.ARROW_DOWN || event.keyCode == SWT.ARROW_RIGHT) {
+ setSelection(AngleSlider.this.selection - STEP);
+ }
+ }
+ };
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Scale#addSelectionListener(org.eclipse.swt.events.SelectionListener)
+ */
+ public void addSelectionListener(final SelectionListener selectionListener) {
+ checkWidget();
+ this.selectionListeners.add(selectionListener);
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Composite#computeSize(int, int, boolean)
+ */
+ @Override
+ public Point computeSize(final int wHint, final int hHint, final boolean changed) {
+ checkWidget();
+ return new Point(WHOLE_RADIUS, WHOLE_RADIUS);
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Scale#getSelection()
+ */
+ public int getSelection() {
+ checkWidget();
+ return this.selection;
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Scale#removeSelectionListener(org.eclipse.swt.events.SelectionListener)
+ */
+ public void removeSelectionListener(final SelectionListener selectionListener) {
+ checkWidget();
+ this.selectionListeners.remove(selectionListener);
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Control#setEnabled(boolean)
+ */
+ @Override
+ public void setEnabled(final boolean enabled) {
+ super.setEnabled(enabled);
+ redraw();
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Scale#setSelection(int)
+ */
+ public void setSelection(final int selection) {
+ checkWidget();
+ if (selection < 0 || selection > 360) {
+ SWT.error(SWT.ERROR_CANNOT_SET_SELECTION);
+ }
+ this.selection = selection;
+ fireSelectionListeners(new Event());
+ redraw();
+ }
+
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/brushedMetalComposite/BrushedMetalComposite.java b/org.tizen.common.externals/src/org/mihalis/opal/brushedMetalComposite/BrushedMetalComposite.java
new file mode 100644
index 000000000..893b8c6ff
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/brushedMetalComposite/BrushedMetalComposite.java
@@ -0,0 +1,378 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON
+ * 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:
+ * Jerry Huxtable (http://www.jhlabs.com/index.html) - initial API and implementation (on SWING),
+ * Laurent CARON (laurent.caron at gmail dot com) - port to SWT
+ *******************************************************************************/
+package org.mihalis.opal.brushedMetalComposite;
+
+import java.util.Random;
+
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.SWTException;
+import org.eclipse.swt.events.DisposeEvent;
+import org.eclipse.swt.events.DisposeListener;
+import org.eclipse.swt.graphics.Color;
+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.Composite;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.Event;
+import org.eclipse.swt.widgets.Listener;
+import org.eclipse.swt.widgets.Widget;
+import org.mihalis.opal.utils.SWTGraphicUtil;
+
+/**
+ * Instances of this class are controls which background's texture is brushed
+ * metal "a la Mac"
+ */
+public class BrushedMetalComposite extends Composite {
+
+ private Image oldImage;
+ private int radius = 10;
+ private float amount = 0.1f;
+ private int color = 0xff888888;
+ private float shine = 0.1f;
+ private boolean monochrome = true;
+ private Random randomNumbers;
+
+ /**
+ * Constructs a new instance of this class given its parent and a style
+ * value describing its behavior and appearance.
+ * <p>
+ * The style value is either one of the style constants defined in class
+ * <code>SWT</code> which is applicable to instances of this class, or must
+ * be built by <em>bitwise OR</em>'ing together (that is, using the
+ * <code>int</code> "|" operator) two or more of those <code>SWT</code>
+ * style constants. The class description lists the style constants that are
+ * applicable to the class. Style bits are also inherited from superclasses.
+ * </p>
+ *
+ * @param parent a widget which will be the parent of the new instance
+ * (cannot be null)
+ * @param style the style of widget to construct
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the parent is null</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the parent</li>
+ * </ul>
+ *
+ * @see Composite#Composite(Composite, int)
+ * @see SWT#NO_BACKGROUND
+ * @see SWT#NO_FOCUS
+ * @see SWT#NO_MERGE_PAINTS
+ * @see SWT#NO_REDRAW_RESIZE
+ * @see SWT#NO_RADIO_GROUP
+ * @see SWT#EMBEDDED
+ * @see SWT#DOUBLE_BUFFERED
+ * @see Widget#getStyle
+ */
+ public BrushedMetalComposite(final Composite parent, final int style) {
+ super(parent, style);
+ this.addListener(SWT.Resize, new Listener() {
+ @Override
+ public void handleEvent(final Event event) {
+ BrushedMetalComposite.this.redrawComposite();
+ }
+ });
+
+ parent.addDisposeListener(new DisposeListener() {
+
+ @Override
+ public void widgetDisposed(final DisposeEvent e) {
+ SWTGraphicUtil.dispose(BrushedMetalComposite.this.oldImage);
+ }
+ });
+ }
+
+ /**
+ * Redraws the composite
+ */
+ private void redrawComposite() {
+ final Display display = this.getDisplay();
+ final Rectangle rect = this.getClientArea();
+ final ImageData imageData = this.drawBrushedMetalBackground(Math.max(1, rect.width), Math.max(1, rect.width));
+ final Image newImage = new Image(display, imageData);
+
+ this.setBackgroundImage(newImage);
+ SWTGraphicUtil.dispose(this.oldImage);
+ this.oldImage = newImage;
+ }
+
+ /**
+ * Create a brushed metal background
+ *
+ * @param width width of the panel
+ * @param height height of the panel
+ * @return an image data that contains the background
+ */
+ private ImageData drawBrushedMetalBackground(final int width, final int height) {
+
+ final int[] inPixels = new int[width];
+ final PaletteData palette = new PaletteData(0xFF0000, 0x00FF00, 0x0000FF);
+ final ImageData data = new ImageData(width, height, 0x20, palette);
+
+ this.randomNumbers = new Random(0);
+ final int a = this.color & 0xff000000;
+ final int r = this.color >> 16 & 0xff;
+ final int g = this.color >> 8 & 0xff;
+ final int b = this.color & 0xff;
+ for (int y = 0; y < height; y++) {
+ for (int x = 0; x < width; x++) {
+ int tr = r;
+ int tg = g;
+ int tb = b;
+ if (this.shine != 0) {
+ final int f = (int) (255 * this.shine * Math.sin((double) x / width * Math.PI));
+ tr += f;
+ tg += f;
+ tb += f;
+ }
+ if (this.monochrome) {
+ final int n = (int) (255 * (2 * this.randomNumbers.nextFloat() - 1) * this.amount);
+ inPixels[x] = a | this.clamp(tr + n) << 16 | this.clamp(tg + n) << 8 | this.clamp(tb + n);
+ } else {
+ inPixels[x] = a | this.random(tr) << 16 | this.random(tg) << 8 | this.random(tb);
+ }
+ }
+
+ if (this.radius != 0) {
+ this.setDataElements(data, palette, 0, y, width, 1, this.blur(inPixels, width, this.radius));
+ } else {
+ this.setDataElements(data, palette, 0, y, width, 1, inPixels);
+ }
+ }
+
+ return data;
+ }
+
+ /**
+ * Sets the data for a rectangle of pixels from a primitive array
+ *
+ * @param data the source ImageData
+ * @param palette the palette associated to the imageData
+ * @param posX The X coordinate of the upper left pixel location.
+ * @param posY The Y coordinate of the upper left pixel location.
+ * @param width Width of the pixel rectangle.
+ * @param height Height of the pixel rectangle
+ * @param pixels An array containing the pixel data to place between x,y and
+ * x+w-1, y+h-1.
+ */
+ private void setDataElements(final ImageData data, final PaletteData palette, final int posX, final int posY, final int width, final int height, final int[] pixels) {
+ int cpt = 0;
+ for (int y = posY; y < posY + height; y++) {
+ for (int x = posX; x < posX + width; x++) {
+ final int rgb = pixels[cpt++];
+ final int pixel = palette.getPixel(new RGB(rgb >> 16 & 0xFF, rgb >> 8 & 0xFF, rgb & 0xFF));
+ data.setPixel(x, y, pixel);
+ data.setAlpha(x, y, rgb >> 24 & 0xFF);
+ }
+ }
+ }
+
+ /**
+ * Add a random number to the value. The result is between 0 and 255
+ *
+ * @param x the initial value
+ * @return
+ */
+ private int random(int x) {
+ x += (int) (255 * (2 * this.randomNumbers.nextFloat() - 1) * this.amount);
+ if (x < 0) {
+ x = 0;
+ } else if (x > 0xff) {
+ x = 0xff;
+ }
+ return x;
+ }
+
+ /**
+ * Clamp a number between 0 and 255
+ *
+ * @param c the number to clamp
+ * @return the number. If c is negative, returns 0. If c is greater than
+ * 255, returns 255.
+ */
+ private int clamp(final int c) {
+ if (c < 0) {
+ return 0;
+ }
+
+ if (c > 255) {
+ return 255;
+ }
+
+ return c;
+ }
+
+ /**
+ * Apply a blur filter to an array of int that represents and image which
+ * size is width columns * 1 row
+ *
+ * @param in the array of int that represents the image
+ * @param width the width of the image
+ * @param radius the "radius" blur parameter
+ */
+ private int[] blur(final int[] in, final int width, final int radius) {
+ final int[] out = new int[width];
+ final int widthMinus1 = width - 1;
+ final int r2 = 2 * radius + 1;
+ int tr = 0, tg = 0, tb = 0;
+
+ for (int i = -radius; i <= radius; i++) {
+ final int rgb = in[this.mod(i, width)];
+ tr += rgb >> 16 & 0xff;
+ tg += rgb >> 8 & 0xff;
+ tb += rgb & 0xff;
+ }
+
+ for (int x = 0; x < width; x++) {
+ out[x] = 0xff000000 | tr / r2 << 16 | tg / r2 << 8 | tb / r2;
+
+ int i1 = x + radius + 1;
+ if (i1 > widthMinus1) {
+ i1 = this.mod(i1, width);
+ }
+ int i2 = x - radius;
+ if (i2 < 0) {
+ i2 = this.mod(i2, width);
+ }
+ final int rgb1 = in[i1];
+ final int rgb2 = in[i2];
+
+ tr += (rgb1 & 0xff0000) - (rgb2 & 0xff0000) >> 16;
+ tg += (rgb1 & 0xff00) - (rgb2 & 0xff00) >> 8;
+ tb += (rgb1 & 0xff) - (rgb2 & 0xff);
+ }
+ return out;
+ }
+
+ /**
+ * Return a mod b. This differs from the % operator with respect to negative
+ * numbers.
+ *
+ * @param a the dividend
+ * @param b the divisor
+ * @return a mod b
+ */
+ private int mod(int a, final int b) {
+ final int n = a / b;
+
+ a -= n * b;
+ if (a < 0) {
+ return a + b;
+ }
+ return a;
+ }
+
+ // ------------------------------------ Getters and Setters
+
+ /**
+ * @return the "radius" of the blur
+ */
+ public int getRadius() {
+ return this.radius;
+ }
+
+ /**
+ * @param radius the "radius" of the blur
+ */
+ public void setRadius(final int radius) {
+ this.radius = radius;
+ this.redrawComposite();
+ }
+
+ /**
+ * @return the amount of noise to add
+ */
+ public float getAmount() {
+ return this.amount;
+ }
+
+ /**
+ * @param amount the amount of noise to add
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_INVALID_ARGUMENT - if the value is not between 0
+ * and 1 inclusive</li>
+ * </ul>
+ */
+ public void setAmount(final float amount) {
+ if (amount < 0f || amount > 1f) {
+ SWT.error(SWT.ERROR_INVALID_ARGUMENT);
+ }
+ this.amount = amount;
+ this.redrawComposite();
+ }
+
+ /**
+ * @return the color of the metal. Please notice that this color is a new
+ * SWT object, so it has to be disposed !
+ */
+ public Color getColor() {
+ return new Color(this.getDisplay(), this.color >> 16 & 0xFF, this.color >> 8 & 0xFF, this.color & 0xFF);
+ }
+
+ /**
+ * @param color the color to set
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the value is null</li>
+ * </ul>
+ */
+ public void setColor(final Color color) {
+ if (color == null) {
+ SWT.error(SWT.ERROR_NULL_ARGUMENT);
+ }
+ this.color = 0xFF << 24 | color.getRed() << 16 | color.getGreen() << 8 | color.getBlue();
+ this.redrawComposite();
+ }
+
+ /**
+ * @return the shine to add
+ */
+ public float getShine() {
+ return this.shine;
+ }
+
+ /**
+ * @param shine the shine to set
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_INVALID_ARGUMENT - if the value is not between 0
+ * and 1 inclusive</li>
+ * </ul>
+ */
+ public void setShine(final float shine) {
+ if (this.amount < 0f || this.amount > 1f) {
+ SWT.error(SWT.ERROR_INVALID_ARGUMENT);
+ }
+ this.shine = shine;
+ this.redrawComposite();
+ }
+
+ /**
+ * @return the monochrome
+ */
+ public boolean isMonochrome() {
+ return this.monochrome;
+ }
+
+ /**
+ * @param monochrome the monochrome to set
+ */
+ public void setMonochrome(final boolean monochrome) {
+ this.monochrome = monochrome;
+ this.redrawComposite();
+ }
+
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/checkBoxGroup/CheckBoxGroup.java b/org.tizen.common.externals/src/org/mihalis/opal/checkBoxGroup/CheckBoxGroup.java
new file mode 100644
index 000000000..d8ec1e34a
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/checkBoxGroup/CheckBoxGroup.java
@@ -0,0 +1,323 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON
+ * 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:
+ * Laurent CARON (laurent.caron at gmail dot com) - Initial implementation and API
+ *******************************************************************************/
+package org.mihalis.opal.checkBoxGroup;
+
+import java.util.ArrayList;
+import java.util.List;
+
+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.events.SelectionListener;
+import org.eclipse.swt.graphics.Font;
+import org.eclipse.swt.graphics.GC;
+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.Display;
+import org.eclipse.swt.widgets.Event;
+import org.eclipse.swt.widgets.Layout;
+import org.eclipse.swt.widgets.Listener;
+import org.eclipse.swt.widgets.Widget;
+import org.mihalis.opal.utils.SWTGraphicUtil;
+
+/**
+ * Instances of this class provide an etched border with a title and a checkbox.
+ * If the checkbox is checked, the content of the composite is enabled. If the
+ * checkbox is unchecked, the content of the composite is disabled, thus not
+ * editable.
+ * <p>
+ * <dl>
+ * <dt><b>Styles:</b></dt>
+ * <dd>BORDER</dd>
+ * <dt><b>Events:</b></dt>
+ * <dd>(none)</dd>
+ * </dl>
+ */
+public class CheckBoxGroup extends Composite {
+ private Image oldImage;
+ protected final Button button;
+ private final Composite content;
+ private final List<SelectionListener> selectionListeners;
+
+ /**
+ * Constructs a new instance of this class given its parent and a style
+ * value describing its behavior and appearance.
+ * <p>
+ * The style value is either one of the style constants defined in class
+ * <code>SWT</code> which is applicable to instances of this class, or must
+ * be built by <em>bitwise OR</em>'ing together (that is, using the
+ * <code>int</code> "|" operator) two or more of those <code>SWT</code>
+ * style constants. The class description lists the style constants that are
+ * applicable to the class. Style bits are also inherited from superclasses.
+ * </p>
+ *
+ * @param parent a widget which will be the parent of the new instance
+ * (cannot be null)
+ * @param style the style of widget to construct
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the parent is null</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the parent</li>
+ * </ul>
+ *
+ * @see Composite#Composite(Composite, int)
+ * @see SWT#BORDER
+ * @see Widget#getStyle
+ */
+ public CheckBoxGroup(final Composite parent, final int style) {
+ super(parent, style);
+ super.setLayout(new GridLayout());
+ this.selectionListeners = new ArrayList<SelectionListener>();
+
+ this.button = new Button(this, SWT.CHECK);
+ final GridData gdButton = new GridData(GridData.BEGINNING, GridData.CENTER, true, false);
+ gdButton.horizontalIndent = 15;
+ this.button.setLayoutData(gdButton);
+ this.button.setSelection(true);
+ this.button.setBackground(this.getBackground());
+ this.button.pack();
+
+ this.button.addSelectionListener(new SelectionAdapter() {
+
+ /**
+ * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
+ */
+ @Override
+ public void widgetSelected(final SelectionEvent e) {
+ e.doit = fireSelectionListeners(e);
+ if (!e.doit) {
+ return;
+ }
+ if (CheckBoxGroup.this.button.getSelection()) {
+ CheckBoxGroup.this.activate();
+ } else {
+ CheckBoxGroup.this.deactivate();
+ }
+ }
+ });
+
+ this.content = new Composite(this, SWT.NONE);
+ this.content.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, true));
+
+ this.addListener(SWT.Resize, new Listener() {
+ @Override
+ public void handleEvent(final Event event) {
+ CheckBoxGroup.this.drawWidget();
+ }
+ });
+
+ }
+
+ /**
+ * Fire the selection listeners
+ *
+ * @param selectionEvent mouse event
+ * @return true if the selection could be changed, false otherwise
+ */
+ private boolean fireSelectionListeners(final SelectionEvent selectionEvent) {
+ selectionEvent.widget = this;
+ for (final SelectionListener listener : this.selectionListeners) {
+ listener.widgetSelected(selectionEvent);
+ if (!selectionEvent.doit) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Draws the widget
+ */
+ private void drawWidget() {
+ final Display display = this.getDisplay();
+ final Rectangle rect = this.getClientArea();
+ final Image newImage = new Image(display, Math.max(1, rect.width), Math.max(1, rect.height));
+
+ final GC gc = new GC(newImage);
+ gc.setBackground(this.getBackground());
+
+ gc.fillRectangle(0, 0, rect.width, rect.height);
+
+ final int margin = (int) (this.button.getSize().y * 1.5);
+ final int startY = margin / 2;
+
+ gc.setForeground(this.getDisplay().getSystemColor(SWT.COLOR_WIDGET_NORMAL_SHADOW));
+ gc.drawRoundRectangle(1, startY, rect.width - 2, rect.height - startY - 2, 2, 2);
+
+ gc.setForeground(this.getDisplay().getSystemColor(SWT.COLOR_WIDGET_LIGHT_SHADOW));
+ gc.drawRoundRectangle(2, startY + 1, rect.width - 4, rect.height - startY - 4, 2, 2);
+
+ gc.dispose();
+
+ this.setBackgroundImage(newImage);
+ if (this.oldImage != null) {
+ this.oldImage.dispose();
+ }
+ this.oldImage = newImage;
+
+ }
+
+ /**
+ * Activate the content
+ */
+ public void activate() {
+ this.button.setSelection(true);
+ SWTGraphicUtil.enable(this.content, true);
+ }
+
+ /**
+ * Adds the listener to the collection of listeners who will be notified
+ * when the user changes the receiver's selection, by sending it one of the
+ * messages defined in the <code>SelectionListener</code> interface.
+ * <p>
+ * When <code>widgetSelected</code> is called, the item field of the event
+ * object is valid. If the receiver has the <code>SWT.CHECK</code> style and
+ * the check selection changes, the event object detail field contains the
+ * value <code>SWT.CHECK</code>. <code>widgetDefaultSelected</code> is
+ * typically called when an item is double-clicked. The item field of the
+ * event object is valid for default selection, but the detail field is not
+ * used.
+ * </p>
+ *
+ * @param listener the listener which should be notified when the user
+ * changes the receiver's selection
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the listener is null</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ *
+ * @see SelectionListener
+ * @see #removeSelectionListener
+ * @see SelectionEvent
+ */
+ public void addSelectionListener(final SelectionListener listener) {
+ checkWidget();
+ this.selectionListeners.add(listener);
+ }
+
+ /**
+ * Deactivate the content
+ */
+ public void deactivate() {
+ this.button.setSelection(false);
+ SWTGraphicUtil.enable(this.content, false);
+ }
+
+ /**
+ * @return <code>true</code> if the content is activated, <code>false</code>
+ * otherwise
+ */
+ public boolean isActivated() {
+ return this.button.getSelection();
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Composite#getLayout()
+ */
+ @Override
+ public Layout getLayout() {
+ return this.content.getLayout();
+ }
+
+ /**
+ * Removes the listener from the collection of listeners who will be
+ * notified when the user changes the receiver's selection.
+ *
+ * @param listener the listener which should no longer be notified
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the listener is null</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ *
+ * @see SelectionListener
+ * @see #addSelectionListener
+ */
+ public void removeSelectionListener(final SelectionListener listener) {
+ checkWidget();
+ this.selectionListeners.remove(listener);
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Composite#setFocus()
+ */
+ @Override
+ public boolean setFocus() {
+ return this.content.setFocus();
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Composite#setLayout(org.eclipse.swt.widgets.Layout)
+ */
+ @Override
+ public void setLayout(final Layout layout) {
+ this.content.setLayout(layout);
+ }
+
+ // ------------------------------------ Getters and Setters
+
+ /**
+ * @return the text of the button
+ */
+ public String getText() {
+ return this.button.getText();
+ }
+
+ /**
+ * @param text the text of the button to set
+ */
+ public void setText(final String text) {
+ this.button.setText(text);
+ }
+
+ /**
+ * @return the font of the button
+ */
+ @Override
+ public Font getFont() {
+ return this.button.getFont();
+ }
+
+ /**
+ * @param font the font to set
+ */
+ @Override
+ public void setFont(final Font font) {
+ this.button.setFont(font);
+ }
+
+ /**
+ * @return the content of the group
+ */
+ public Composite getContent() {
+ return this.content;
+ }
+
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/columns/ColumnBrowserWidget.java b/org.tizen.common.externals/src/org/mihalis/opal/columns/ColumnBrowserWidget.java
new file mode 100755
index 000000000..991f6a210
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/columns/ColumnBrowserWidget.java
@@ -0,0 +1,785 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON
+ * 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:
+ * Laurent CARON (laurent.caron at gmail dot com) - Initial implementation and API
+ *******************************************************************************/
+package org.mihalis.opal.columns;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.List;
+
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.SWTException;
+import org.eclipse.swt.custom.ScrolledComposite;
+import org.eclipse.swt.events.DisposeEvent;
+import org.eclipse.swt.events.DisposeListener;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.events.SelectionListener;
+import org.eclipse.swt.graphics.Color;
+import org.eclipse.swt.graphics.Cursor;
+import org.eclipse.swt.graphics.Font;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.graphics.Rectangle;
+import org.eclipse.swt.layout.RowData;
+import org.eclipse.swt.layout.RowLayout;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Event;
+import org.eclipse.swt.widgets.Listener;
+import org.eclipse.swt.widgets.Menu;
+import org.eclipse.swt.widgets.Table;
+import org.eclipse.swt.widgets.TableColumn;
+import org.eclipse.swt.widgets.TableItem;
+import org.eclipse.swt.widgets.Widget;
+import org.mihalis.opal.utils.SWTGraphicUtil;
+
+/**
+ * Instances of this class provide a data browser similar to the ones used in
+ * Mac OS X. Look at http://en.wikipedia.org/wiki/Miller_Columns
+ * <p>
+ * <dl>
+ * <dt><b>Styles:</b></dt>
+ * <dd>BORDER</dd>
+ * <dt><b>Events:</b></dt>
+ * <dd>Selection</dd>
+ * </dl>
+ */
+public class ColumnBrowserWidget extends ScrolledComposite {
+
+ private final List<Table> columns;
+ private final Composite composite;
+ private final Image columnArrow;
+ private final List<SelectionListener> selectionListeners;
+
+ /**
+ * Constructs a new instance of this class given its parent and a style
+ * value describing its behavior and appearance.
+ * <p>
+ * The style value is either one of the style constants defined in class
+ * <code>SWT</code> which is applicable to instances of this class, or must
+ * be built by <em>bitwise OR</em>'ing together (that is, using the
+ * <code>int</code> "|" operator) two or more of those <code>SWT</code>
+ * style constants. The class description lists the style constants that are
+ * applicable to the class. Style bits are also inherited from superclasses.
+ * </p>
+ *
+ * @param parent a widget which will be the parent of the new instance
+ * (cannot be null)
+ * @param style the style of widget to construct
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the parent is null</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the parent</li>
+ * </ul>
+ *
+ * @see Composite#Composite(Composite, int)
+ * @see SWT#BORDER
+ * @see Widget#getStyle
+ */
+ public ColumnBrowserWidget(final Composite parent, final int style) {
+ super(parent, style | SWT.H_SCROLL | SWT.V_SCROLL);
+
+ this.composite = new Composite(this, SWT.NONE);
+ final RowLayout layout = new RowLayout(SWT.HORIZONTAL);
+ layout.spacing = 1;
+ layout.pack = false;
+ this.composite.setLayout(layout);
+
+ this.columnArrow = SWTGraphicUtil.createImage("images/columnArrow.png");
+
+ this.columns = new ArrayList<Table>();
+ for (int i = 0; i < 3; i++) {
+ this.createTable();
+ }
+
+ // Store root
+ this.columns.get(0).setData(new ColumnItem(this));
+
+ this.setContent(this.composite);
+ this.setExpandHorizontal(true);
+ this.setExpandVertical(true);
+ this.setShowFocusedControl(true);
+ this.updateContent();
+ this.setMinSize(this.composite.computeSize(SWT.DEFAULT, SWT.DEFAULT));
+
+ this.selectionListeners = new ArrayList<SelectionListener>();
+
+ this.addDisposeListener(new DisposeListener() {
+
+ @Override
+ public void widgetDisposed(final DisposeEvent arg0) {
+ SWTGraphicUtil.dispose(ColumnBrowserWidget.this.columnArrow);
+ }
+ });
+
+ }
+
+ /**
+ * Create a column that displays data
+ */
+ private void createTable() {
+ final Table table = new Table(this.composite, SWT.SINGLE | SWT.H_SCROLL | SWT.FULL_SELECTION | SWT.BORDER);
+ new TableColumn(table, SWT.LEFT);
+
+ table.setLayoutData(new RowData(150, 175));
+ this.columns.add(table);
+
+ table.addListener(SWT.Resize, new Listener() {
+
+ @Override
+ public void handleEvent(final Event event) {
+ final int width = table.getSize().x;
+ table.getColumn(0).setWidth(width - 5);
+ }
+ });
+
+ table.addListener(SWT.Selection, new Listener() {
+ @Override
+ public void handleEvent(final Event event) {
+ final Table table = (Table) event.widget;
+ if (table.getSelection() == null || table.getSelection().length != 1) {
+ return;
+ }
+ ColumnBrowserWidget.this.selectItem(table.getSelection()[0]);
+ }
+ });
+
+ final Listener paintListener = new Listener() {
+ @Override
+ public void handleEvent(final Event event) {
+ switch (event.type) {
+ case SWT.MeasureItem: {
+ final Rectangle rect = ColumnBrowserWidget.this.columnArrow.getBounds();
+ event.width += rect.width;
+ event.height = Math.max(event.height, rect.height + 2);
+ break;
+ }
+
+ case SWT.PaintItem: {
+ if (!(event.item instanceof TableItem)) {
+ return;
+ }
+ final TableItem item = (TableItem) event.item;
+ if (item.getData() == null) {
+ return;
+ }
+
+ if (((ColumnItem) item.getData()).getItemCount() == 0) {
+ return;
+ }
+
+ final int x = event.x + event.width;
+ final Rectangle rect = ColumnBrowserWidget.this.columnArrow.getBounds();
+ final int offset = Math.max(0, (event.height - rect.height) / 2);
+ event.gc.drawImage(ColumnBrowserWidget.this.columnArrow, x, event.y + offset);
+ break;
+ }
+ default:
+ break;
+ }
+ }
+ };
+ table.addListener(SWT.MeasureItem, paintListener);
+ table.addListener(SWT.PaintItem, paintListener);
+
+ table.addSelectionListener(new SelectionListener() {
+
+ @Override
+ public void widgetSelected(final SelectionEvent e) {
+ ColumnBrowserWidget.this.fireSelectionListeners(e);
+ }
+
+ @Override
+ public void widgetDefaultSelected(final SelectionEvent e) {
+ ColumnBrowserWidget.this.fireSelectionListeners(e);
+ }
+ });
+
+ if (super.getBackground() != null && super.getBackground().getRed() != 240 && super.getBackground().getGreen() != 240 && super.getBackground().getBlue() != 240) {
+ table.setBackground(super.getBackground());
+ }
+ table.setBackgroundImage(super.getBackgroundImage());
+ table.setBackgroundMode(super.getBackgroundMode());
+ table.setCursor(super.getCursor());
+ table.setFont(super.getFont());
+ table.setForeground(super.getForeground());
+ table.setMenu(super.getMenu());
+ table.setToolTipText(super.getToolTipText());
+
+ }
+
+ /**
+ * Fire the selection listeners
+ *
+ * @param selectionEvent mouse event
+ * @return true if the selection could be changed, false otherwise
+ */
+ private boolean fireSelectionListeners(final SelectionEvent selectionEvent) {
+ for (final SelectionListener listener : this.selectionListeners) {
+ final Event event = new Event();
+
+ event.button = 0;
+ event.display = this.getDisplay();
+ event.item = null;
+ event.widget = this;
+ event.data = null;
+ event.time = selectionEvent.time;
+ event.x = selectionEvent.x;
+ event.y = selectionEvent.y;
+
+ final SelectionEvent selEvent = new SelectionEvent(event);
+ listener.widgetSelected(selEvent);
+ if (!selEvent.doit) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Perform actions when an item is selected (ie fill the next column and
+ * force focus on it)
+ *
+ * @param tableItem selected item
+ */
+ private void selectItem(final TableItem tableItem) {
+ final ColumnItem c = (ColumnItem) tableItem.getData();
+
+ if (c.getItemCount() == 0) {
+ return;
+ }
+
+ final int selectedColumn = this.findSelectedColumn(tableItem);
+ boolean needPacking = false;
+ if (selectedColumn != this.columns.size() - 1) {
+ for (int i = selectedColumn + 1; i < this.columns.size(); i++) {
+ this.columns.get(i).setData(null);
+ this.columns.get(i).deselectAll();
+ }
+
+ int i = 0;
+ final Iterator<Table> it = this.columns.iterator();
+ while (it.hasNext()) {
+ final Table t = it.next();
+ if (i >= 3) {
+ t.dispose();
+ it.remove();
+ // Don't know why, it's not working if I do not include this
+ // :(
+ this.setMinSize(this.composite.computeSize(SWT.DEFAULT, SWT.DEFAULT));
+ }
+ i++;
+ }
+
+ if (selectedColumn != this.columns.size() - 1) {
+ this.columns.get(selectedColumn + 1).setData(c);
+ } else {
+ this.createTable();
+ this.columns.get(this.columns.size() - 1).setData(c);
+ }
+ needPacking = true;
+
+ } else {
+ this.createTable();
+ needPacking = true;
+ this.columns.get(this.columns.size() - 1).setData(c);
+ }
+ this.updateContent();
+ if (needPacking) {
+ this.composite.pack();
+ this.setMinSize(this.composite.computeSize(SWT.DEFAULT, SWT.DEFAULT));
+ }
+ this.columns.get(this.columns.size() - 1).forceFocus();
+ }
+
+ /**
+ * Find which column has been selected
+ *
+ * @param tableItem selected table item
+ * @return the index of the selected column
+ */
+ private int findSelectedColumn(final TableItem tableItem) {
+ for (int i = 0; i < this.columns.size(); i++) {
+ if (this.columns.get(i).equals(tableItem.getParent())) {
+ return i;
+ }
+ }
+ return -1;
+ }
+
+ /**
+ * Update the content of the widget
+ */
+ void updateContent() {
+ if (this.columns == null) {
+ return;
+ }
+
+ for (int i = 0; i < this.columns.size(); i++) {
+
+ final Table table = this.columns.get(i);
+ final int index = table.getSelectionIndex();
+ table.removeAll();
+ if (table.getData() == null) {
+ continue;
+ }
+ for (final ColumnItem c : ((ColumnItem) table.getData()).getItems()) {
+ final TableItem item = new TableItem(table, SWT.NONE);
+ item.setData(c);
+ if (c.getText() != null) {
+ item.setText(c.getText());
+ }
+ if (c.getImage() != null) {
+ item.setImage(c.getImage());
+ }
+ }
+ table.setSelection(index);
+ }
+ }
+
+ /**
+ * Adds the listener to the collection of listeners who will be notified
+ * when the user changes the receiver's selection, by sending it one of the
+ * messages defined in the <code>SelectionListener</code> interface.
+ * <p>
+ * When <code>widgetSelected</code> is called, the item field of the event
+ * object is valid. If the receiver has the <code>SWT.CHECK</code> style and
+ * the check selection changes, the event object detail field contains the
+ * value <code>SWT.CHECK</code>. <code>widgetDefaultSelected</code> is
+ * typically called when an item is double-clicked. The item field of the
+ * event object is valid for default selection, but the detail field is not
+ * used.
+ * </p>
+ *
+ * @param listener the listener which should be notified when the user
+ * changes the receiver's selection
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the listener is null</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ *
+ * @see SelectionListener
+ * @see #removeSelectionListener
+ * @see SelectionEvent
+ */
+ public void addSelectionListener(final SelectionListener listener) {
+ checkWidget();
+ this.selectionListeners.add(listener);
+ }
+
+ /**
+ * Clear the selection
+ *
+ * @param needPacking if <code>true</code>, the widget is packed
+ */
+ public void clear(final boolean needPacking) {
+ final Iterator<Table> it = this.columns.iterator();
+ int i = 0;
+ while (it.hasNext()) {
+ final Table t = it.next();
+ if (i >= 3) {
+ t.dispose();
+ it.remove();
+ } else {
+ if (i != 0) {
+ t.setData(null);
+ }
+ t.deselectAll();
+ }
+ i++;
+ }
+ this.updateContent();
+ if (needPacking) {
+ this.composite.pack();
+ this.setMinSize(this.composite.computeSize(SWT.DEFAULT, SWT.DEFAULT));
+ }
+ this.columns.get(0).forceFocus();
+ }
+
+ /**
+ * Returns the <code>ColumnItem</code>s that is currently selected in the
+ * receiver.
+ *
+ * @return the selected item, or <code>null</code> if no one is selected
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public ColumnItem getSelection() {
+ for (int i = this.columns.size() - 1; i >= 0; i--) {
+ final Table table = this.columns.get(i);
+ if (table == null || table.getData() == null || table.getSelection().length == 0) {
+ continue;
+ }
+
+ return (ColumnItem) table.getItem(table.getSelectionIndex()).getData();
+
+ }
+ return null;
+ }
+
+ /**
+ * Removes the listener from the collection of listeners who will be
+ * notified when the user changes the receiver's selection.
+ *
+ * @param listener the listener which should no longer be notified
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the listener is null</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ *
+ * @see SelectionListener
+ * @see #addSelectionListener
+ */
+ public void removeSelectionListener(final SelectionListener listener) {
+ checkWidget();
+ this.selectionListeners.remove(listener);
+ }
+
+ /**
+ * Selects an item in the receiver. If the item was already selected, it
+ * remains selected.
+ *
+ * @param item the item to be selected
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the item is null</li>
+ * <li>ERROR_INVALID_ARGUMENT - if the item has been disposed
+ * </li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void select(final ColumnItem item) {
+
+ final List<ColumnItem> items = new ArrayList<ColumnItem>();
+ this.findElement(item, items);
+ Collections.reverse(items);
+ if (items.isEmpty()) {
+ return;
+ }
+
+ this.clear(false);
+ for (int i = 3; i < items.size(); i++) {
+ this.createTable();
+ }
+ for (int i = 0; i < items.size() - 1; i++) {
+ this.columns.get(i + 1).setData(items.get(i));
+ }
+ this.updateContent();
+
+ for (int i = 0; i < this.columns.size() - 1; i++) {
+ final ColumnItem nextItem = (ColumnItem) this.columns.get(i + 1).getData();
+ for (final TableItem tableItem : this.columns.get(i).getItems()) {
+ if (tableItem.getData() != null && tableItem.getData().equals(nextItem)) {
+ tableItem.getParent().setSelection(tableItem);
+ }
+ }
+ }
+
+ this.composite.pack();
+ this.setMinSize(this.composite.computeSize(SWT.DEFAULT, SWT.DEFAULT));
+ this.columns.get(this.columns.size() - 1).forceFocus();
+
+ }
+
+ /**
+ * Build an array that contains the hierarchy of ColumnItem from the root
+ * node to a given item.
+ *
+ * @param item item to find
+ * @param items the lists of item that composes the hierarchy
+ */
+ private void findElement(final ColumnItem item, final List<ColumnItem> items) {
+ if (item == null) {
+ return;
+ }
+ items.add(item);
+ this.findElement(item.getParentItem(), items);
+ }
+
+ /**
+ * Sets the receiver's background color to the color specified by the
+ * argument, or to the default system color for the control if the argument
+ * is null.
+ * <p>
+ * Note: This operation is a hint and may be overridden by the platform. For
+ * example, on Windows the background of a Button cannot be changed.
+ * </p>
+ *
+ * @param color the new color (or null)
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_INVALID_ARGUMENT - if the argument has been
+ * disposed</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ * @see org.eclipse.swt.widgets.Control#setBackground(org.eclipse.swt.graphics.Color)
+ */
+ @Override
+ public void setBackground(final Color color) {
+ super.setBackground(color);
+ for (final Table column : this.columns) {
+ column.setBackground(color);
+ }
+ }
+
+ /**
+ * Sets the background drawing mode to the argument which should be one of
+ * the following constants defined in class <code>SWT</code>:
+ * <code>INHERIT_NONE</code>, <code>INHERIT_DEFAULT</code>,
+ * <code>INHERIT_FORCE</code>.
+ *
+ * @param mode the new background mode
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ *
+ * @see SWT
+ * @see org.eclipse.swt.widgets.Composite#setBackgroundMode(int)
+ */
+ @Override
+ public void setBackgroundMode(final int mode) {
+ super.setBackgroundMode(mode);
+ for (final Table column : this.columns) {
+ column.setBackgroundMode(mode);
+ }
+ }
+
+ /**
+ * Sets the receiver's background image to the image specified by the
+ * argument, or to the default system color for the control if the argument
+ * is null. The background image is tiled to fill the available space.
+ * <p>
+ * Note: This operation is a hint and may be overridden by the platform. For
+ * example, on Windows the background of a Button cannot be changed.
+ * </p>
+ *
+ * @param image the new image (or null)
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_INVALID_ARGUMENT - if the argument has been
+ * disposed</li>
+ * <li>ERROR_INVALID_ARGUMENT - if the argument is not a
+ * bitmap</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ *
+ * @see org.eclipse.swt.widgets.Control#setBackgroundImage(org.eclipse.swt.graphics.Image)
+ */
+ @Override
+ public void setBackgroundImage(final Image image) {
+ super.setBackgroundImage(image);
+ for (final Table column : this.columns) {
+ column.setBackgroundImage(image);
+ }
+ }
+
+ /**
+ * Sets the receiver's cursor to the cursor specified by the argument, or to
+ * the default cursor for that kind of control if the argument is null.
+ * <p>
+ * When the mouse pointer passes over a control its appearance is changed to
+ * match the control's cursor.
+ * </p>
+ *
+ * @param cursor the new cursor (or null)
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_INVALID_ARGUMENT - if the argument has been
+ * disposed</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ * @see org.eclipse.swt.widgets.Control#setCursor(org.eclipse.swt.graphics.Cursor)
+ */
+ @Override
+ public void setCursor(final Cursor cursor) {
+ super.setCursor(cursor);
+ for (final Table column : this.columns) {
+ column.setCursor(cursor);
+ }
+ }
+
+ /**
+ * Sets the font that the receiver will use to paint textual information to
+ * the font specified by the argument, or to the default font for that kind
+ * of control if the argument is null.
+ *
+ * @param font the new font (or null)
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_INVALID_ARGUMENT - if the argument has been
+ * disposed</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ * @see org.eclipse.swt.widgets.Control#setFont(org.eclipse.swt.graphics.Font)
+ */
+ @Override
+ public void setFont(final Font font) {
+ super.setFont(font);
+ for (final Table column : this.columns) {
+ column.setFont(font);
+ }
+ }
+
+ /**
+ * Sets the receiver's foreground color to the color specified by the
+ * argument, or to the default system color for the control if the argument
+ * is null.
+ * <p>
+ * Note: This operation is a hint and may be overridden by the platform.
+ * </p>
+ *
+ * @param color the new color (or null)
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_INVALID_ARGUMENT - if the argument has been
+ * disposed</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ * @see org.eclipse.swt.widgets.Control#setForeground(org.eclipse.swt.graphics.Color)
+ */
+ @Override
+ public void setForeground(final Color color) {
+ super.setForeground(color);
+ for (final Table column : this.columns) {
+ column.setForeground(color);
+ }
+ }
+
+ /**
+ * Sets the receiver's pop up menu to the argument. All controls may
+ * optionally have a pop up menu that is displayed when the user requests
+ * one for the control. The sequence of key strokes, button presses and/or
+ * button releases that are used to request a pop up menu is platform
+ * specific.
+ * <p>
+ * Note: Disposing of a control that has a pop up menu will dispose of the
+ * menu. To avoid this behavior, set the menu to null before the control is
+ * disposed.
+ * </p>
+ *
+ * @param menu the new pop up menu
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_MENU_NOT_POP_UP - the menu is not a pop up menu</li>
+ * <li>ERROR_INVALID_PARENT - if the menu is not in the same
+ * widget tree</li>
+ * <li>ERROR_INVALID_ARGUMENT - if the menu has been disposed
+ * </li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ * @see org.eclipse.swt.widgets.Control#setMenu(org.eclipse.swt.widgets.Menu)
+ */
+ @Override
+ public void setMenu(final Menu menu) {
+ super.setMenu(menu);
+ for (final Table column : this.columns) {
+ column.setMenu(menu);
+ }
+ }
+
+ /**
+ * Sets the receiver's tool tip text to the argument, which may be null
+ * indicating that the default tool tip for the control will be shown. For a
+ * control that has a default tool tip, such as the Tree control on Windows,
+ * setting the tool tip text to an empty string replaces the default,
+ * causing no tool tip text to be shown.
+ * <p>
+ * The mnemonic indicator (character '&amp;') is not displayed in a tool
+ * tip. To display a single '&amp;' in the tool tip, the character '&amp;'
+ * can be escaped by doubling it in the string.
+ * </p>
+ *
+ * @param string the new tool tip text (or null)
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ * @see org.eclipse.swt.widgets.Control#setToolTipText(java.lang.String)
+ */
+ @Override
+ public void setToolTipText(final String tooltipText) {
+ super.setToolTipText(tooltipText);
+ for (final Table column : this.columns) {
+ column.setToolTipText(tooltipText);
+ }
+ }
+
+ /**
+ * @return the root item, or null if there is no data
+ */
+ ColumnItem getRootItem() {
+ if (this.columns == null || this.columns.isEmpty()) {
+ return null;
+ }
+ return (ColumnItem) this.columns.get(0).getData();
+ }
+
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/columns/ColumnItem.java b/org.tizen.common.externals/src/org/mihalis/opal/columns/ColumnItem.java
new file mode 100644
index 000000000..52d63fa70
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/columns/ColumnItem.java
@@ -0,0 +1,416 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON
+ * 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:
+ * Laurent CARON (laurent.caron at gmail dot com) - Initial implementation and API
+ *******************************************************************************/
+package org.mihalis.opal.columns;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.SWTException;
+import org.mihalis.opal.OpalItem;
+
+/**
+ * Instances of this object are items manipulated by the ColumnBrowser widget.
+ * ColumnItems are part of a tree structure .
+ *
+ * @see OpalItem
+ */
+public class ColumnItem extends OpalItem {
+
+ private final ColumnBrowserWidget widget;
+ private final ColumnItem parent;
+ private final List<ColumnItem> children;
+
+ /**
+ * Constructs a new instance of this class given its parent. The item is
+ * added to the end of the items maintained by its parent.
+ *
+ * @param widget the widget that will contain this item (can not be null)
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the parent is null</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * </ul>
+ */
+ public ColumnItem(final ColumnBrowserWidget widget) {
+ if (widget == null) {
+ SWT.error(SWT.ERROR_NULL_ARGUMENT);
+ }
+
+ if (widget.isDisposed()) {
+ SWT.error(SWT.ERROR_WIDGET_DISPOSED);
+ }
+
+ this.widget = widget;
+ this.parent = null;
+ this.children = new ArrayList<ColumnItem>();
+
+ if (widget.getRootItem() != null) {
+ widget.getRootItem().children.add(this);
+ }
+ widget.updateContent();
+ }
+
+ /**
+ * Constructs a new instance of this class given its parent. The item is
+ * added at a given position in the items'list maintained by its parent.
+ *
+ * @param widget the widget that will contain this item (can not be null)
+ * @param index the position
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the parent is null</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * </ul>
+ */
+ public ColumnItem(final ColumnBrowserWidget widget, final int index) {
+
+ if (widget == null) {
+ SWT.error(SWT.ERROR_NULL_ARGUMENT);
+ }
+
+ if (widget.isDisposed()) {
+ SWT.error(SWT.ERROR_WIDGET_DISPOSED);
+ }
+
+ this.widget = widget;
+ this.parent = null;
+ this.children = new ArrayList<ColumnItem>();
+ widget.getRootItem().children.add(index, this);
+ widget.updateContent();
+ }
+
+ /**
+ * Constructs a new instance of this class given its parent. The item is
+ * added to the end of the items maintained by its parent.
+ *
+ * @param widget the widget that will contain this item (can not be null)
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the parent is null</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * </ul>
+ */
+ public ColumnItem(final ColumnItem parent) {
+
+ if (parent == null) {
+ SWT.error(SWT.ERROR_NULL_ARGUMENT);
+ }
+
+ if (parent.widget.isDisposed()) {
+ SWT.error(SWT.ERROR_WIDGET_DISPOSED);
+ }
+
+ this.widget = parent.widget;
+ this.parent = parent;
+ this.children = new ArrayList<ColumnItem>();
+ parent.children.add(this);
+ parent.widget.updateContent();
+ }
+
+ /**
+ * Constructs a new instance of this class given its parent. The item is
+ * added at a given position in the items'list maintained by its parent.
+ *
+ * @param widget the widget that will contain this item (can not be null)
+ * @param index the position
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the parent is null</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * </ul>
+ */
+ public ColumnItem(final ColumnItem parent, final int index) {
+ if (parent == null) {
+ SWT.error(SWT.ERROR_NULL_ARGUMENT);
+ }
+
+ if (parent.widget.isDisposed()) {
+ SWT.error(SWT.ERROR_WIDGET_DISPOSED);
+ }
+
+ this.widget = parent.widget;
+ this.parent = parent;
+ this.children = new ArrayList<ColumnItem>();
+ parent.children.add(index, this);
+ parent.widget.updateContent();
+ }
+
+ /**
+ * Remove a given children of this object
+ *
+ * @param item the item to remove (can not be null)
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the parent is null</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * </ul>
+ */
+ public void remove(final ColumnItem item) {
+ if (this.widget == null) {
+ SWT.error(SWT.ERROR_NULL_ARGUMENT);
+ }
+
+ if (this.widget.isDisposed()) {
+ SWT.error(SWT.ERROR_WIDGET_DISPOSED);
+ }
+ this.children.remove(item);
+ this.widget.updateContent();
+ }
+
+ /**
+ * Remove a children in a given position of this object
+ *
+ * @param index position of the children in the items'list
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the parent is null</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * </ul>
+ */
+ public void remove(final int index) {
+ if (this.widget == null) {
+ SWT.error(SWT.ERROR_NULL_ARGUMENT);
+ }
+
+ if (this.widget.isDisposed()) {
+ SWT.error(SWT.ERROR_WIDGET_DISPOSED);
+ }
+ this.children.remove(index);
+ this.widget.updateContent();
+ }
+
+ /**
+ * Remove all children of this object
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the parent is null</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * </ul>
+ */
+ public void removeAll() {
+ if (this.widget == null) {
+ SWT.error(SWT.ERROR_NULL_ARGUMENT);
+ }
+
+ if (this.widget.isDisposed()) {
+ SWT.error(SWT.ERROR_WIDGET_DISPOSED);
+ }
+ this.children.clear();
+ this.widget.updateContent();
+ }
+
+ /**
+ * Returns an item located at a given position
+ *
+ * @param index position
+ * @return the item located at the index position
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the parent is null</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * </ul>
+ */
+ public ColumnItem getItem(final int index) {
+ if (this.widget == null) {
+ SWT.error(SWT.ERROR_NULL_ARGUMENT);
+ }
+
+ if (this.widget.isDisposed()) {
+ SWT.error(SWT.ERROR_WIDGET_DISPOSED);
+ }
+ return this.children.get(index);
+ }
+
+ /**
+ * @return the number of children
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the parent is null</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * </ul>
+ */
+ public int getItemCount() {
+ if (this.widget == null) {
+ SWT.error(SWT.ERROR_NULL_ARGUMENT);
+ }
+
+ if (this.widget.isDisposed()) {
+ SWT.error(SWT.ERROR_WIDGET_DISPOSED);
+ }
+ return this.children.size();
+ }
+
+ /**
+ * @return all children of this item
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the parent is null</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * </ul>
+ */
+ public ColumnItem[] getItems() {
+ if (this.widget == null) {
+ SWT.error(SWT.ERROR_NULL_ARGUMENT);
+ }
+
+ if (this.widget.isDisposed()) {
+ SWT.error(SWT.ERROR_WIDGET_DISPOSED);
+ }
+ return this.children.toArray(new ColumnItem[this.children.size()]);
+ }
+
+ /**
+ * @return the widget that holds this item
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the parent is null</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * </ul>
+ */
+ public ColumnBrowserWidget getParent() {
+ if (this.widget == null) {
+ SWT.error(SWT.ERROR_NULL_ARGUMENT);
+ }
+
+ if (this.widget.isDisposed()) {
+ SWT.error(SWT.ERROR_WIDGET_DISPOSED);
+ }
+ return this.widget;
+ }
+
+ /**
+ * @return the parent item, of <code>null</code> if this item is the root
+ * node
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the parent is null</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * </ul>
+ */
+ public ColumnItem getParentItem() {
+ if (this.widget == null) {
+ SWT.error(SWT.ERROR_NULL_ARGUMENT);
+ }
+
+ if (this.widget.isDisposed()) {
+ SWT.error(SWT.ERROR_WIDGET_DISPOSED);
+ }
+ return this.parent;
+ }
+
+ /**
+ * Return the position of a given item in children's list
+ *
+ * @param item item to find
+ * @return the position of the children, or -1 if <code>item</code> is a not
+ * a children of this object
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the parent is null</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * </ul>
+ */
+ public int indexOf(final ColumnItem item) {
+ return this.children.indexOf(item);
+ }
+
+ /**
+ * @see java.lang.Object#hashCode()
+ */
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + (this.parent == null ? 0 : this.parent.hashCode());
+ result = prime * result + (this.widget == null ? 0 : this.widget.hashCode());
+ return result;
+ }
+
+ /**
+ * @see java.lang.Object#equals(java.lang.Object)
+ */
+ @Override
+ public boolean equals(final Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (obj == null) {
+ return false;
+ }
+ if (getClass() != obj.getClass()) {
+ return false;
+ }
+ final ColumnItem other = (ColumnItem) obj;
+ if (this.children == null) {
+ if (other.children != null) {
+ return false;
+ }
+ } else if (!this.children.equals(other.children)) {
+ return false;
+ }
+ if (this.parent == null) {
+ if (other.parent != null) {
+ return false;
+ }
+ } else if (!this.parent.equals(other.parent)) {
+ return false;
+ }
+ if (this.widget == null) {
+ if (other.widget != null) {
+ return false;
+ }
+ } else if (!this.widget.equals(other.widget)) {
+ return false;
+ }
+ return true;
+ }
+
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/flatButton/FlatButton.java b/org.tizen.common.externals/src/org/mihalis/opal/flatButton/FlatButton.java
new file mode 100644
index 000000000..ede14ba2f
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/flatButton/FlatButton.java
@@ -0,0 +1,633 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON
+ * 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:
+ * Laurent CARON (laurent.caron at gmail dot com) - initial API and implementation
+ *******************************************************************************/
+package org.mihalis.opal.flatButton;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.SWTException;
+import org.eclipse.swt.events.PaintEvent;
+import org.eclipse.swt.events.PaintListener;
+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.Point;
+import org.eclipse.swt.graphics.Rectangle;
+import org.eclipse.swt.widgets.Canvas;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Event;
+import org.eclipse.swt.widgets.Listener;
+import org.mihalis.opal.utils.SWTGraphicUtil;
+
+/**
+ * Instances of this class represent a flat button.
+ * <dl>
+ * <dt><b>Styles:</b></dt>
+ * <dd>(none)</dd>
+ * <dd>UP, DOWN, LEFT, RIGHT, CENTER</dd>
+ * <dt><b>Events:</b></dt>
+ * <dd>Selection</dd>
+ * </dl>
+ * <p>
+ * Note: Only one of the styles LEFT, RIGHT, and CENTER may be specified.
+ * </p>
+ *
+ */
+public class FlatButton extends Canvas {
+ private Image image;
+ private String text;
+ private boolean selection;
+ private int alignment;
+ private final List<SelectionListener> listeners;
+ private boolean mouseIn;
+ private Color backgroundColor;
+ private Color selectedColor;
+ private Color selectedTextColor;
+ private Color mouseOverColor;
+
+ /**
+ * Constructs a new instance of this class given its parent and a style
+ * value describing its behavior and appearance.
+ * <p>
+ * The style value is either one of the style constants defined in class
+ * <code>SWT</code> which is applicable to instances of this class, or must
+ * be built by <em>bitwise OR</em>'ing together (that is, using the
+ * <code>int</code> "|" operator) two or more of those <code>SWT</code>
+ * style constants. The class description lists the style constants that are
+ * applicable to the class. Style bits are also inherited from superclasses.
+ * </p>
+ *
+ * @param parent a composite control which will be the parent of the new
+ * instance (cannot be null)
+ * @param style the style of control to construct
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the parent is null</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the parent</li>
+ * <li>ERROR_INVALID_SUBCLASS - if this class is not an
+ * allowed subclass</li>
+ * </ul>
+ *
+ * @see SWT#DOWN
+ * @see SWT#LEFT
+ * @see SWT#RIGHT
+ * @see SWT#CENTER
+ */
+ public FlatButton(final Composite parent, final int style) {
+ super(parent, style);
+ this.listeners = new ArrayList<SelectionListener>();
+ buildAlignmentFromStyle(style);
+ addListeners();
+ initializeDefaultColors();
+ }
+
+ private void buildAlignmentFromStyle(final int style) {
+ if ((style & SWT.LEFT) == SWT.LEFT) {
+ this.alignment = SWT.LEFT;
+ } else if ((style & SWT.RIGHT) == SWT.RIGHT) {
+ this.alignment = SWT.RIGHT;
+ } else {
+ this.alignment = SWT.CENTER;
+
+ }
+ }
+
+ private void addListeners() {
+ addPaintListener(new PaintListener() {
+ @Override
+ public void paintControl(final PaintEvent e) {
+ FlatButton.this.paintControl(e);
+ }
+ });
+
+ addListener(SWT.MouseEnter, new Listener() {
+ @Override
+ public void handleEvent(final Event event) {
+ FlatButton.this.mouseIn = true;
+ redraw();
+ }
+ });
+
+ addListener(SWT.MouseExit, new Listener() {
+ @Override
+ public void handleEvent(final Event event) {
+ FlatButton.this.mouseIn = false;
+ redraw();
+ }
+ });
+
+ addListener(SWT.MouseUp, new Listener() {
+ @Override
+ public void handleEvent(final Event event) {
+ boolean doIt = true;
+ FlatButton.this.selection = !FlatButton.this.selection;
+ for (final SelectionListener listener : FlatButton.this.listeners) {
+ final SelectionEvent sEvent = new SelectionEvent(event);
+ listener.widgetSelected(sEvent);
+ doIt = doIt && sEvent.doit;
+ }
+ if (!doIt) {
+ FlatButton.this.selection = !FlatButton.this.selection;
+ }
+ }
+
+ });
+ }
+
+ private void initializeDefaultColors() {
+ this.backgroundColor = getDisplay().getSystemColor(SWT.COLOR_WHITE);
+ this.selectedColor = new Color(getDisplay(), 0, 112, 192);
+ this.selectedTextColor = getDisplay().getSystemColor(SWT.COLOR_WHITE);
+ this.mouseOverColor = new Color(getDisplay(), 235, 234, 226);
+
+ SWTGraphicUtil.dispose(this, this.selectedColor);
+ SWTGraphicUtil.dispose(this, this.mouseOverColor);
+ SWTGraphicUtil.dispose(this, this.image);
+ }
+
+ private void paintControl(final PaintEvent e) {
+ final GC gc = e.gc;
+ drawBackground(gc);
+ if (this.image != null) {
+ drawImage(gc);
+ }
+ if (this.text != null) {
+ drawText(gc);
+ }
+ }
+
+ private void drawBackground(final GC gc) {
+ Color color;
+ if (this.selection) {
+ color = this.selectedColor;
+ } else if (this.mouseIn) {
+ color = this.mouseOverColor;
+ } else {
+ color = this.backgroundColor;
+ }
+ gc.setBackground(color);
+ gc.fillRectangle(getClientArea());
+
+ }
+
+ private void drawImage(final GC gc) {
+ final Rectangle rect = getClientArea();
+ final Point imageSize = new Point(this.image.getBounds().width, this.image.getBounds().height);
+
+ int x;
+ if (this.alignment == SWT.LEFT) {
+ x = 5;
+ } else if (this.alignment == SWT.RIGHT) {
+ x = rect.width - imageSize.x - 5;
+ } else {
+ x = (rect.width - imageSize.x) / 2;
+ }
+ gc.drawImage(this.image, x, 5);
+ }
+
+ private void drawText(final GC gc) {
+ final Rectangle rect = getClientArea();
+
+ if (this.selection) {
+ gc.setForeground(this.selectedTextColor);
+ } else {
+ gc.setForeground(getForeground());
+ }
+
+ gc.setFont(getFont());
+ final Point textSize = gc.stringExtent(this.text);
+ int x, y;
+
+ if (this.alignment == SWT.LEFT) {
+ x = 5;
+ } else if (this.alignment == SWT.RIGHT) {
+ x = rect.width - textSize.x - 5;
+ } else {
+ x = (rect.width - textSize.x) / 2;
+ }
+ if (this.image == null) {
+ y = 5;
+ } else {
+ y = 10 + this.image.getBounds().height;
+ }
+ gc.drawString(this.text, x, y, true);
+ }
+
+ /**
+ * Adds the listener to the collection of listeners who will be notified
+ * when the control is selected by the user, by sending it one of the
+ * messages defined in the <code>SelectionListener</code> interface.
+ * <p>
+ * <code>widgetSelected</code> is called when the control is selected by the
+ * user. <code>widgetDefaultSelected</code> is not called.
+ * </p>
+ * <p>
+ * When the <code>SWT.RADIO</code> style bit is set, the
+ * <code>widgetSelected</code> method is also called when the receiver loses
+ * selection because another item in the same radio group was selected by
+ * the user. During <code>widgetSelected</code> the application can use
+ * <code>getSelection()</code> to determine the current selected state of
+ * the receiver.
+ * </p>
+ *
+ * @param listener the listener which should be notified
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the listener is null</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ *
+ * @see SelectionListener
+ * @see #removeSelectionListener
+ * @see SelectionEvent
+ */
+ public void addSelectionListener(final SelectionListener listener) {
+ checkWidget();
+ this.listeners.add(listener);
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Composite#computeSize(int, int, boolean)
+ */
+ @Override
+ public Point computeSize(final int wHint, final int hHint, final boolean changed) {
+ int width = 10, height = 15;
+ if (this.image != null) {
+ final Rectangle bounds = this.image.getBounds();
+ width += bounds.width;
+ height += bounds.height;
+ }
+
+ if (this.text != null) {
+ final GC gc = new GC(this);
+ final Point extent = gc.stringExtent(this.text);
+ gc.dispose();
+ width = Math.max(width, extent.x + 10);
+ height = height + extent.y;
+ }
+
+ return new Point(Math.max(width, wHint), Math.max(height, hHint));
+ }
+
+ /**
+ * Returns a value which describes the position of the text in the receiver.
+ * The value will be one of <code>LEFT</code>, <code>RIGHT</code> or
+ * <code>CENTER</code>.
+ *
+ * @return the alignment
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public int getAlignment() {
+ checkWidget();
+ return this.alignment;
+ }
+
+ /**
+ * Returns a value which describes the default background color
+ *
+ * @return the default background color
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public Color getBackgroundColor() {
+ checkWidget();
+ return this.backgroundColor;
+ }
+
+ /**
+ * Returns the receiver's image if it has one, or null if it does not.
+ *
+ * @return the receiver's image
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public Image getImage() {
+ checkWidget();
+ return this.image;
+ }
+
+ /**
+ * Returns a value which describes the color when the mouse is over the
+ * button
+ *
+ * @return the color when the mouse is over the button
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public Color getMouseOverColor() {
+ checkWidget();
+ return this.mouseOverColor;
+ }
+
+ /**
+ * Returns a value which describes the color when the button is selected
+ *
+ * @return the color when the button is selected
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public Color getSelectedColor() {
+ checkWidget();
+ return this.selectedColor;
+ }
+
+ /**
+ * Returns a value which describes the color of the text when the button is
+ * selected
+ *
+ * @return the color of the text when the button is selected
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+
+ public Color getSelectedTextColor() {
+ return this.selectedTextColor;
+ }
+
+ /**
+ * Returns <code>true</code> if the receiver is selected, and false
+ * otherwise.
+ * <p>
+ *
+ * @return the selection state
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li> <li>ERROR_THREAD_INVALID_ACCESS - if not
+ * called from the thread that created the receiver</li>
+ * </ul>
+ */
+ public boolean getSelection() {
+ checkWidget();
+ return this.selection;
+ }
+
+ /**
+ * Returns the receiver's text.
+ *
+ * @return the receiver's text
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public String getText() {
+ checkWidget();
+ return this.text;
+ }
+
+ /**
+ * Removes the listener from the collection of listeners who will be
+ * notified when the control is selected by the user.
+ *
+ * @param listener the listener which should no longer be notified
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the listener is null</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ *
+ * @see SelectionListener
+ * @see #addSelectionListener
+ */
+ public void removeSelectionListener(final SelectionListener listener) {
+ checkWidget();
+ this.listeners.remove(listener);
+ }
+
+ /**
+ * Controls how text, images and arrows will be displayed in the receiver.
+ * The argument should be one of <code>LEFT</code>, <code>RIGHT</code> or
+ * <code>CENTER</code>.
+ *
+ * @param alignment the new alignment
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void setAlignment(final int alignment) {
+ checkWidget();
+ if ((alignment & (SWT.LEFT | SWT.RIGHT | SWT.CENTER)) == 0) {
+ return;
+ }
+ this.alignment = alignment;
+ redraw();
+ }
+
+ /**
+ * Sets the receiver's background color to the color specified by the
+ * argument.
+ *
+ * @param color the new color
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_INVALID_ARGUMENT - if the argument has been
+ * disposed</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void setBackgroundColor(final Color backgroundColor) {
+ checkWidget();
+ this.backgroundColor = backgroundColor;
+ }
+
+ /**
+ * Sets the receiver's image to the argument, which may be <code>null</code>
+ * indicating that no image should be displayed.
+ * <p>
+ * Note that a Button can display an image and text simultaneously on
+ * Windows (starting with XP), GTK+ and OSX. On other platforms, a Button
+ * that has an image and text set into it will display the image or text
+ * that was set most recently.
+ * </p>
+ *
+ * @param image the image to display on the receiver (may be
+ * <code>null</code>)
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_INVALID_ARGUMENT - if the image has been
+ * disposed</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void setImage(final Image image) {
+ checkWidget();
+ this.image = image;
+ redraw();
+ }
+
+ /**
+ * Sets the receiver's color when the mouse if over the button.
+ *
+ * @param color the new color
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_INVALID_ARGUMENT - if the argument has been
+ * disposed</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void setMouseOverColor(final Color mouseOverColor) {
+ checkWidget();
+ this.mouseOverColor = mouseOverColor;
+ }
+
+ /**
+ * Sets the receiver's color when the button is selected.
+ *
+ * @param color the new color
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_INVALID_ARGUMENT - if the argument has been
+ * disposed</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void setSelectedColor(final Color selectedColor) {
+ checkWidget();
+ this.selectedColor = selectedColor;
+ }
+
+ /**
+ * Sets the receiver's text color when the button is selected.
+ *
+ * @param color the new color
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_INVALID_ARGUMENT - if the argument has been
+ * disposed</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void setSelectedTextColor(final Color selectedTextColor) {
+ this.selectedTextColor = selectedTextColor;
+ }
+
+ /**
+ * Sets the selection state of the receiver.
+ *
+ * @param selected the new selection state
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void setSelection(final boolean selected) {
+ checkWidget();
+ this.selection = selected;
+ redraw();
+ }
+
+ /**
+ * Sets the receiver's text.
+ *
+ *
+ * @param string the new text
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the text is null</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void setText(final String text) {
+ checkWidget();
+ this.text = text;
+ redraw();
+ }
+
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/gradientComposite/GradientComposite.java b/org.tizen.common.externals/src/org/mihalis/opal/gradientComposite/GradientComposite.java
new file mode 100644
index 000000000..80e5c6736
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/gradientComposite/GradientComposite.java
@@ -0,0 +1,154 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON
+ * 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:
+ * Laurent CARON (laurent.caron at gmail dot com) - Initial implementation and API
+ *******************************************************************************/
+package org.mihalis.opal.gradientComposite;
+
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.SWTException;
+import org.eclipse.swt.events.DisposeEvent;
+import org.eclipse.swt.events.DisposeListener;
+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 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.Widget;
+import org.mihalis.opal.utils.SWTGraphicUtil;
+
+/**
+ * Instances of this class are controls which background's texture is a gradient
+ * composite
+ */
+public class GradientComposite extends Composite {
+ private Image oldImage;
+ private Color gradientEnd;
+ private Color gradientStart;
+
+ /**
+ * Constructs a new instance of this class given its parent and a style
+ * value describing its behavior and appearance.
+ * <p>
+ * The style value is either one of the style constants defined in class
+ * <code>SWT</code> which is applicable to instances of this class, or must
+ * be built by <em>bitwise OR</em>'ing together (that is, using the
+ * <code>int</code> "|" operator) two or more of those <code>SWT</code>
+ * style constants. The class description lists the style constants that are
+ * applicable to the class. Style bits are also inherited from superclasses.
+ * </p>
+ *
+ * @param parent a widget which will be the parent of the new instance
+ * (cannot be null)
+ * @param style the style of widget to construct
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the parent is null</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the parent</li>
+ * </ul>
+ *
+ * @see Composite#Composite(Composite, int)
+ * @see SWT#NO_BACKGROUND
+ * @see SWT#NO_FOCUS
+ * @see SWT#NO_MERGE_PAINTS
+ * @see SWT#NO_REDRAW_RESIZE
+ * @see SWT#NO_RADIO_GROUP
+ * @see SWT#EMBEDDED
+ * @see SWT#DOUBLE_BUFFERED
+ * @see Widget#getStyle
+ */
+ public GradientComposite(final Composite parent, final int style) {
+ super(parent, style);
+ this.addListener(SWT.Resize, new Listener() {
+ @Override
+ public void handleEvent(final Event event) {
+ GradientComposite.this.redrawComposite();
+ }
+ });
+
+ parent.addDisposeListener(new DisposeListener() {
+
+ @Override
+ public void widgetDisposed(final DisposeEvent e) {
+ SWTGraphicUtil.dispose(GradientComposite.this.oldImage);
+ SWTGraphicUtil.dispose(GradientComposite.this.gradientEnd);
+ SWTGraphicUtil.dispose(GradientComposite.this.gradientStart);
+ }
+
+ });
+
+ this.gradientEnd = new Color(this.getDisplay(), 110, 110, 110);
+ this.gradientStart = new Color(this.getDisplay(), 0, 0, 0);
+
+ }
+
+ /**
+ * Redraws the composite
+ */
+ private void redrawComposite() {
+ final Display display = this.getDisplay();
+ final Rectangle rect = this.getClientArea();
+ final Image newImage = new Image(display, Math.max(1, rect.width), Math.max(1, rect.height));
+
+ final GC gc = new GC(newImage);
+ gc.setForeground(this.gradientStart);
+ gc.setBackground(this.gradientEnd);
+
+ gc.fillGradientRectangle(rect.x, rect.y, rect.width, rect.height / 2, true);
+
+ gc.setForeground(this.gradientEnd);
+ gc.setBackground(this.gradientStart);
+
+ gc.fillGradientRectangle(rect.x, rect.height / 2, rect.width, rect.height / 2, true);
+ gc.dispose();
+
+ this.setBackgroundImage(newImage);
+ if (this.oldImage != null) {
+ this.oldImage.dispose();
+ }
+ this.oldImage = newImage;
+
+ }
+
+ // ------------------------------------ Getters and Setters
+ /**
+ * @return the gradientEnd color
+ */
+ public Color getGradientEnd() {
+ return this.gradientEnd;
+ }
+
+ /**
+ * @param gradientEnd the gradientEnd color to set
+ */
+ public void setGradientEnd(final Color gradientEnd) {
+ SWTGraphicUtil.dispose(this.gradientEnd);
+ this.gradientEnd = gradientEnd;
+ }
+
+ /**
+ * @return the gradientStart color
+ */
+ public Color getGradientStart() {
+ return this.gradientStart;
+ }
+
+ /**
+ * @param gradientStart the gradientStart color to set
+ */
+ public void setGradientStart(final Color gradientStart) {
+ SWTGraphicUtil.dispose(this.gradientStart);
+ this.gradientStart = gradientStart;
+ }
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/header/Header.java b/org.tizen.common.externals/src/org/mihalis/opal/header/Header.java
new file mode 100644
index 000000000..6cdd42366
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/header/Header.java
@@ -0,0 +1,529 @@
+package org.mihalis.opal.header;
+
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.SWTException;
+import org.eclipse.swt.custom.StyledText;
+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.Rectangle;
+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.Event;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Layout;
+import org.eclipse.swt.widgets.Listener;
+import org.mihalis.opal.utils.SWTGraphicUtil;
+
+/**
+ * Instances of this class provide a header, which is composed of a text, a
+ * description and an image.
+ * <p>
+ * <dl>
+ * <dt><b>Styles:</b></dt>
+ * <dd>BORDER</dd>
+ * <dt><b>Events:</b></dt>
+ * <dd>(none)</dd>
+ * </dl>
+ */
+public class Header extends Composite {
+
+ private Image image;
+ private String title;
+ private String description;
+ private Font titleFont;
+ private Color titleColor;
+
+ private Image oldImage;
+ private Color gradientEnd;
+ private Color gradientStart;
+ private Color separatorColor;
+
+ /**
+ * Constructs a new instance of this class given its parent and a style
+ * value describing its behavior and appearance.
+ * <p>
+ * The style value is either one of the style constants defined in class
+ * <code>SWT</code> which is applicable to instances of this class, or must
+ * be built by <em>bitwise OR</em>'ing together (that is, using the
+ * <code>int</code> "|" operator) two or more of those <code>SWT</code>
+ * style constants. The class description lists the style constants that are
+ * applicable to the class. Style bits are also inherited from superclasses.
+ * </p>
+ *
+ * @param parent a composite control which will be the parent of the new
+ * instance (cannot be null)
+ * @param style the style of control to construct
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the parent is null</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the parent</li>
+ * </ul>
+ *
+ */
+ public Header(final Composite parent, final int style) {
+ super(parent, style);
+
+ final FontData[] fontData = getFont().getFontData();
+ if (fontData != null && fontData.length > 0) {
+ final FontData fd = fontData[0];
+ fd.setStyle(SWT.BOLD);
+ fd.setHeight(fd.getHeight() + 2);
+ this.titleFont = new Font(getDisplay(), fd);
+ } else {
+ this.titleFont = null;
+ }
+
+ this.titleColor = new Color(getDisplay(), 0, 88, 150);
+
+ this.gradientEnd = new Color(this.getDisplay(), 239, 239, 239);
+ this.gradientStart = new Color(this.getDisplay(), 255, 255, 255);
+ this.separatorColor = new Color(this.getDisplay(), 229, 229, 229);
+
+ this.addListener(SWT.Resize, new Listener() {
+ @Override
+ public void handleEvent(final Event event) {
+ redrawComposite();
+ }
+ });
+
+ this.addListener(SWT.Dispose, new Listener() {
+ @Override
+ public void handleEvent(final Event event) {
+ SWTGraphicUtil.dispose(Header.this.titleColor);
+ SWTGraphicUtil.dispose(Header.this.titleFont);
+ SWTGraphicUtil.dispose(Header.this.oldImage);
+ SWTGraphicUtil.dispose(Header.this.gradientEnd);
+ SWTGraphicUtil.dispose(Header.this.gradientStart);
+ SWTGraphicUtil.dispose(Header.this.separatorColor);
+ }
+ });
+ setBackgroundMode(SWT.INHERIT_FORCE);
+ }
+
+ /**
+ * Redraw the composite
+ */
+ private void redrawComposite() {
+ // Dispose previous content
+ for (final Control c : this.getChildren()) {
+ c.dispose();
+ }
+
+ int numberOfColumns = 1;
+ if (this.image != null) {
+ numberOfColumns++;
+ }
+
+ super.setLayout(new GridLayout(numberOfColumns, false));
+ createContent();
+ drawBackground();
+ }
+
+ /**
+ * Create the content (title, image, description)
+ */
+ private void createContent() {
+ if (this.title != null) {
+ createTitle();
+ }
+
+ if (this.image != null) {
+ createImage();
+ }
+
+ if (this.description != null) {
+ createDescription();
+ }
+ }
+
+ /**
+ * Create the title
+ */
+ private void createTitle() {
+ final Label labelTitle = new Label(this, SWT.NONE);
+ labelTitle.setLayoutData(new GridData(GridData.FILL, GridData.BEGINNING, true, false));
+ labelTitle.setFont(this.titleFont);
+ labelTitle.setForeground(this.titleColor);
+ labelTitle.setText(this.title);
+ }
+
+ /**
+ * Create the image
+ */
+ private void createImage() {
+
+ int numberOfLines = 1;
+
+ if (this.title != null && this.description != null) {
+ numberOfLines++;
+ }
+ final Label labelImage = new Label(this, SWT.NONE);
+ labelImage.setLayoutData(new GridData(GridData.FILL, GridData.BEGINNING, false, true, 1, numberOfLines));
+ labelImage.setImage(this.image);
+ }
+
+ /**
+ * Create the description
+ */
+ private void createDescription() {
+ final StyledText labelDescription = new StyledText(this, SWT.WRAP | SWT.READ_ONLY);
+ labelDescription.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, true));
+ labelDescription.setEnabled(false);
+ labelDescription.setFont(getFont());
+ labelDescription.setForeground(getForeground());
+ labelDescription.setText("<html><body>" + this.description + "</body></html>");
+ SWTGraphicUtil.applyHTMLFormating(labelDescription);
+ }
+
+ /**
+ * Draw the background (a gradient+a separator)
+ */
+ private void drawBackground() {
+ final Display display = this.getDisplay();
+ final Rectangle rect = this.getClientArea();
+ final Image newImage = new Image(display, Math.max(1, rect.width), Math.max(1, rect.height));
+
+ final GC gc = new GC(newImage);
+ gc.setForeground(this.gradientStart);
+ gc.setBackground(this.gradientEnd);
+
+ gc.fillGradientRectangle(rect.x, rect.y, rect.width, rect.height, false);
+
+ gc.setForeground(this.separatorColor);
+ gc.drawLine(rect.x, rect.y + rect.height - 1, rect.x + rect.width, rect.y + rect.height - 1);
+
+ gc.dispose();
+
+ this.setBackgroundImage(newImage);
+ if (this.oldImage != null) {
+ this.oldImage.dispose();
+ }
+ this.oldImage = newImage;
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Composite#setLayout(org.eclipse.swt.widgets.Layout)
+ */
+ @Override
+ public void setLayout(final Layout layout) {
+ throw new UnsupportedOperationException("Not supported");
+ }
+
+ // ------------------------------------ Getters and Setters
+
+ /**
+ * Returns the receiver's description if it has one, or null if it does not.
+ *
+ * @return the receiver's description if it has one, or null if it does not
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public String getDescription() {
+ checkWidget();
+ return this.description;
+ }
+
+ /**
+ * Returns the receiver's gradient end color.
+ *
+ * @return the receiver's gradient end color
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public Color getGradientEnd() {
+ checkWidget();
+ return this.gradientEnd;
+ }
+
+ /**
+ * Returns the receiver's gradient start color.
+ *
+ * @return the receiver's gradient start color
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public Color getGradientStart() {
+ checkWidget();
+ return this.gradientStart;
+ }
+
+ /**
+ * Returns the receiver's image if it has one, or null if it does not.
+ *
+ * @return the receiver's image if it has one, or null if it does not
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public Image getImage() {
+ checkWidget();
+ return this.image;
+ }
+
+ /**
+ * Returns the receiver's separator color.
+ *
+ * @return the receiver's separator color
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public Color getSeparatorColor() {
+ checkWidget();
+ return this.separatorColor;
+ }
+
+ /**
+ * Returns the receiver's title if it has one, or null if it does not.
+ *
+ * @return the receiver's title if it has one, or null if it does not
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public String getTitle() {
+ checkWidget();
+ return this.title;
+ }
+
+ /**
+ * Returns the title's color.
+ *
+ * @return the title's color
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public Color getTitleColor() {
+ checkWidget();
+ return this.titleColor;
+ }
+
+ /**
+ * Returns the title's font.
+ *
+ * @return the title's font.
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public Font getTitleFont() {
+ checkWidget();
+ return this.titleFont;
+ }
+
+ /**
+ * Sets the receiver's description to the argument, which may be null
+ * indicating that no description should be displayed.
+ *
+ * @param description the description of the header (may be null)
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_INVALID_ARGUMENT - if the image has been
+ * disposed</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void setDescription(final String description) {
+ checkWidget();
+ this.description = description;
+ }
+
+ /**
+ * Sets the receiver's gradient end color.
+ *
+ * @param gradientEnd the receiver's gradient end color
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_INVALID_ARGUMENT - if the image has been
+ * disposed</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void setGradientEnd(final Color gradientEnd) {
+ checkWidget();
+ this.gradientEnd = gradientEnd;
+ }
+
+ /**
+ * Sets the receiver's gradient start color.
+ *
+ * @param gradientStart the receiver's gradient start color
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_INVALID_ARGUMENT - if the image has been
+ * disposed</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void setGradientStart(final Color gradientStart) {
+ checkWidget();
+ this.gradientStart = gradientStart;
+ }
+
+ /**
+ * Sets the receiver's image to the argument, which may be null indicating
+ * that no image should be displayed.
+ *
+ * @param image the image to display on the receiver (may be null)
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_INVALID_ARGUMENT - if the image has been
+ * disposed</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void setImage(final Image image) {
+ checkWidget();
+ this.image = image;
+ }
+
+ /**
+ * Sets the receiver's separator color.
+ *
+ * @param separatorColor the receiver's separator color
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_INVALID_ARGUMENT - if the image has been
+ * disposed</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void setSeparatorColor(final Color separatorColor) {
+ this.separatorColor = separatorColor;
+ }
+
+ /**
+ * Sets the receiver's title to the argument, which may be null indicating
+ * that no title should be displayed.
+ *
+ * @param title the title
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_INVALID_ARGUMENT - if the image has been
+ * disposed</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void setTitle(final String title) {
+ checkWidget();
+ this.title = title;
+ }
+
+ /**
+ * Sets the receiver's title color.
+ *
+ * @param headerColor the receiver's title color
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_INVALID_ARGUMENT - if the image has been
+ * disposed</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void setTitleColor(final Color headerColor) {
+ checkWidget();
+ this.titleColor = headerColor;
+ }
+
+ /**
+ * Sets the receiver's title font.
+ *
+ * @param headerFont the receiver's title font
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_INVALID_ARGUMENT - if the image has been
+ * disposed</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void setTitleFont(final Font headerFont) {
+ checkWidget();
+ this.titleFont = headerFont;
+ }
+
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/heapManager/HeapManager.java b/org.tizen.common.externals/src/org/mihalis/opal/heapManager/HeapManager.java
new file mode 100644
index 000000000..a702b6fab
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/heapManager/HeapManager.java
@@ -0,0 +1,297 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON
+ * 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:
+ * Laurent CARON (laurent.caron at gmail dot com) - Initial implementation and API
+ *******************************************************************************/
+package org.mihalis.opal.heapManager;
+
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.SWTException;
+import org.eclipse.swt.events.DisposeEvent;
+import org.eclipse.swt.events.DisposeListener;
+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.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.Canvas;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Widget;
+import org.mihalis.opal.utils.ResourceManager;
+import org.mihalis.opal.utils.SWTGraphicUtil;
+
+/**
+ * Instances of this class are controls that display the memory used, the whole
+ * memory, and contains a button to perform a GC
+ */
+public class HeapManager extends Composite {
+ private Canvas bar;
+ private Button button;
+ private int heapMaxSize;
+ private int heapSize;
+ private Color barBorderColor;
+ private Color barInnerColor;
+ private Color barTextColor;
+ private Color barGradientColorTopStart;
+ private Color barGradientColorTopEnd;
+ private Color barGradientColorMiddleStart;
+
+ /**
+ * Constructs a new instance of this class given its parent and a style
+ * value describing its behavior and appearance.
+ * <p>
+ * The style value is either one of the style constants defined in class
+ * <code>SWT</code> which is applicable to instances of this class, or must
+ * be built by <em>bitwise OR</em>'ing together (that is, using the
+ * <code>int</code> "|" operator) two or more of those <code>SWT</code>
+ * style constants. The class description lists the style constants that are
+ * applicable to the class. Style bits are also inherited from superclasses.
+ * </p>
+ *
+ * @param parent a widget which will be the parent of the new instance
+ * (cannot be null)
+ * @param style the style of widget to construct
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the parent is null</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the parent</li>
+ * </ul>
+ *
+ * @see Composite#Composite(Composite, int)
+ * @see Widget#getStyle
+ */
+ public HeapManager(final Composite parent, final int style) {
+ super(parent, style);
+ final GridLayout gridLayout = new GridLayout(2, false);
+ gridLayout.horizontalSpacing = gridLayout.verticalSpacing = 0;
+ setLayout(gridLayout);
+
+ createBar();
+ createButton();
+ updateContent();
+ createDefaultColors();
+
+ addDisposeListener(new DisposeListener() {
+
+ @Override
+ public void widgetDisposed(final DisposeEvent e) {
+ SWTGraphicUtil.dispose(HeapManager.this.barBorderColor);
+ SWTGraphicUtil.dispose(HeapManager.this.barInnerColor);
+ SWTGraphicUtil.dispose(HeapManager.this.barGradientColorTopStart);
+ SWTGraphicUtil.dispose(HeapManager.this.barGradientColorTopEnd);
+ SWTGraphicUtil.dispose(HeapManager.this.barGradientColorMiddleStart);
+ SWTGraphicUtil.dispose(HeapManager.this.barTextColor);
+ }
+ });
+
+ }
+
+ /**
+ * Creates the bar that displays the memory
+ */
+ private void createBar() {
+ this.bar = new Canvas(this, SWT.NONE);
+ final GridData gd = new GridData(GridData.FILL, GridData.FILL, true, false);
+ gd.minimumWidth = 100;
+ gd.heightHint = 30;
+ this.bar.setLayoutData(gd);
+ this.heapMaxSize = (int) (Runtime.getRuntime().maxMemory() / (1024 * 1024));
+ this.bar.addPaintListener(new PaintListener() {
+
+ @Override
+ public void paintControl(final PaintEvent e) {
+ drawBar(e);
+ }
+ });
+ }
+
+ /**
+ * Draw the bar
+ *
+ * @param e {@link PaintEvent}
+ */
+ private void drawBar(final PaintEvent e) {
+ final GC gc = e.gc;
+ final Rectangle clientArea = this.bar.getClientArea();
+
+ gc.setForeground(this.barBorderColor);
+ gc.setBackground(this.barInnerColor);
+ gc.fillRectangle(clientArea);
+ gc.drawRectangle(clientArea.x, clientArea.y, clientArea.width - 1, clientArea.height - 1);
+
+ final float width = (clientArea.width - 2f) * this.heapSize / this.heapMaxSize;
+
+ gc.setForeground(this.barGradientColorTopStart);
+ gc.setBackground(this.barGradientColorTopEnd);
+ gc.fillGradientRectangle(clientArea.x + 1, clientArea.y + 1, (int) width, clientArea.height / 2, true);
+
+ gc.setForeground(this.barGradientColorMiddleStart);
+ gc.setBackground(this.barBorderColor);
+ gc.fillGradientRectangle(clientArea.x + 1, clientArea.height / 2, (int) width, clientArea.height / 2, true);
+
+ final String message = this.heapSize + " " + ResourceManager.getLabel(ResourceManager.MEGABYTES) + "/" + //
+ this.heapMaxSize + " " + ResourceManager.getLabel(ResourceManager.MEGABYTES);
+ final Point size = gc.stringExtent(message);
+
+ gc.setForeground(this.barTextColor);
+ gc.setFont(getFont());
+ gc.drawText(message, (clientArea.width - size.x) / 2, (clientArea.height - size.y) / 2, true);
+
+ gc.dispose();
+
+ }
+
+ /**
+ * Create the button used to perform GC
+ */
+ private void createButton() {
+ this.button = new Button(this, SWT.PUSH);
+ this.button.setImage(SWTGraphicUtil.createImage("images/trash.png"));
+ this.button.setLayoutData(new GridData(GridData.FILL, GridData.FILL, false, false));
+ this.button.addSelectionListener(new SelectionAdapter() {
+
+ /**
+ * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
+ */
+ @Override
+ public void widgetSelected(final SelectionEvent e) {
+ System.gc();
+ }
+
+ });
+ this.button.setToolTipText(ResourceManager.getLabel(ResourceManager.PERFORM_GC));
+ this.button.pack();
+ }
+
+ /**
+ * Update the content of the bar
+ */
+ private void updateContent() {
+ getDisplay().timerExec(500, new Runnable() {
+
+ @Override
+ public void run() {
+ HeapManager.this.heapSize = (int) (Runtime.getRuntime().totalMemory() / (1024 * 1024));
+ if (!isDisposed()) {
+ HeapManager.this.bar.redraw();
+ if (!getDisplay().isDisposed()) {
+ getDisplay().timerExec(500, this);
+ }
+ }
+ }
+ });
+
+ }
+
+ /**
+ * Creates the default colors
+ */
+ private void createDefaultColors() {
+ this.barTextColor = new Color(getDisplay(), 57, 98, 149);
+ this.barInnerColor = new Color(getDisplay(), 219, 230, 243);
+ this.barBorderColor = new Color(getDisplay(), 101, 148, 207);
+ this.barGradientColorTopStart = new Color(getDisplay(), 175, 202, 237);
+ this.barGradientColorTopEnd = new Color(getDisplay(), 136, 177, 229);
+ this.barGradientColorMiddleStart = new Color(getDisplay(), 112, 161, 223);
+
+ }
+
+ /**
+ * @return the barBorderColor
+ */
+ public Color getBarBorderColor() {
+ return this.barBorderColor;
+ }
+
+ /**
+ * @param barBorderColor the barBorderColor to set
+ */
+ public void setBarBorderColor(final Color barBorderColor) {
+ this.barBorderColor = barBorderColor;
+ }
+
+ /**
+ * @return the barInnerColor
+ */
+ public Color getBarInnerColor() {
+ return this.barInnerColor;
+ }
+
+ /**
+ * @param barInnerColor the barInnerColor to set
+ */
+ public void setBarInnerColor(final Color barInnerColor) {
+ this.barInnerColor = barInnerColor;
+ }
+
+ /**
+ * @return the barTextColor
+ */
+ public Color getBarTextColor() {
+ return this.barTextColor;
+ }
+
+ /**
+ * @param barTextColor the barTextColor to set
+ */
+ public void setBarTextColor(final Color barTextColor) {
+ this.barTextColor = barTextColor;
+ }
+
+ /**
+ * @return the barGradientColorTopStart
+ */
+ public Color getBarGradientColorTopStart() {
+ return this.barGradientColorTopStart;
+ }
+
+ /**
+ * @param barGradientColorTopStart the barGradientColorTopStart to set
+ */
+ public void setBarGradientColorTopStart(final Color barGradientColorTopStart) {
+ this.barGradientColorTopStart = barGradientColorTopStart;
+ }
+
+ /**
+ * @return the barGradientColorTopEnd
+ */
+ public Color getBarGradientColorTopEnd() {
+ return this.barGradientColorTopEnd;
+ }
+
+ /**
+ * @param barGradientColorTopEnd the barGradientColorTopEnd to set
+ */
+ public void setBarGradientColorTopEnd(final Color barGradientColorTopEnd) {
+ this.barGradientColorTopEnd = barGradientColorTopEnd;
+ }
+
+ /**
+ * @return the barGradientColorMiddleStart
+ */
+ public Color getBarGradientColorMiddleStart() {
+ return this.barGradientColorMiddleStart;
+ }
+
+ /**
+ * @param barGradientColorMiddleStart the barGradientColorMiddleStart to set
+ */
+ public void setBarGradientColorMiddleStart(final Color barGradientColorMiddleStart) {
+ this.barGradientColorMiddleStart = barGradientColorMiddleStart;
+ }
+
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/horizontalSpinner/HorizontalSpinner.java b/org.tizen.common.externals/src/org/mihalis/opal/horizontalSpinner/HorizontalSpinner.java
new file mode 100644
index 000000000..5362a36f0
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/horizontalSpinner/HorizontalSpinner.java
@@ -0,0 +1,947 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON
+ * 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:
+ * Laurent CARON (laurent.caron at gmail dot com) - Implementation
+ *******************************************************************************/
+package org.mihalis.opal.horizontalSpinner;
+
+import java.text.DecimalFormatSymbols;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.SWTException;
+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.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.Color;
+import org.eclipse.swt.graphics.Cursor;
+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.Menu;
+import org.eclipse.swt.widgets.Text;
+import org.mihalis.opal.utils.StringUtil;
+
+/**
+ * Instances of this class are selectable user interface objects that allow the user to enter and modify numeric values.
+ * <p>
+ * <dl>
+ * <dt><b>Styles:</b></dt>
+ * <dd>READ_ONLY, FLAP</dd>
+ * <dt><b>Events:</b></dt>
+ * <dd>Selection, Modify</dd>
+ * </dl>
+ * </p>
+ */
+public class HorizontalSpinner extends Composite {
+ private final List<ModifyListener> modifyListeners = new ArrayList<ModifyListener>();
+ private final List<SelectionListener> selectionListeners = new ArrayList<SelectionListener>();
+
+ private Button leftButton;
+ private Button rightButton;
+ private Text text;
+ private int digits = 0;
+ private int increment = 1;
+ private int maximum = 0;
+ private int minimum = 255;
+ private int pageIncrement = 10;
+ private int storedValue = 0;
+
+ private final char decimalFormatSeparator;
+
+ /**
+ * Constructs a new instance of this class given its parent and a style value describing its behavior and appearance.
+ * <p>
+ * The style value is either one of the style constants defined in class <code>SWT</code> which is applicable to instances of this class, or must be built by <em>bitwise OR</em>'ing together (that is, using the <code>int</code> "|" operator) two or more of those <code>SWT</code> style constants. The class description lists the style constants that are applicable to the class. Style bits are also inherited from superclasses.
+ * </p>
+ *
+ * @param parent a composite control which will be the parent of the new instance (cannot be null)
+ * @param style the style of control to construct
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the parent is null</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the parent</li>
+ * <li>ERROR_INVALID_SUBCLASS - if this class is not an allowed subclass</li>
+ * </ul>
+ *
+ * @see SWT#READ_ONLY
+ * @see SWT#FLAT
+ */
+ public HorizontalSpinner(final Composite parent, final int style) {
+ super(parent, style);
+
+ final GridLayout gd = new GridLayout(3, false);
+ gd.horizontalSpacing = gd.verticalSpacing = 0;
+ gd.marginWidth = gd.marginHeight = 0;
+ this.setLayout(gd);
+
+ this.createContent(style);
+ this.addTextListeners();
+ this.addButtonsListener();
+ this.addModifyListeners();
+
+ this.decimalFormatSeparator = new DecimalFormatSymbols().getDecimalSeparator();
+ }
+
+ /**
+ * Create the content of the widget
+ *
+ * @param style style of the widget
+ */
+ private void createContent(final int style) {
+ final boolean readOnly = (style & SWT.READ_ONLY) == SWT.READ_ONLY;
+ final boolean flat = (style & SWT.FLAT) == SWT.FLAT;
+
+ final int buttonStyle = SWT.ARROW | (flat ? SWT.FLAT : SWT.NONE);
+ this.leftButton = new Button(this, buttonStyle | SWT.LEFT);
+ this.leftButton.setFont(this.getFont());
+ this.leftButton.setBackground(this.getBackground());
+ this.leftButton.setCursor(this.getCursor());
+ this.leftButton.setEnabled(this.getEnabled());
+ this.leftButton.setFont(this.getFont());
+ this.leftButton.setForeground(this.getForeground());
+ this.leftButton.setLayoutData(new GridData(GridData.FILL, GridData.FILL, false, false));
+
+ this.text = new Text(this, readOnly ? SWT.READ_ONLY : SWT.NONE);
+ final GridData gd = new GridData(GridData.FILL, GridData.CENTER, true, false);
+ gd.minimumWidth = 40;
+ this.text.setLayoutData(gd);
+
+ this.rightButton = new Button(this, buttonStyle | SWT.RIGHT);
+ this.rightButton.setFont(this.getFont());
+ this.rightButton.setBackground(this.getBackground());
+ this.rightButton.setCursor(this.getCursor());
+ this.rightButton.setEnabled(this.getEnabled());
+ this.rightButton.setFont(this.getFont());
+ this.rightButton.setForeground(this.getForeground());
+ this.rightButton.setLayoutData(new GridData(GridData.FILL, GridData.FILL, false, false));
+
+ }
+
+ /**
+ * Add the text listeners
+ */
+ private void addTextListeners() {
+ this.text.addVerifyListener(new VerifyListener() {
+
+ @Override
+ public void verifyText(final VerifyEvent e) {
+ if (e.character != 0 && !Character.isDigit(e.character) && e.keyCode != SWT.BS && e.keyCode != SWT.DEL) {
+ e.doit = false;
+ return;
+ }
+
+ e.doit = HorizontalSpinner.this.verifyEntryAndStoreValue(e.text, e.keyCode);
+
+ }
+ });
+
+ this.text.addKeyListener(new KeyAdapter() {
+
+ /**
+ * @see org.eclipse.swt.events.KeyAdapter#keyReleased(org.eclipse.swt.events.KeyEvent)
+ */
+ @Override
+ public void keyReleased(final KeyEvent e) {
+ if (e.keyCode == SWT.ARROW_UP) {
+ HorizontalSpinner.this.increaseValue(HorizontalSpinner.this.increment);
+ }
+ if (e.keyCode == SWT.ARROW_DOWN) {
+ HorizontalSpinner.this.decreaseValue(HorizontalSpinner.this.increment);
+ }
+ if (e.keyCode == SWT.PAGE_UP) {
+ HorizontalSpinner.this.increaseValue(HorizontalSpinner.this.pageIncrement);
+ }
+ if (e.keyCode == SWT.PAGE_DOWN) {
+ HorizontalSpinner.this.decreaseValue(HorizontalSpinner.this.pageIncrement);
+ }
+ }
+
+ });
+
+ this.text.addFocusListener(new org.eclipse.swt.events.FocusAdapter() {
+
+ /**
+ * @see org.eclipse.swt.events.FocusAdapter#focusLost(org.eclipse.swt.events.FocusEvent)
+ */
+ @Override
+ public void focusLost(final org.eclipse.swt.events.FocusEvent e) {
+ if (HorizontalSpinner.this.text.getText().trim().equals("")) {
+ HorizontalSpinner.this.setSelection(HorizontalSpinner.this.storedValue);
+ }
+ }
+
+ });
+
+ }
+
+ /**
+ * Verify the entry and store the value in the field storedValue
+ *
+ * @param entry entry to check
+ * @param keyCode code of the typed key
+ * @return <code>true</code> if the entry if correct, <code>false</code> otherwise
+ */
+ private boolean verifyEntryAndStoreValue(final String entry, final int keyCode) {
+ final String work;
+ if (keyCode == SWT.DEL) {
+ work = StringUtil.removeCharAt(this.text.getText(), this.text.getCaretPosition());
+ } else if (keyCode == SWT.BS && this.text.getCaretPosition() == 0) {
+ work = StringUtil.removeCharAt(this.text.getText(), this.text.getCaretPosition() - 1);
+ } else if (keyCode == 0) {
+ work = entry;
+ } else {
+ work = StringUtil.insertString(this.text.getText(), entry, this.text.getCaretPosition());
+ }
+
+ try {
+ final double d = Double.parseDouble(work.replace(this.decimalFormatSeparator, '.'));
+ this.storedValue = (int) (d * Math.pow(10, this.getDigits()));
+ } catch (final NumberFormatException nfe) {
+ return false;
+ }
+
+ for (final SelectionListener s : HorizontalSpinner.this.selectionListeners) {
+ s.widgetSelected(null);
+ }
+
+ return true;
+ }
+
+ /**
+ * Add the listener to the buttons
+ */
+ private void addButtonsListener() {
+ this.leftButton.addSelectionListener(new SelectionAdapter() {
+
+ /**
+ * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
+ */
+ @Override
+ public void widgetSelected(final SelectionEvent e) {
+ HorizontalSpinner.this.decreaseValue(HorizontalSpinner.this.increment);
+ }
+ });
+
+ this.rightButton.addSelectionListener(new SelectionAdapter() {
+
+ /**
+ * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
+ */
+ @Override
+ public void widgetSelected(final SelectionEvent e) {
+ HorizontalSpinner.this.increaseValue(HorizontalSpinner.this.increment);
+ }
+ });
+
+ }
+
+ /**
+ * Increase the value stored in this snippet
+ *
+ * @param value value to increase
+ */
+ private void increaseValue(final int value) {
+ this.setSelection(this.getSelection() + value);
+
+ }
+
+ /**
+ * Decrease the value stored in this snippet
+ *
+ * @param value value to decrease
+ */
+ private void decreaseValue(final int value) {
+ this.setSelection(this.getSelection() - value);
+ }
+
+ /**
+ * Add the modify listeners
+ */
+ private void addModifyListeners() {
+ this.text.addModifyListener(new ModifyListener() {
+
+ @Override
+ public void modifyText(final ModifyEvent e) {
+ for (final ModifyListener m : HorizontalSpinner.this.modifyListeners) {
+ m.modifyText(e);
+ }
+
+ }
+ });
+
+ }
+
+ /**
+ * Adds the listener to the collection of listeners who will be notified when the receiver's text is modified, by sending it one of the messages defined in the <code>ModifyListener</code> interface.
+ *
+ * @param listener the listener which should be notified
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the listener is null</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
+ * </ul>
+ *
+ * @see ModifyListener
+ * @see #removeModifyListener
+ * @see org.eclipse.swt.widgets.Spinner#addModifyListener(org.eclipse.swt.events.ModifyListener)
+ */
+
+ public void addModifyListener(final ModifyListener listener) {
+ this.checkWidget();
+ this.modifyListeners.add(listener);
+ }
+
+ /**
+ * Adds the listener to the collection of listeners who will be notified when the control is selected by the user, by sending it one of the messages defined in the <code>SelectionListener</code> interface.
+ * <p>
+ * <code>widgetSelected</code> is not called for texts. <code>widgetDefaultSelected</code> is typically called when ENTER is pressed in a single-line text.
+ * </p>
+ *
+ * @param listener the listener which should be notified when the control is selected by the user
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the listener is null</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
+ * </ul>
+ *
+ * @see SelectionListener
+ * @see #removeSelectionListener
+ * @see SelectionEvent
+ */
+ public void addSelectionListener(final SelectionListener listener) {
+ this.checkWidget();
+ this.selectionListeners.add(listener);
+ }
+
+ /**
+ * Copies the selected text.
+ * <p>
+ * The current selection is copied to the clipboard.
+ * </p>
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
+ * </ul>
+ */
+ public void copy() {
+ this.checkWidget();
+ this.text.copy();
+ }
+
+ /**
+ * Cuts the selected text.
+ * <p>
+ * The current selection is first copied to the clipboard and then deleted from the widget.
+ * </p>
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
+ * </ul>
+ */
+ public void cut() {
+ this.checkWidget();
+ this.text.cut();
+ }
+
+ /**
+ * Returns the number of decimal places used by the receiver.
+ *
+ * @return the digits
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
+ * </ul>
+ */
+ public int getDigits() {
+ this.checkWidget();
+ return this.digits;
+ }
+
+ /**
+ * Returns the amount that the receiver's value will be modified by when the up/down arrows are pressed.
+ *
+ * @return the increment
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
+ * </ul>
+ */
+ public int getIncrement() {
+ this.checkWidget();
+ return this.increment;
+ }
+
+ /**
+ * Returns the maximum value which the receiver will allow.
+ *
+ * @return the maximum
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
+ * </ul>
+ */
+ public int getMaximum() {
+ this.checkWidget();
+ return this.maximum;
+ }
+
+ /**
+ * Returns the minimum value which the receiver will allow.
+ *
+ * @return the minimum
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
+ * </ul>
+ */
+ public int getMinimum() {
+ this.checkWidget();
+ return this.minimum;
+ }
+
+ /**
+ * Returns the amount that the receiver's position will be modified by when the page up/down keys are pressed.
+ *
+ * @return the page increment
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
+ * </ul>
+ */
+ public int getPageIncrement() {
+ this.checkWidget();
+ return this.pageIncrement;
+ }
+
+ /**
+ * Returns the <em>selection</em>, which is the receiver's position.
+ *
+ * @return the selection
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
+ * </ul>
+ */
+ public int getSelection() {
+ this.checkWidget();
+ return this.storedValue;
+
+ }
+
+ /**
+ * Returns a string containing a copy of the contents of the receiver's text field, or an empty string if there are no contents.
+ *
+ * @return the receiver's text
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
+ * </ul>
+ *
+ */
+ public String getText() {
+ this.checkWidget();
+ return this.text.getText();
+ }
+
+ /**
+ * Returns the maximum number of characters that the receiver's text field is capable of holding. If this has not been changed by <code>setTextLimit()</code>, it will be the constant <code>Spinner.LIMIT</code>.
+ *
+ * @return the text limit
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
+ * </ul>
+ *
+ * @see #LIMIT
+ */
+ public int getTextLimit() {
+ this.checkWidget();
+ return this.text.getTextLimit();
+ }
+
+ /**
+ * Pastes text from clipboard.
+ * <p>
+ * The selected text is deleted from the widget and new text inserted from the clipboard.
+ * </p>
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
+ * </ul>
+ */
+ public void paste() {
+ this.checkWidget();
+ this.text.paste();
+ }
+
+ /**
+ * Removes the listener from the collection of listeners who will be notified when the receiver's text is modified.
+ *
+ * @param listener the listener which should no longer be notified
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the listener is null</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
+ * </ul>
+ *
+ * @see ModifyListener
+ * @see #addModifyListener
+ */
+ public void removeModifyListener(final ModifyListener listener) {
+ this.checkWidget();
+ this.modifyListeners.remove(listener);
+ }
+
+ /**
+ * Removes the listener from the collection of listeners who will be notified when the control is selected by the user.
+ *
+ * @param listener the listener which should no longer be notified
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the listener is null</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
+ * </ul>
+ *
+ * @see SelectionListener
+ * @see #addSelectionListener
+ */
+ public void removeSelectionListener(final SelectionListener listener) {
+ this.checkWidget();
+ this.selectionListeners.remove(listener);
+ }
+
+ /**
+ * Sets the number of decimal places used by the receiver.
+ * <p>
+ * The digit setting is used to allow for floating point values in the receiver. For example, to set the selection to a floating point value of 1.37 call setDigits() with a value of 2 and setSelection() with a value of 137. Similarly, if getDigits() has a value of 2 and getSelection() returns 137 this should be interpreted as 1.37. This applies to all numeric APIs.
+ * </p>
+ *
+ * @param value the new digits (must be greater than or equal to zero)
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_INVALID_ARGUMENT - if the value is less than zero</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
+ * </ul>
+ */
+ public void setDigits(final int value) {
+ this.checkWidget();
+ this.digits = value;
+ this.convertSelection();
+ }
+
+ /**
+ * Sets the amount that the receiver's value will be modified by when the up/down arrows are pressed to the argument, which must be at least one.
+ *
+ * @param value the new increment (must be greater than zero)
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
+ * </ul>
+ */
+ public void setIncrement(final int value) {
+ this.checkWidget();
+ this.increment = value;
+ }
+
+ /**
+ * Sets the maximum value that the receiver will allow. This new value will be ignored if it is less than the receiver's current minimum value. If the new maximum is applied then the receiver's selection value will be adjusted if necessary to fall within its new range.
+ *
+ * @param value the new maximum, which must be greater than or equal to the current minimum
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
+ * </ul>
+ */
+ public void setMaximum(final int value) {
+ this.checkWidget();
+ this.maximum = value;
+ }
+
+ /**
+ * Sets the minimum value that the receiver will allow. This new value will be ignored if it is greater than the receiver's current maximum value. If the new minimum is applied then the receiver's selection value will be adjusted if necessary to fall within its new range.
+ *
+ * @param value the new minimum, which must be less than or equal to the current maximum
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
+ * </ul>
+ */
+ public void setMinimum(final int value) {
+ this.checkWidget();
+ this.minimum = value;
+ }
+
+ /**
+ * Sets the amount that the receiver's position will be modified by when the page up/down keys are pressed to the argument, which must be at least one.
+ *
+ * @param value the page increment (must be greater than zero)
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
+ * </ul>
+ */
+ public void setPageIncrement(final int value) {
+ this.checkWidget();
+ this.pageIncrement = value;
+ }
+
+ /**
+ * Sets the <em>selection</em>, which is the receiver's position, to the argument. If the argument is not within the range specified by minimum and maximum, it will be adjusted to fall within this range.
+ *
+ * @param value the new selection (must be zero or greater)
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
+ * </ul>
+ */
+ public void setSelection(int selection) {
+ this.checkWidget();
+ if (selection < this.minimum) {
+ selection = this.minimum;
+ } else if (selection > this.maximum) {
+ selection = this.maximum;
+ }
+
+ this.storedValue = selection;
+ this.text.setText(this.convertSelection());
+ this.text.selectAll();
+ this.text.setFocus();
+
+ for (final SelectionListener s : HorizontalSpinner.this.selectionListeners) {
+ s.widgetSelected(null);
+ }
+
+ }
+
+ /**
+ * Convert the selection into a string
+ *
+ * @return the string representation of the selection
+ */
+ private String convertSelection() {
+ if (this.getDigits() == 0) {
+ return String.valueOf(this.storedValue);
+ }
+ final String temp = String.valueOf(this.storedValue * Math.pow(10, -1 * this.getDigits()));
+ return temp.replace('.', this.decimalFormatSeparator);
+ }
+
+ /**
+ * Sets the maximum number of characters that the receiver's text field is capable of holding to be the argument.
+ * <p>
+ * To reset this value to the default, use <code>setTextLimit(Spinner.LIMIT)</code>. Specifying a limit value larger than <code>Spinner.LIMIT</code> sets the receiver's limit to <code>Spinner.LIMIT</code>.
+ * </p>
+ *
+ * @param limit new text limit
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_CANNOT_BE_ZERO - if the limit is zero</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
+ * </ul>
+ *
+ * @see #LIMIT
+ */
+ public void setTextLimit(final int limit) {
+ this.checkWidget();
+ this.text.setTextLimit(limit);
+ }
+
+ /**
+ * Sets the receiver's selection, minimum value, maximum value, digits, increment and page increment all at once.
+ * <p>
+ * Note: This is similar to setting the values individually using the appropriate methods, but may be implemented in a more efficient fashion on some platforms.
+ * </p>
+ *
+ * @param selection the new selection value
+ * @param minimum the new minimum value
+ * @param maximum the new maximum value
+ * @param digits the new digits value
+ * @param increment the new increment value
+ * @param pageIncrement the new pageIncrement value
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
+ * </ul>
+ */
+ public void setValues(final int selection, final int minimum, final int maximum, final int digits, final int increment, final int pageIncrement) {
+ this.setMinimum(minimum);
+ this.setMaximum(maximum);
+ this.setDigits(digits);
+ this.setIncrement(increment);
+ this.setPageIncrement(pageIncrement);
+ this.setSelection(selection);
+ }
+
+ /**
+ * Sets the receiver's drag detect state. If the argument is <code>true</code>, the receiver will detect drag gestures, otherwise these gestures will be ignored.
+ *
+ * @param dragDetect the new drag detect state
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
+ * </ul>
+ */
+ @Override
+ public boolean setFocus() {
+ this.checkWidget();
+ return this.text.setFocus();
+ }
+
+ /**
+ * Forces the receiver to have the <em>keyboard focus</em>, causing all keyboard events to be delivered to it.
+ *
+ * @return <code>true</code> if the control got focus, and <code>false</code> if it was unable to.
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
+ * </ul>
+ *
+ * @see #setFocus
+ */
+ @Override
+ public boolean forceFocus() {
+ this.checkWidget();
+ return this.text.forceFocus();
+ }
+
+ /**
+ * Sets the receiver's background color to the color specified by the argument, or to the default system color for the control if the argument is null.
+ * <p>
+ * Note: This operation is a hint and may be overridden by the platform. For example, on Windows the background of a Button cannot be changed.
+ * </p>
+ *
+ * @param color the new color (or null)
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_INVALID_ARGUMENT - if the argument has been disposed</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
+ * </ul>
+ */
+ @Override
+ public void setBackground(final Color color) {
+ super.setBackground(color);
+ this.leftButton.setBackground(color);
+ this.rightButton.setBackground(color);
+ this.text.setBackground(color);
+ }
+
+ /**
+ * Sets the receiver's background image to the image specified by the argument, or to the default system color for the control if the argument is null. The background image is tiled to fill the available space.
+ * <p>
+ * Note: This operation is a hint and may be overridden by the platform. For example, on Windows the background of a Button cannot be changed.
+ * </p>
+ *
+ * @param image the new image (or null)
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_INVALID_ARGUMENT - if the argument has been disposed</li>
+ * <li>ERROR_INVALID_ARGUMENT - if the argument is not a bitmap</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
+ * </ul>
+ */
+ @Override
+ public void setBackgroundImage(final Image image) {
+ super.setBackgroundImage(image);
+ this.leftButton.setBackgroundImage(image);
+ this.rightButton.setBackgroundImage(image);
+ this.text.setBackgroundImage(image);
+
+ }
+
+ /**
+ * Sets the receiver's cursor to the cursor specified by the argument, or to the default cursor for that kind of control if the argument is null.
+ * <p>
+ * When the mouse pointer passes over a control its appearance is changed to match the control's cursor.
+ * </p>
+ *
+ * @param cursor the new cursor (or null)
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_INVALID_ARGUMENT - if the argument has been disposed</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
+ * </ul>
+ */
+ @Override
+ public void setCursor(final Cursor cursor) {
+ super.setCursor(cursor);
+ this.leftButton.setCursor(cursor);
+ this.rightButton.setCursor(cursor);
+ this.text.setCursor(cursor);
+
+ }
+
+ /**
+ * Enables the receiver if the argument is <code>true</code>, and disables it otherwise. A disabled control is typically not selectable from the user interface and draws with an inactive or "grayed" look.
+ *
+ * @param enabled the new enabled state
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
+ * </ul>
+ */
+ @Override
+ public void setEnabled(final boolean enabled) {
+ super.setEnabled(enabled);
+ this.leftButton.setEnabled(enabled);
+ this.rightButton.setEnabled(enabled);
+ this.text.setEnabled(enabled);
+
+ }
+
+ /**
+ * Sets the font that the receiver will use to paint textual information to the font specified by the argument, or to the default font for that kind of control if the argument is null.
+ *
+ * @param font the new font (or null)
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_INVALID_ARGUMENT - if the argument has been disposed</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
+ * </ul>
+ */
+ @Override
+ public void setFont(final Font font) {
+ super.setFont(font);
+ this.text.setFont(font);
+ }
+
+ /**
+ * Sets the receiver's foreground color to the color specified by the argument, or to the default system color for the control if the argument is null.
+ * <p>
+ * Note: This operation is a hint and may be overridden by the platform.
+ * </p>
+ *
+ * @param color the new color (or null)
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_INVALID_ARGUMENT - if the argument has been disposed</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
+ * </ul>
+ */
+ @Override
+ public void setForeground(final Color color) {
+ super.setForeground(color);
+ this.leftButton.setForeground(color);
+ this.rightButton.setForeground(color);
+ this.text.setForeground(color);
+
+ }
+
+ /**
+ * Sets the receiver's pop up menu to the argument. All controls may optionally have a pop up menu that is displayed when the user requests one for the control. The sequence of key strokes, button presses and/or button releases that are used to request a pop up menu is platform specific.
+ * <p>
+ * Note: Disposing of a control that has a pop up menu will dispose of the menu. To avoid this behavior, set the menu to null before the control is disposed.
+ * </p>
+ *
+ * @param menu the new pop up menu
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_MENU_NOT_POP_UP - the menu is not a pop up menu</li>
+ * <li>ERROR_INVALID_PARENT - if the menu is not in the same widget tree</li>
+ * <li>ERROR_INVALID_ARGUMENT - if the menu has been disposed</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
+ * </ul>
+ */
+ @Override
+ public void setMenu(final Menu menu) {
+ super.setMenu(menu);
+ this.leftButton.setMenu(menu);
+ this.rightButton.setMenu(menu);
+ this.text.setMenu(menu);
+ }
+
+ /**
+ * Sets the receiver's tool tip text to the argument, which may be null indicating that the default tool tip for the control will be shown. For a control that has a default tool tip, such as the Tree control on Windows, setting the tool tip text to an empty string replaces the default, causing no tool tip text to be shown.
+ * <p>
+ * The mnemonic indicator (character '&amp;') is not displayed in a tool tip. To display a single '&amp;' in the tool tip, the character '&amp;' can be escaped by doubling it in the string.
+ * </p>
+ *
+ * @param string the new tool tip text (or null)
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
+ * </ul>
+ */
+ @Override
+ public void setToolTipText(final String tooltipText) {
+ super.setToolTipText(tooltipText);
+ this.leftButton.setToolTipText(tooltipText);
+ this.rightButton.setToolTipText(tooltipText);
+ this.text.setToolTipText(tooltipText);
+ }
+
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/imageSelector/ISItem.java b/org.tizen.common.externals/src/org/mihalis/opal/imageSelector/ISItem.java
new file mode 100644
index 000000000..fc9109905
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/imageSelector/ISItem.java
@@ -0,0 +1,114 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON
+ * 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:
+ * Laurent CARON (laurent.caron at gmail dot com) - Initial implementation and API
+ *******************************************************************************/
+package org.mihalis.opal.imageSelector;
+
+import org.eclipse.swt.graphics.Point;
+import org.mihalis.opal.OpalItem;
+import org.mihalis.opal.utils.SWTGraphicUtil;
+
+/**
+ * Instances of this class represents items manipulated by the ImageSelector
+ * widget
+ */
+public class ISItem extends OpalItem implements Comparable<ISItem> {
+
+ private double zPosition;
+ private Point upperLeftCorner;
+ private Point lowerRightCorner;
+
+ /**
+ * Constructor
+ *
+ * @param fileName file name of the image that will be displayed
+ */
+ public ISItem(final String fileName) {
+ setImage(SWTGraphicUtil.createImage(fileName));
+ }
+
+ /**
+ * Constructor
+ *
+ * @param title the title of the image
+ * @param fileName file name of the image that will be displayed
+ */
+ public ISItem(final String title, final String fileName) {
+ setImage(SWTGraphicUtil.createImage(fileName));
+ setText(title);
+ }
+
+ /**
+ * @return the zPosition
+ */
+ double getzPosition() {
+ return this.zPosition;
+ }
+
+ /**
+ * @param zPosition the zPosition to set
+ */
+ ISItem setzPosition(final double zPosition) {
+ this.zPosition = zPosition;
+ return this;
+ }
+
+ /**
+ * @return the upperLeftCorner
+ */
+ Point getUpperLeftCorner() {
+ return this.upperLeftCorner;
+ }
+
+ /**
+ * @param x the upperLeftCorner.x to set
+ * @param y the upperLeftCorner.y to set
+ */
+ void setUpperLeftCorner(final int x, final int y) {
+ this.upperLeftCorner = new Point(x, y);
+ }
+
+ /**
+ * @return the lowerRightCorner
+ */
+ Point getLowerRightCorner() {
+ return this.lowerRightCorner;
+ }
+
+ /**
+ * @param x the lowerRightCorner.x to set
+ * @param y the lowerRightCorner.y to set
+ */
+ void setLowerRightCorner(final int x, final int y) {
+ this.lowerRightCorner = new Point(x, y);
+ }
+
+ void resetCornerToNull() {
+ this.upperLeftCorner = null;
+ this.lowerRightCorner = null;
+
+ }
+
+ /**
+ * @see java.lang.Object#toString()
+ */
+ @Override
+ public String toString() {
+ return "ISItem [getText()=" + this.getText() + "]";
+ }
+
+ /**
+ * @see java.lang.Comparable#compareTo(java.lang.Object)
+ */
+ @Override
+ public int compareTo(final ISItem o) {
+ return new Double(Math.abs(this.zPosition)).compareTo(Math.abs(o.getzPosition())) * -1;
+ }
+
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/imageSelector/ImageSelector.java b/org.tizen.common.externals/src/org/mihalis/opal/imageSelector/ImageSelector.java
new file mode 100755
index 000000000..2bab62d96
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/imageSelector/ImageSelector.java
@@ -0,0 +1,615 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON
+ * 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:
+ * Laurent CARON (laurent.caron at gmail dot com) - Initial implementation and API
+ * Romain Guy - Original Swing Implementation (http://www.curious-creature.org/2005/07/09/a-music-shelf-in-java2d/)
+ *******************************************************************************/
+package org.mihalis.opal.imageSelector;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.SWTException;
+import org.eclipse.swt.events.DisposeEvent;
+import org.eclipse.swt.events.DisposeListener;
+import org.eclipse.swt.events.KeyAdapter;
+import org.eclipse.swt.events.KeyEvent;
+import org.eclipse.swt.events.MouseAdapter;
+import org.eclipse.swt.events.MouseEvent;
+import org.eclipse.swt.events.MouseMoveListener;
+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.Point;
+import org.eclipse.swt.graphics.Rectangle;
+import org.eclipse.swt.widgets.Canvas;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Event;
+import org.eclipse.swt.widgets.Listener;
+import org.mihalis.opal.utils.SWTGraphicUtil;
+
+/**
+ * Instances of this class are controls that allow the user to select images.
+ * <dl>
+ * <dt><b>Styles:</b></dt>
+ * <dd>(none)</dd>
+ * <dt><b>Events:</b></dt>
+ * <dd>(none)</dd>
+ * </dl>
+ */
+public class ImageSelector extends Canvas {
+ private List<ISItem> items;
+ private List<ISItem> originalItems;
+ private Font font;
+ private static final int DEFAULT_WIDTH = 148;
+ private int maxItemWidth = DEFAULT_WIDTH;
+ private int index = -1;
+ private double sigma;
+ private double rho;
+ private double expMultiplier;
+ private double expMember;
+ private float spacing = 0.4f;
+ private Color gradientStart;
+ private Color gradientEnd;
+ private double animationStep = -1d;
+ private static final int TIMER_INTERVAL = 50;
+ private int pageIncrement = 5;
+
+ /**
+ * Constructs a new instance of this class given its parent and a style
+ * value describing its behavior and appearance.
+ * <p>
+ * The style value is either one of the style constants defined in class
+ * <code>SWT</code> which is applicable to instances of this class, or must
+ * be built by <em>bitwise OR</em>'ing together (that is, using the
+ * <code>int</code> "|" operator) two or more of those <code>SWT</code>
+ * style constants. The class description lists the style constants that are
+ * applicable to the class. Style bits are also inherited from superclasses.
+ * </p>
+ *
+ * @param parent a composite control which will be the parent of the new
+ * instance (cannot be null)
+ * @param style the style of control to construct
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the parent is null</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the parent</li>
+ * </ul>
+ *
+ */
+ public ImageSelector(final Composite parent, final int style) {
+ super(parent, style | SWT.NO_BACKGROUND | SWT.DOUBLE_BUFFERED);
+ this.font = new Font(this.getDisplay(), "Lucida Sans", 24, SWT.NONE);
+
+ this.addDisposeListener(new DisposeListener() {
+
+ @Override
+ public void widgetDisposed(final DisposeEvent e) {
+ SWTGraphicUtil.dispose(ImageSelector.this.font);
+ SWTGraphicUtil.dispose(ImageSelector.this.gradientStart);
+ SWTGraphicUtil.dispose(ImageSelector.this.gradientEnd);
+ }
+
+ });
+
+ addPaintListener(new PaintListener() {
+ @Override
+ public void paintControl(final PaintEvent e) {
+ ImageSelector.this.paintControl(e);
+ }
+
+ });
+
+ addKeyListener();
+ addMouseListeners();
+
+ setSigma(0.5);
+ this.gradientStart = new Color(getDisplay(), 0, 0, 0);
+ this.gradientEnd = new Color(getDisplay(), 110, 110, 110);
+ }
+
+ /**
+ * Set the sigma value for the gaussian curve
+ *
+ * @param sigma new sigma parameter
+ */
+ public void setSigma(final double sigma) {
+ this.sigma = sigma;
+ this.rho = 1.0;
+ computeEquationParts();
+ this.rho = computeModifierUnbounded(0.0);
+ computeEquationParts();
+ redraw();
+ }
+
+ /**
+ * Computer both members of the equation
+ */
+ private void computeEquationParts() {
+ this.expMultiplier = Math.sqrt(2.0 * Math.PI) / this.sigma / this.rho;
+ this.expMember = 4.0 * this.sigma * this.sigma;
+ }
+
+ /**
+ * Compute the value of the modifier. The value is bounded between -1 and +1
+ *
+ * @param x input value
+ * @return the value of the modifier between -1 and +1
+ */
+ private double computeModifierBounded(final double x) {
+ double result = computeModifierUnbounded(x);
+ if (result > 1.0) {
+ result = 1.0;
+ } else if (result < -1.0) {
+ result = -1.0;
+ }
+ return result;
+ }
+
+ /**
+ * Compute the value of the modifier
+ *
+ * @param x input value
+ * @return the value of the function
+ */
+ private double computeModifierUnbounded(final double x) {
+ return this.expMultiplier * Math.exp(-x * x / this.expMember);
+ }
+
+ /**
+ * Draw the widget
+ *
+ * @param e the paintEvent
+ */
+ private void paintControl(final PaintEvent e) {
+
+ // Create the image to fill the canvas
+ final Image image = new Image(getDisplay(), getClientArea());
+
+ // Set up the offscreen gc
+ final GC gc = new GC(image);
+
+ // Draw gradient
+ drawBackground(gc);
+
+ // Draw the items
+ drawItems(gc);
+
+ // Draw the title
+ if (this.animationStep < 0d) {
+ drawTitle(gc);
+ }
+
+ // Draw the offscreen buffer to the screen
+ e.gc.drawImage(image, 0, 0);
+
+ // Clean up
+ image.dispose();
+ gc.dispose();
+
+ }
+
+ /**
+ * Draw the background
+ *
+ * @param gc graphical context
+ */
+ private void drawBackground(final GC gc) {
+ final Rectangle rect = getClientArea();
+
+ gc.setForeground(this.gradientStart);
+ gc.setBackground(this.gradientEnd);
+ gc.fillGradientRectangle(rect.x, rect.y, rect.width, rect.height / 2, true);
+
+ gc.setForeground(this.gradientEnd);
+ gc.setBackground(this.gradientStart);
+ gc.fillGradientRectangle(rect.x, rect.height / 2, rect.width, rect.height / 2, true);
+ }
+
+ /**
+ * Draw the items
+ *
+ * @param gc graphical context
+ */
+ private void drawItems(final GC gc) {
+
+ if (this.animationStep < 0d) {
+ this.items.clear();
+ this.items.addAll(this.originalItems);
+ for (int i = 0; i < this.items.size(); i++) {
+ final ISItem item = this.items.get(i);
+ item.setzPosition((i - this.index) * this.spacing);
+ }
+
+ Collections.sort(this.items);
+ }
+
+ for (final ISItem item : this.items) {
+ drawItem(gc, item);
+ }
+ }
+
+ /**
+ * Draw a given item
+ *
+ * @param gc graphical context
+ * @param item item to draw
+ */
+ private void drawItem(final GC gc, final ISItem item) {
+
+ final int size = computeSize(item);
+ final int centerX = computeZPosition(item);
+ final int centerY = this.getClientArea().height / 2;
+
+ if (size <= 0 || centerX < 0 || centerX > getBounds().width) {
+ item.resetCornerToNull();
+ return;
+ }
+
+ final int alpha = computeAlpha(item);
+
+ final Image newImage = SWTGraphicUtil.createReflectedResizedImage(item.getImage(), size, size);
+ gc.setAlpha(alpha);
+
+ final int x = centerX - newImage.getBounds().width / 2;
+ final int y = centerY - newImage.getBounds().height / 2;
+
+ gc.drawImage(newImage, x, y);
+
+ item.setUpperLeftCorner(x, y);
+ item.setLowerRightCorner(x + newImage.getBounds().width, (int) (y + newImage.getBounds().height / 1.5));
+
+ newImage.dispose();
+ }
+
+ /**
+ * Compute the z position for a given item
+ *
+ * @param item item
+ * @return the z position of the item
+ */
+ private int computeZPosition(final ISItem item) {
+ final int totalWidth = this.getClientArea().width / 2;
+ final int centerX = this.getClientArea().width / 2;
+ return (int) (centerX + item.getzPosition() * totalWidth);
+ }
+
+ /**
+ * Compute size for a given item
+ *
+ * @param item item
+ * @return the size of the item
+ */
+ private int computeSize(final ISItem item) {
+ return (int) (computeModifierBounded(item.getzPosition()) * this.maxItemWidth);
+ }
+
+ /**
+ * Compute the alpha value of a given item
+ *
+ * @param item item
+ * @return the alpha value of the item
+ */
+ private int computeAlpha(final ISItem item) {
+ return (int) (255 - 150 * Math.abs(item.getzPosition()));
+ }
+
+ /**
+ * Draw the title under the selected item
+ *
+ * @param gc graphical context
+ */
+ private void drawTitle(final GC gc) {
+ final String title = this.originalItems.get(this.index).getText();
+ if (title == null || title.trim().equals("")) {
+ return;
+ }
+ gc.setFont(getFont());
+ final Point textSize = gc.stringExtent(title);
+
+ gc.setAntialias(SWT.ON);
+ gc.setFont(getFont());
+ gc.setForeground(getDisplay().getSystemColor(SWT.COLOR_WHITE));
+ gc.setAlpha(255);
+
+ final int centerX = this.getClientArea().width / 2;
+ final int centerY = (this.getClientArea().height + this.maxItemWidth) / 2;
+
+ gc.drawString(title, centerX - textSize.x / 2, (centerY - textSize.y / 2), true);
+
+ }
+
+ /**
+ * Add the key listener
+ */
+ private void addKeyListener() {
+ this.addKeyListener(new KeyAdapter() {
+
+ /**
+ * @see org.eclipse.swt.events.KeyAdapter#keyReleased(org.eclipse.swt.events.KeyEvent)
+ */
+ @Override
+ public void keyReleased(final KeyEvent e) {
+ switch (e.keyCode) {
+ case SWT.ARROW_LEFT:
+ case SWT.ARROW_UP:
+ scrollAndAnimateBy(-1);
+ break;
+ case SWT.ARROW_RIGHT:
+ case SWT.ARROW_DOWN:
+ scrollAndAnimateBy(1);
+ break;
+ case SWT.HOME:
+ scrollBy(-1 * ImageSelector.this.index);
+ break;
+ case SWT.END:
+ scrollBy(ImageSelector.this.index);
+ break;
+ case SWT.PAGE_UP:
+ scrollBy(-1 * ImageSelector.this.pageIncrement);
+ break;
+ case SWT.PAGE_DOWN:
+ scrollBy(ImageSelector.this.pageIncrement);
+ break;
+ default:
+ break;
+ }
+ }
+
+ });
+ }
+
+ /**
+ * Scroll the selected item
+ *
+ * @param increment increment value
+ */
+ private void scrollBy(final int increment) {
+ this.index += increment;
+ if (this.index < 0) {
+ this.index = 0;
+ }
+
+ if (this.index >= this.items.size()) {
+ this.index = this.items.size() - 1;
+ }
+ redraw();
+ }
+
+ /**
+ * Scroll the selected item with an animation
+ *
+ * @param increment increment value
+ */
+ private void scrollAndAnimateBy(final int increment) {
+ if (this.index == 0 && increment < 0 || this.index == this.items.size() - 1 && increment > 0) {
+ return;
+ }
+
+ final double step = Math.abs(increment) / (300d / TIMER_INTERVAL);
+ ImageSelector.this.animationStep = step;
+ setCursor(getDisplay().getSystemCursor(SWT.CURSOR_WAIT));
+
+ getDisplay().syncExec(new Runnable() {
+
+ @Override
+ public void run() {
+
+ ImageSelector.this.items.clear();
+ ImageSelector.this.items.addAll(ImageSelector.this.originalItems);
+ for (int i = 0; i < ImageSelector.this.items.size(); i++) {
+ final ISItem item = ImageSelector.this.items.get(i);
+ item.setzPosition((i - ImageSelector.this.index + ImageSelector.this.animationStep * (increment > 0 ? -1d : 1d)) * ImageSelector.this.spacing);
+ }
+ Collections.sort(ImageSelector.this.items);
+ if (!isDisposed()) {
+ redraw();
+ }
+
+ ImageSelector.this.animationStep += step;
+ if (ImageSelector.this.animationStep >= 1d) {
+ ImageSelector.this.animationStep = -1d;
+ ImageSelector.this.index += increment;
+ setCursor(getDisplay().getSystemCursor(SWT.CURSOR_ARROW));
+ } else {
+ if (!isDisposed()) {
+ getDisplay().timerExec(TIMER_INTERVAL, this);
+ }
+ }
+
+ }
+ });
+
+ }
+
+ /**
+ * Add mouse listeners
+ */
+ private void addMouseListeners() {
+ addMouseMoveListener(new MouseMoveListener() {
+
+ @Override
+ public void mouseMove(final MouseEvent e) {
+ for (final ISItem item : ImageSelector.this.items) {
+ if (item.getUpperLeftCorner() != null && item.getLowerRightCorner() != null && e.x >= item.getUpperLeftCorner().x && e.x <= item.getLowerRightCorner().x && e.y >= item.getUpperLeftCorner().y && e.y <= item.getLowerRightCorner().y) {
+ setCursor(getDisplay().getSystemCursor(SWT.CURSOR_HAND));
+ return;
+ }
+ }
+ setCursor(getDisplay().getSystemCursor(SWT.CURSOR_ARROW));
+ }
+ });
+
+ addMouseListener(new MouseAdapter() {
+
+ /**
+ * @see org.eclipse.swt.events.MouseAdapter#mouseUp(org.eclipse.swt.events.MouseEvent)
+ */
+ @Override
+ public void mouseUp(final MouseEvent e) {
+ for (final ISItem item : ImageSelector.this.items) {
+ if (item.getUpperLeftCorner() != null && item.getLowerRightCorner() != null && e.x >= item.getUpperLeftCorner().x && e.x <= item.getLowerRightCorner().x && e.y >= item.getUpperLeftCorner().y && e.y <= item.getLowerRightCorner().y) {
+ scrollAndAnimateBy(ImageSelector.this.originalItems.indexOf(item) - ImageSelector.this.index);
+ return;
+ }
+ }
+ }
+ });
+
+ addListener(SWT.MouseWheel, new Listener() {
+
+ @Override
+ public void handleEvent(final Event event) {
+ scrollBy(-1 * event.count);
+ }
+ });
+
+ }
+
+ /**
+ * @return the items displayed by this widget
+ */
+ public List<ISItem> getItems() {
+ return this.originalItems;
+ }
+
+ /**
+ * @param items the items that are displayed in this widget to set
+ */
+ public void setItems(final List<ISItem> items) {
+ this.items = new ArrayList<ISItem>(items);
+ this.originalItems = items;
+ this.index = this.items.size() / 2;
+ redraw();
+ }
+
+ /**
+ * @return the font used for the title
+ */
+ @Override
+ public Font getFont() {
+ return this.font;
+ }
+
+ /**
+ * @param font the font used for the title to set
+ */
+ @Override
+ public void setFont(final Font font) {
+ SWTGraphicUtil.dispose(this.font);
+ this.font = font;
+ redraw();
+ }
+
+ /**
+ * @return the index of the selected image
+ */
+ public int getIndex() {
+ return this.index;
+ }
+
+ /**
+ * @param index the index of the selected image to set
+ */
+ public void setIndex(final int index) {
+ this.index = index;
+ redraw();
+ }
+
+ /**
+ * @return the maximum items width
+ */
+ public int getMaxItemWidth() {
+ return this.maxItemWidth;
+ }
+
+ /**
+ * @param maxItemWidth the the maximum items width to set
+ */
+ public void setMaxItemWidth(final int maxItemWidth) {
+ this.maxItemWidth = maxItemWidth;
+ redraw();
+ }
+
+ /**
+ * @return the sigma value
+ */
+ public double getSigma() {
+ return this.sigma;
+ }
+
+ /**
+ * @return the spacing between 2 items
+ */
+ public float getSpacing() {
+ return this.spacing;
+ }
+
+ /**
+ * @param spacing the the spacing between 2 items to set
+ */
+ public void setSpacing(final float spacing) {
+ this.spacing = spacing;
+ redraw();
+ }
+
+ /**
+ * @return the gradient start color
+ */
+ public Color getGradientStart() {
+ return this.gradientStart;
+ }
+
+ /**
+ * @param gradientStart the the gradient start color to set
+ */
+ public void setGradientStart(final Color gradientStart) {
+ SWTGraphicUtil.dispose(this.gradientStart);
+ this.gradientStart = gradientStart;
+ redraw();
+ }
+
+ /**
+ * @return the the gradient end color
+ */
+ public Color getGradientEnd() {
+ return this.gradientEnd;
+ }
+
+ /**
+ * @param gradientEnd the the gradient end color to set
+ */
+ public void setGradientEnd(final Color gradientEnd) {
+ SWTGraphicUtil.dispose(this.gradientEnd);
+ this.gradientEnd = gradientEnd;
+ redraw();
+ }
+
+ /**
+ * @return the page increment when the user uses PgUp and PgDown
+ */
+ public int getPageIncrement() {
+ return this.pageIncrement;
+ }
+
+ /**
+ * @param pageIncrement the page increment to set
+ */
+ public void setPageIncrement(final int pageIncrement) {
+ this.pageIncrement = pageIncrement;
+ }
+
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/infinitePanel/InfiniteProgressPanel.java b/org.tizen.common.externals/src/org/mihalis/opal/infinitePanel/InfiniteProgressPanel.java
new file mode 100644
index 000000000..e7a62dea3
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/infinitePanel/InfiniteProgressPanel.java
@@ -0,0 +1,604 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON
+ * 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:
+ * Laurent CARON (laurent.caron at gmail dot com) - initial API and implementation,
+ * inspired by Romain Guy's work (http://www.curious-creature.org)
+ *******************************************************************************/
+package org.mihalis.opal.infinitePanel;
+
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.SWTException;
+import org.eclipse.swt.events.DisposeEvent;
+import org.eclipse.swt.events.DisposeListener;
+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.Point;
+import org.eclipse.swt.graphics.Rectangle;
+import org.eclipse.swt.layout.FillLayout;
+import org.eclipse.swt.widgets.Canvas;
+import org.eclipse.swt.widgets.Event;
+import org.eclipse.swt.widgets.Listener;
+import org.eclipse.swt.widgets.Shell;
+import org.mihalis.opal.utils.SWTGraphicUtil;
+
+/**
+ * Instances of this class are controls located on the top of a shell. They
+ * display a ticker that indicates to the user that a long task operation is
+ * running
+ */
+public class InfiniteProgressPanel {
+
+ private static final String INFINITE_PANEL_KEY = "org.mihalis.opal.InfinitePanel.InfiniteProgressPanel";
+ private static final int NUMBER_OF_STEPS = 10;
+
+ private final Shell parent;
+ private Shell panel;
+ private String text;
+ private Font textFont;
+ private Color textColor;
+ private float fps;
+ private int barsCount;
+ private int lineWidth;
+ private int alpha;
+ private Color defaultColor;
+ private Color selectionColor;
+ private int currentPosition;
+ private Thread animatorThread;
+ private Canvas canvas;
+ private boolean fadeIn;
+ private boolean fadeOut;
+ private int fadeOutCounter;
+
+ /**
+ * Constructs a new instance of this class given its parent.
+ *
+ * @param shell a shell that will be the parent of the new instance (cannot
+ * be null)
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the parent is null</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the parent has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the parent</li>
+ * </ul>
+ */
+ private InfiniteProgressPanel(final Shell shell) {
+ if (shell == null) {
+ SWT.error(SWT.ERROR_NULL_ARGUMENT);
+ }
+
+ if (shell.isDisposed()) {
+ SWT.error(SWT.ERROR_INVALID_ARGUMENT);
+ }
+
+ this.parent = shell;
+ if (shell.getData(INFINITE_PANEL_KEY) != null) {
+ throw new IllegalArgumentException("This shell has already an infinite panel attached on it !");
+ }
+
+ this.text = null;
+ this.textFont = null;
+ this.barsCount = 14;
+ this.fps = 15.0f;
+ this.lineWidth = 16;
+ this.alpha = 200;
+ this.fadeIn = false;
+ this.fadeOut = false;
+ this.fadeOutCounter = 0;
+ shell.setData(INFINITE_PANEL_KEY, this);
+
+ this.parent.addListener(SWT.Activate, new Listener() {
+
+ @Override
+ public void handleEvent(final Event e) {
+ if (InfiniteProgressPanel.this.panel != null && //
+ !InfiniteProgressPanel.this.panel.isDisposed() && !InfiniteProgressPanel.this.panel.isVisible()) {
+ InfiniteProgressPanel.this.panel.setVisible(true);
+ InfiniteProgressPanel.this.panel.setActive();
+ }
+ }
+ });
+ }
+
+ /**
+ * Starts the ticker
+ */
+ public void start() {
+ if (this.parent.isDisposed()) {
+ SWT.error(SWT.ERROR_WIDGET_DISPOSED);
+ }
+
+ this.panel = new Shell(this.parent, SWT.APPLICATION_MODAL | SWT.NO_TRIM | SWT.ON_TOP);
+ this.panel.setLayout(new FillLayout());
+ this.panel.setAlpha(0);
+
+ this.panel.addListener(SWT.KeyUp, new Listener() {
+
+ @Override
+ public void handleEvent(final Event event) {
+ event.doit = false;
+ }
+ });
+
+ if (this.defaultColor == null) {
+ this.defaultColor = new Color(this.parent.getDisplay(), 200, 200, 200);
+ }
+
+ if (this.selectionColor == null) {
+ this.selectionColor = new Color(this.parent.getDisplay(), 0, 0, 0);
+ }
+
+ this.parent.addDisposeListener(new DisposeListener() {
+
+ @Override
+ public void widgetDisposed(final DisposeEvent e) {
+ SWTGraphicUtil.dispose(InfiniteProgressPanel.this.defaultColor);
+ SWTGraphicUtil.dispose(InfiniteProgressPanel.this.selectionColor);
+ }
+ });
+
+ this.currentPosition = 0;
+ this.fadeIn = true;
+ this.fadeOut = false;
+ this.fadeOutCounter = 0;
+
+ this.canvas = new Canvas(this.panel, SWT.NO_BACKGROUND | SWT.DOUBLE_BUFFERED);
+ this.canvas.addPaintListener(new PaintListener() {
+
+ @Override
+ public void paintControl(final PaintEvent e) {
+ InfiniteProgressPanel.this.paintCanvas(e);
+ }
+ });
+
+ this.panel.setBounds(this.panel.getDisplay().map(this.parent, null, this.parent.getClientArea()));
+ this.panel.open();
+
+ this.animatorThread = new Thread() {
+
+ /**
+ * @see java.lang.Thread#run()
+ */
+ @Override
+ public void run() {
+ while (!Thread.interrupted()) {
+ InfiniteProgressPanel.this.currentPosition = (InfiniteProgressPanel.this.currentPosition + 1) % InfiniteProgressPanel.this.barsCount;
+ if (InfiniteProgressPanel.this.fadeOut) {
+ InfiniteProgressPanel.this.fadeOutCounter++;
+ }
+ InfiniteProgressPanel.this.panel.getDisplay().asyncExec(new Runnable() {
+
+ @Override
+ public void run() {
+ InfiniteProgressPanel.this.canvas.redraw();
+ }
+ });
+
+ try {
+ sleep(InfiniteProgressPanel.this.fadeOut ? 20 : (long) (1000 / InfiniteProgressPanel.this.fps));
+ } catch (final InterruptedException e) {
+ break;
+ }
+ }
+ }
+ };
+ this.animatorThread.start();
+
+ this.panel.addListener(SWT.Deactivate, new Listener() {
+
+ @Override
+ public void handleEvent(final Event arg0) {
+ InfiniteProgressPanel.this.panel.setVisible(false);
+ }
+ });
+
+ }
+
+ /**
+ * Paint the canvas that holds the ticker
+ *
+ * @param e
+ */
+ private void paintCanvas(final PaintEvent e) {
+ // Paint the panel
+ final Rectangle clientArea = ((Canvas) e.widget).getClientArea();
+ final GC gc = e.gc;
+
+ this.handleFadeIn();
+ this.handleFadeOut();
+ this.drawBackground(clientArea, gc);
+ this.drawTicker(clientArea, gc);
+ this.drawText(clientArea, gc);
+
+ }
+
+ /**
+ * Handle the fade in effect of the panel
+ */
+ private void handleFadeIn() {
+ if (this.fadeIn) {
+ if (this.currentPosition == NUMBER_OF_STEPS) {
+ this.fadeIn = false;
+ this.panel.setAlpha(this.alpha);
+ } else {
+ this.panel.setAlpha(this.currentPosition * this.alpha / NUMBER_OF_STEPS);
+ }
+ }
+ }
+
+ /**
+ * Handle the fade out effect of the panel
+ */
+ private void handleFadeOut() {
+ if (this.fadeOut) {
+ if (this.fadeOutCounter == NUMBER_OF_STEPS) {
+ if (this.animatorThread != null) {
+ this.animatorThread.interrupt();
+ this.animatorThread = null;
+ }
+ if (!this.panel.isDisposed()) {
+ this.panel.getDisplay().asyncExec(new Runnable() {
+
+ @Override
+ public void run() {
+ if (!InfiniteProgressPanel.this.panel.isDisposed()) {
+ InfiniteProgressPanel.this.panel.dispose();
+ }
+ }
+ });
+ }
+ }
+ this.panel.setAlpha(255 - this.fadeOutCounter * this.alpha / NUMBER_OF_STEPS);
+ }
+ }
+
+ /**
+ * Draw the background of the panel
+ *
+ * @param gc GC on with the background is drawn
+ * @param clientArea client area of the canvas
+ */
+ private void drawBackground(final Rectangle clientArea, final GC gc) {
+ // Draw the background
+ gc.setBackground(this.panel.getDisplay().getSystemColor(SWT.COLOR_WHITE));
+ gc.fillRectangle(clientArea);
+ }
+
+ /**
+ * Draw the ticker
+ *
+ * @param gc GC on with the ticker is drawn
+ * @param clientArea client area of the canvas
+ */
+ private void drawTicker(final Rectangle clientArea, final GC gc) {
+ // Draw the ticker
+ final int centerX = clientArea.width / 2;
+ final int centerY = clientArea.height / 2;
+ final int maxRay = (int) (Math.min(clientArea.width, clientArea.height) * 0.6f) / 2;
+ final int minRay = (int) (maxRay * 0.5f);
+
+ double angle = Math.PI / 2;
+
+ gc.setLineCap(SWT.CAP_ROUND);
+ gc.setLineWidth(this.lineWidth);
+ gc.setAntialias(SWT.ON);
+
+ for (int i = 0; i < this.barsCount; i++) {
+ if (i == this.currentPosition) {
+ gc.setForeground(this.selectionColor);
+ } else {
+ gc.setForeground(this.defaultColor);
+ }
+ gc.drawLine((int) (centerX + minRay * Math.cos(angle)), //
+ (int) (centerY - minRay * Math.sin(angle)), //
+ (int) (centerX + maxRay * Math.cos(angle)), //
+ (int) (centerY - maxRay * Math.sin(angle)));
+ angle -= 2 * Math.PI / this.barsCount;
+ }
+ }
+
+ /**
+ * Draw the text over the ticker
+ *
+ * @param gc GC on with the text is drawn
+ * @param clientArea client area of the canvas
+ */
+ private void drawText(final Rectangle clientArea, final GC gc) {
+ if (this.text == null || "".equals(this.text)) {
+ return;
+ }
+
+ final Font font;
+ if (this.textFont == null) {
+ font = this.parent.getDisplay().getSystemFont();
+ } else {
+ font = this.textFont;
+ }
+
+ final Color color;
+ if (this.textColor == null) {
+ color = this.parent.getDisplay().getSystemColor(SWT.COLOR_BLACK);
+ } else {
+ color = this.textColor;
+ }
+
+ gc.setForeground(color);
+ gc.setFont(font);
+ gc.setTextAntialias(SWT.ON);
+ final Point textSize = gc.textExtent(this.text, SWT.DRAW_TRANSPARENT);
+ final int textWidth = textSize.x;
+ final int textHeight = textSize.y;
+
+ gc.drawString(this.text, (clientArea.width - textWidth) / 2, (clientArea.height - textHeight) / 2, true);
+
+ }
+
+ /**
+ * Stop the animation and dispose the panel
+ */
+ public void stop() {
+ if (this.panel.isDisposed() || this.panel.getDisplay().isDisposed()) {
+ return;
+ }
+ this.fadeOut = true;
+ }
+
+ /**
+ * Returns the infinite progress panel for the shell. If no infinite panel
+ * has been declared, returns null.
+ *
+ * @param shell the shell for which we are trying to get the associated
+ * progess panel
+ * @return the progress panel associated to shell, or null if there is no
+ * progress panel
+ */
+ public static InfiniteProgressPanel getInfiniteProgressPanelFor(final Shell shell) {
+ if (shell == null) {
+ SWT.error(SWT.ERROR_NULL_ARGUMENT);
+ }
+
+ if (shell.isDisposed()) {
+ SWT.error(SWT.ERROR_WIDGET_DISPOSED);
+ }
+
+ if (shell.getDisplay().isDisposed()) {
+ SWT.error(SWT.ERROR_DEVICE_DISPOSED);
+ }
+
+ final InfiniteProgressPanel[] temp = new InfiniteProgressPanel[1];
+ shell.getDisplay().syncExec(new Runnable() {
+
+ @Override
+ public void run() {
+ final Object data = shell.getData(INFINITE_PANEL_KEY);
+ if (data != null && data instanceof InfiniteProgressPanel) {
+ temp[0] = (InfiniteProgressPanel) data;
+ }
+ }
+ });
+
+ if (temp[0] == null) {
+ return new InfiniteProgressPanel(shell);
+ } else {
+ return temp[0];
+ }
+ }
+
+ /**
+ * Check if a shell has an associated progress panel
+ *
+ * @param shell the shell
+ * @return <code>true</code> if the shell has an associated panel,
+ * <code>false</code> otherwise
+ */
+ public static boolean hasInfiniteProgressPanel(final Shell shell) {
+ return getInfiniteProgressPanelFor(shell) != null;
+ }
+
+ // ------------------------------------------------- Getters and Setters
+
+ /**
+ * @return the alpha value of the panel
+ */
+ public int getAlpha() {
+ return this.alpha;
+ }
+
+ /**
+ * @param alpha the alpha value of the panel, between 0 and 255
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_INVALID_ARGUMENT - if the animation is running</li>
+ * </ul>
+ */
+ public void setAlpha(final int alpha) {
+ if (alpha < 0 || alpha > 255) {
+ SWT.error(SWT.ERROR_INVALID_ARGUMENT);
+ }
+ this.checkIfAnimationIsRunning();
+ this.alpha = alpha;
+ }
+
+ /**
+ * Check if the animation is running
+ */
+ private void checkIfAnimationIsRunning() {
+ if (this.animatorThread != null) {
+ SWT.error(SWT.ERROR_INVALID_ARGUMENT, null, "Can not change this value when an animation is running");
+ }
+ }
+
+ /**
+ * @return the number of bars displayed in the ticker
+ */
+ public int getBarsCount() {
+ return this.barsCount;
+ }
+
+ /**
+ * @param barsCount the number of bars displayed in the ticker
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_INVALID_ARGUMENT - if the animation is running</li>
+ * </ul>
+ */
+ public void setBarsCount(final int barsCount) {
+ this.checkIfAnimationIsRunning();
+ this.barsCount = barsCount;
+ }
+
+ /**
+ * @return the default color for the ticker's bars
+ */
+ public Color getDefaultColor() {
+ return this.defaultColor;
+ }
+
+ /**
+ * @param defaultColor the new default color for the ticker's bars. Please
+ * notice that the previous color is disposed.
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_INVALID_ARGUMENT - if the animation is running</li>
+ * </ul>
+ */
+ public void setDefaultColor(final Color defaultColor) {
+ this.checkIfAnimationIsRunning();
+ SWTGraphicUtil.dispose(this.defaultColor);
+ this.defaultColor = defaultColor;
+ }
+
+ /**
+ * @return the number of frame per second for the animation
+ */
+ public float getFps() {
+ return this.fps;
+ }
+
+ /**
+ * @param fps the new frame per second value
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_INVALID_ARGUMENT - if the animation is running</li>
+ * </ul>
+ */
+ public void setFps(final float fps) {
+ this.checkIfAnimationIsRunning();
+ this.fps = fps;
+ }
+
+ /**
+ * @return the line width of the bars that compose the ticker
+ */
+ public int getLineWidth() {
+ return this.lineWidth;
+ }
+
+ /**
+ * @param lineWidth the line width of the bars that compose the ticker
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_INVALID_ARGUMENT - if the animation is running</li>
+ * </ul>
+ */
+ public void setLineWidth(final int lineWidth) {
+ this.checkIfAnimationIsRunning();
+ this.lineWidth = lineWidth;
+ }
+
+ /**
+ * @return the selection color of the ticker's bars
+ */
+ public Color getSelectionColor() {
+ return this.selectionColor;
+ }
+
+ /**
+ * @param selectionColor the new selection color for the ticker's bars.
+ * Please notice that the previous color is disposed.
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_INVALID_ARGUMENT - if the animation is running</li>
+ * </ul>
+ */
+ public void setSelectionColor(final Color selectionColor) {
+ this.checkIfAnimationIsRunning();
+ SWTGraphicUtil.dispose(this.selectionColor);
+ this.selectionColor = selectionColor;
+ }
+
+ /**
+ * @return the displayed text
+ */
+ public String getText() {
+ return this.text;
+ }
+
+ /**
+ * @param text set the text to display
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_INVALID_ARGUMENT - if the animation is running</li>
+ * </ul>
+ */
+ public void setText(final String text) {
+ this.checkIfAnimationIsRunning();
+ this.text = text;
+ }
+
+ /**
+ * @return the text color
+ */
+ public Color getTextColor() {
+ return this.textColor;
+ }
+
+ /**
+ * @param textColor the text color. Please notice that the previous color is
+ * disposed.
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_INVALID_ARGUMENT - if the animation is running</li>
+ * </ul>
+ */
+ public void setTextColor(final Color textColor) {
+ this.checkIfAnimationIsRunning();
+ SWTGraphicUtil.dispose(this.textColor);
+ this.textColor = textColor;
+ }
+
+ /**
+ * @return the text font
+ */
+ public Font getTextFont() {
+ return this.textFont;
+ }
+
+ /**
+ * @param textFont the new text font. Please notice that the previous font
+ * set is disposed.
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_INVALID_ARGUMENT - if the animation is running</li>
+ * </ul>
+ */
+ public void setTextFont(final Font textFont) {
+ this.checkIfAnimationIsRunning();
+ if (this.textFont != null && !this.textFont.isDisposed()) {
+ this.textFont.dispose();
+ }
+ this.textFont = textFont;
+
+ }
+
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/itemSelector/DLItem.java b/org.tizen.common.externals/src/org/mihalis/opal/itemSelector/DLItem.java
new file mode 100644
index 000000000..953226f21
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/itemSelector/DLItem.java
@@ -0,0 +1,105 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON
+ * 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:
+ * Laurent CARON (laurent.caron at gmail dot com) - initial API and implementation
+ *******************************************************************************/
+package org.mihalis.opal.itemSelector;
+
+import org.eclipse.swt.graphics.Color;
+import org.eclipse.swt.graphics.Font;
+import org.eclipse.swt.graphics.Image;
+import org.mihalis.opal.OpalItem;
+
+/**
+ * Instances of this class represents items manipulated by this DualList widget
+ */
+public class DLItem extends OpalItem {
+
+ /**
+ * Constructor
+ *
+ * @param text the text displayed in the DualList widget for this item
+ */
+ public DLItem(final String text) {
+ this.setText(text);
+ }
+
+ /**
+ * Constructor
+ *
+ * @param text the text displayed in the DualList widget for this item
+ * @param image the image displayed in the DualList widget for this item
+ */
+ public DLItem(final String text, final Image image) {
+ this.setText(text);
+ this.setImage(image);
+ }
+
+ /**
+ * Constructor
+ *
+ * @param text the text displayed in the DualList widget for this item
+ * @param image the image displayed in the DualList widget for this item
+ * @param font the font displayed in the DualList widget for this item
+ * @param foregroundColor the foreground color displayed in the DualList
+ * widget for this item
+ */
+ public DLItem(final String text, final Image image, final Font font, final Color foregroundColor) {
+ this.setText(text);
+ this.setImage(image);
+ this.setFont(font);
+ this.setForeground(foregroundColor);
+ }
+
+ /**
+ * Constructor
+ *
+ * @param text the text displayed in the DualList widget for this item
+ * @param image the image displayed in the DualList widget for this item
+ * @param foregroundColor the foreground color displayed in the DualList
+ * widget for this item
+ * @param backgroundColor the background color displayed in the DualList
+ * widget for this item
+ */
+ public DLItem(final String text, final Image image, final Color foregroundColor, final Color backgroundColor) {
+ this.setText(text);
+ this.setImage(image);
+ this.setForeground(foregroundColor);
+ this.setBackground(backgroundColor);
+ }
+
+ /**
+ * Constructor
+ *
+ * @param text the text displayed in the DualList widget for this item
+ * @param image the image displayed in the DualList widget for this item
+ * @param font the font displayed in the DualList widget for this item
+ */
+ public DLItem(final String text, final Image image, final Font font) {
+ this.setText(text);
+ this.setImage(image);
+ this.setFont(font);
+ }
+
+ /**
+ * @see org.mihalis.opal.OpalItem#getHeight()
+ */
+ @Override
+ public int getHeight() {
+ throw new UnsupportedOperationException("DLItem does not support this method");
+ }
+
+ /**
+ * @see org.mihalis.opal.OpalItem#setHeight(int)
+ */
+ @Override
+ public void setHeight(final int height) {
+ throw new UnsupportedOperationException("DLItem does not support this method");
+ }
+
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/itemSelector/DualList.java b/org.tizen.common.externals/src/org/mihalis/opal/itemSelector/DualList.java
new file mode 100644
index 000000000..8b6b90296
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/itemSelector/DualList.java
@@ -0,0 +1,1265 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON
+ * 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:
+ * Laurent CARON (laurent.caron at gmail dot com) - initial API and implementation
+ *******************************************************************************/
+package org.mihalis.opal.itemSelector;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.SWTException;
+import org.eclipse.swt.events.DisposeEvent;
+import org.eclipse.swt.events.DisposeListener;
+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.Image;
+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.Event;
+import org.eclipse.swt.widgets.Table;
+import org.eclipse.swt.widgets.TableColumn;
+import org.eclipse.swt.widgets.TableItem;
+import org.mihalis.opal.utils.SWTGraphicUtil;
+import org.mihalis.opal.utils.SimpleSelectionAdapter;
+
+/**
+ * Instances of this class are controls that allow the user to select multiple
+ * elements.
+ * <dl>
+ * <dt><b>Styles:</b></dt>
+ * <dd>(none)</dd>
+ * <dt><b>Events:</b></dt>
+ * <dd>Selection</dd>
+ * </dl>
+ */
+
+public class DualList extends Composite {
+
+ private final List<DLItem> items;
+ private final List<DLItem> selection;
+
+ private final Table itemsTable;
+ private final Table selectionTable;
+
+ private List<SelectionListener> eventTable;
+
+ /**
+ * Constructs a new instance of this class given its parent and a style
+ * value describing its behavior and appearance.
+ * <p>
+ * The style value is either one of the style constants defined in class
+ * <code>SWT</code> which is applicable to instances of this class, or must
+ * be built by <em>bitwise OR</em>'ing together (that is, using the
+ * <code>int</code> "|" operator) two or more of those <code>SWT</code>
+ * style constants. The class description lists the style constants that are
+ * applicable to the class. Style bits are also inherited from superclasses.
+ * </p>
+ *
+ * @param parent a composite control which will be the parent of the new
+ * instance (cannot be null)
+ * @param style the style of control to construct
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the parent is null</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the parent</li>
+ * </ul>
+ *
+ */
+ public DualList(final Composite parent, final int style) {
+ super(parent, style);
+ this.items = new ArrayList<DLItem>();
+ this.selection = new ArrayList<DLItem>();
+
+ this.setLayout(new GridLayout(4, false));
+ this.itemsTable = this.createTable();
+ this.itemsTable.addMouseListener(new MouseAdapter() {
+
+ /**
+ * @see org.eclipse.swt.events.MouseAdapter#mouseDoubleClick(org.eclipse.swt.events.MouseEvent)
+ */
+ @Override
+ public void mouseDoubleClick(final MouseEvent event) {
+ DualList.this.selectItem();
+ }
+
+ });
+ final Button buttonSelectAll = this.createButton("double_right.png", true, GridData.END);
+ buttonSelectAll.addSelectionListener(new SimpleSelectionAdapter() {
+
+ @Override
+ public void handle(final SelectionEvent e) {
+ DualList.this.selectAll();
+ }
+ });
+
+ this.selectionTable = this.createTable();
+ this.selectionTable.addMouseListener(new MouseAdapter() {
+
+ /**
+ * @see org.eclipse.swt.events.MouseAdapter#mouseDoubleClick(org.eclipse.swt.events.MouseEvent)
+ */
+ @Override
+ public void mouseDoubleClick(final MouseEvent event) {
+ DualList.this.deselectItem();
+ }
+
+ });
+
+ final Button buttonMoveFirst = this.createButton("double_up.png", true, GridData.END);
+ buttonMoveFirst.addSelectionListener(new SimpleSelectionAdapter() {
+
+ @Override
+ public void handle(final SelectionEvent e) {
+ DualList.this.moveSelectionToFirstPosition();
+ }
+ });
+
+ final Button buttonSelect = this.createButton("arrow_right.png", false, GridData.CENTER);
+ buttonSelect.addSelectionListener(new SimpleSelectionAdapter() {
+
+ @Override
+ public void handle(final SelectionEvent e) {
+ DualList.this.selectItem();
+ }
+ });
+
+ final Button buttonMoveUp = this.createButton("arrow_up.png", false, GridData.CENTER);
+ buttonMoveUp.addSelectionListener(new SimpleSelectionAdapter() {
+
+ @Override
+ public void handle(final SelectionEvent e) {
+ DualList.this.moveUpItem();
+ }
+ });
+
+ final Button buttonDeselect = this.createButton("arrow_left.png", false, GridData.CENTER);
+ buttonDeselect.addSelectionListener(new SimpleSelectionAdapter() {
+
+ @Override
+ public void handle(final SelectionEvent e) {
+ DualList.this.deselectItem();
+ }
+ });
+
+ final Button buttonMoveDown = this.createButton("arrow_down.png", false, GridData.CENTER);
+ buttonMoveDown.addSelectionListener(new SimpleSelectionAdapter() {
+
+ @Override
+ public void handle(final SelectionEvent e) {
+ DualList.this.moveDownItem();
+ }
+ });
+
+ final Button buttonDeselectAll = this.createButton("double_left.png", false, GridData.BEGINNING);
+ buttonDeselectAll.addSelectionListener(new SimpleSelectionAdapter() {
+
+ @Override
+ public void handle(final SelectionEvent e) {
+ DualList.this.deselectAll();
+ }
+ });
+
+ final Button buttonMoveLast = this.createButton("double_down.png", true, GridData.BEGINNING);
+ buttonMoveLast.addSelectionListener(new SimpleSelectionAdapter() {
+
+ @Override
+ public void handle(final SelectionEvent e) {
+ DualList.this.moveSelectionToLastPosition();
+ }
+ });
+
+ }
+
+ /**
+ * @return a table that will contain data
+ */
+ private Table createTable() {
+ final Table table = new Table(this, SWT.V_SCROLL | SWT.H_SCROLL | SWT.MULTI | SWT.FULL_SELECTION);
+ table.setLinesVisible(false);
+ table.setHeaderVisible(false);
+ final GridData gd = new GridData(GridData.FILL, GridData.FILL, true, true, 1, 4);
+ gd.widthHint = 200;
+ table.setLayoutData(gd);
+ new TableColumn(table, SWT.CENTER);
+ new TableColumn(table, SWT.LEFT);
+ table.setData(-1);
+ return table;
+ }
+
+ /**
+ * Create a button
+ *
+ * @param fileName file name of the icon
+ * @param verticalExpand if <code>true</code>, the button will take all the
+ * available space vertically
+ * @param alignment button alignment
+ * @return a new button
+ */
+ private Button createButton(final String fileName, final boolean verticalExpand, final int alignment) {
+ final Button button = new Button(this, SWT.PUSH);
+ final Image image = new Image(this.getDisplay(), this.getClass().getClassLoader().getResourceAsStream("images/" + fileName));
+ button.setImage(image);
+ button.setLayoutData(new GridData(GridData.CENTER, alignment, false, verticalExpand));
+ button.addDisposeListener(new DisposeListener() {
+
+ @Override
+ public void widgetDisposed(final DisposeEvent e) {
+ SWTGraphicUtil.dispose(image);
+ }
+ });
+ return button;
+ }
+
+ /**
+ * Adds the argument to the end of the receiver's list.
+ *
+ * @param item the new item
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the item is null</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ *
+ * @see #add(DLItem,int)
+ */
+ public void add(final DLItem item) {
+ this.checkWidget();
+ if (item == null) {
+ SWT.error(SWT.ERROR_NULL_ARGUMENT);
+ }
+ this.items.add(item);
+ }
+
+ /**
+ * Adds the argument to the receiver's list at the given zero-relative
+ * index.
+ * <p>
+ * Note: To add an item at the end of the list, use the result of calling
+ * <code>getItemCount()</code> as the index or use <code>add(DLItem)</code>.
+ * </p>
+ *
+ * @param item the new item
+ * @param index the index for the item
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the item is null</li>
+ * <li>ERROR_INVALID_RANGE - if the index is not between 0
+ * and the number of elements in the list (inclusive)</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ *
+ * @see #add(String)
+ */
+ public void add(final DLItem item, final int index) {
+ this.checkWidget();
+ if (item == null) {
+ SWT.error(SWT.ERROR_NULL_ARGUMENT);
+ }
+ if (index <= 0 || index >= this.items.size()) {
+ SWT.error(SWT.ERROR_INVALID_ARGUMENT);
+ }
+ this.items.add(index, item);
+ }
+
+ /**
+ * Adds the listener to the collection of listeners who will be notified
+ * when the user changes the receiver's selection, by sending it one of the
+ * messages defined in the <code>SelectionListener</code> interface.
+ *
+ * @param listener the listener which should be notified
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the listener is null</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ *
+ * @see SelectionListener
+ * @see #removeSelectionListener
+ * @see SelectionEvent
+ */
+ public void addSelectionListener(final SelectionListener listener) {
+ this.checkWidget();
+ if (listener == null) {
+ SWT.error(SWT.ERROR_NULL_ARGUMENT);
+ }
+ if (this.eventTable == null) {
+ this.eventTable = new ArrayList<SelectionListener>();
+ }
+ this.eventTable.add(listener);
+ }
+
+ /**
+ * Removes the listener from the collection of listeners who will be
+ * notified when the user changes the receiver's selection.
+ *
+ * @param listener the listener which should no longer be notified
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the listener is null</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ *
+ * @see SelectionListener
+ * @see #addSelectionListener
+ */
+ public void removeSelectionListener(final SelectionListener listener) {
+ this.checkWidget();
+ if (listener == null) {
+ SWT.error(SWT.ERROR_NULL_ARGUMENT);
+ }
+ if (this.eventTable == null) {
+ return;
+ }
+ this.eventTable.remove(listener);
+ }
+
+ /**
+ * Deselects the item at the given zero-relative index in the receiver. If
+ * the item at the index was already deselected, it remains deselected.
+ * Indices that are out of range are ignored.
+ *
+ * @param index the index of the item to deselect
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void deselect(final int index) {
+ this.checkWidget();
+ if (index <= 0 || index >= this.items.size()) {
+ return;
+ }
+ this.fireEvents(this.selection.remove(index));
+ this.redrawTables();
+ }
+
+ /**
+ * Deselects the items at the given zero-relative indices in the receiver.
+ * If the item at the given zero-relative index in the receiver is selected,
+ * it is deselected. If the item at the index was not selected, it remains
+ * deselected. Indices that are out of range and duplicate indices are
+ * ignored.
+ *
+ * @param indices the array of indices for the items to deselect
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the set of indices is null</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void deselect(final int[] indices) {
+ this.checkWidget();
+ if (indices == null) {
+ SWT.error(SWT.ERROR_NULL_ARGUMENT);
+ }
+
+ final List<DLItem> toBeRemoved = new ArrayList<DLItem>();
+
+ for (final int index : indices) {
+ if (index <= 0 || index >= this.items.size()) {
+ continue;
+ }
+ toBeRemoved.add(this.selection.get(index));
+ }
+
+ for (final DLItem item : toBeRemoved) {
+ this.selection.remove(item);
+ }
+ toBeRemoved.clear();
+ this.redrawTables();
+ }
+
+ /**
+ * Deselects the items at the given zero-relative indices in the receiver.
+ * If the item at the given zero-relative index in the receiver is selected,
+ * it is deselected. If the item at the index was not selected, it remains
+ * deselected. The range of the indices is inclusive. Indices that are out
+ * of range are ignored.
+ *
+ * @param start the start index of the items to deselect
+ * @param end the end index of the items to deselect
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_INVALID_RANGE - if start is greater than end</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void deselect(final int start, final int end) {
+ this.checkWidget();
+ if (start > end) {
+ SWT.error(SWT.ERROR_INVALID_RANGE);
+ }
+ final List<DLItem> toBeRemoved = new ArrayList<DLItem>();
+
+ for (int index = start; index <= end; index++) {
+ if (index <= 0 || index >= this.items.size()) {
+ continue;
+ }
+ toBeRemoved.add(this.selection.get(index));
+ }
+
+ for (final DLItem item : toBeRemoved) {
+ this.selection.remove(item);
+ }
+ toBeRemoved.clear();
+ this.redrawTables();
+ }
+
+ /**
+ * Deselects all selected items in the receiver.
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void deselectAll() {
+ this.checkWidget();
+ this.items.addAll(this.selection);
+ this.selection.clear();
+ this.redrawTables();
+ }
+
+ /**
+ * Returns the item at the given, zero-relative index in the receiver.
+ * Throws an exception if the index is out of range.
+ *
+ * @param index the index of the item to return
+ * @return the item at the given index
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_INVALID_RANGE - if the index is not between 0
+ * and the number of elements in the list minus 1 (inclusive)
+ * </li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+
+ public DLItem getItem(final int index) {
+ this.checkWidget();
+ if (index <= 0 || index >= this.items.size()) {
+ SWT.error(SWT.ERROR_INVALID_ARGUMENT);
+ }
+ return this.items.get(index);
+ }
+
+ /**
+ * Returns the number of items contained in the receiver.
+ *
+ * @return the number of items
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public int getItemCount() {
+ this.checkWidget();
+ return this.items.size();
+ }
+
+ /**
+ * Returns a (possibly empty) array of <code>DLItem</code>s which are the
+ * items in the receiver.
+ * <p>
+ * Note: This is not the actual structure used by the receiver to maintain
+ * its list of items, so modifying the array will not affect the receiver.
+ * </p>
+ *
+ * @return the items in the receiver's list
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public DLItem[] getItems() {
+ this.checkWidget();
+ return this.items.toArray(new DLItem[this.items.size()]);
+ }
+
+ /**
+ * Returns a (possibly empty) list of <code>DLItem</code>s which are the
+ * items in the receiver.
+ * <p>
+ * Note: This is not the actual structure used by the receiver to maintain
+ * its list of items, so modifying the array will not affect the receiver.
+ * </p>
+ *
+ * @return the items in the receiver's list
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public List<DLItem> getItemsAsList() {
+ this.checkWidget();
+ return new ArrayList<DLItem>(this.items);
+ }
+
+ /**
+ * Returns an array of <code>DLItem</code>s that are currently selected in
+ * the receiver. An empty array indicates that no items are selected.
+ * <p>
+ * Note: This is not the actual structure used by the receiver to maintain
+ * its selection, so modifying the array will not affect the receiver.
+ * </p>
+ *
+ * @return an array representing the selection
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public DLItem[] getSelection() {
+ this.checkWidget();
+ return this.selection.toArray(new DLItem[this.items.size()]);
+ }
+
+ /**
+ * Returns a list of <code>DLItem</code>s that are currently selected in the
+ * receiver. An empty array indicates that no items are selected.
+ * <p>
+ * Note: This is not the actual structure used by the receiver to maintain
+ * its selection, so modifying the array will not affect the receiver.
+ * </p>
+ *
+ * @return an array representing the selection
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public List<DLItem> getSelectionAsList() {
+ this.checkWidget();
+ return new ArrayList<DLItem>(this.selection);
+ }
+
+ /**
+ * Returns the number of selected items contained in the receiver.
+ *
+ * @return the number of selected items
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public int getSelectionCount() {
+ this.checkWidget();
+ return this.selection.size();
+ }
+
+ /**
+ * Removes the item from the receiver at the given zero-relative index.
+ *
+ * @param index the index for the item
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_INVALID_RANGE - if the index is not between 0
+ * and the number of elements in the list minus 1 (inclusive)
+ * </li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void remove(final int index) {
+ this.checkWidget();
+ if (index <= 0 || index >= this.items.size()) {
+ SWT.error(SWT.ERROR_INVALID_ARGUMENT);
+ }
+ this.items.remove(index);
+ this.redrawTables();
+ }
+
+ /**
+ * Removes the items from the receiver at the given zero-relative indices.
+ *
+ * @param indices the array of indices of the items
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_INVALID_RANGE - if the index is not between 0
+ * and the number of elements in the list minus 1 (inclusive)
+ * </li>
+ * <li>ERROR_NULL_ARGUMENT - if the indices array is null</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void remove(final int[] indices) {
+ this.checkWidget();
+ for (final int index : indices) {
+ if (index <= 0 || index >= this.items.size()) {
+ SWT.error(SWT.ERROR_INVALID_ARGUMENT);
+ }
+ this.items.remove(index);
+ }
+ this.redrawTables();
+ }
+
+ /**
+ * Removes the items from the receiver which are between the given
+ * zero-relative start and end indices (inclusive).
+ *
+ * @param start the start of the range
+ * @param end the end of the range
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_INVALID_RANGE - if either the start or end are
+ * not between 0 and the number of elements in the list minus
+ * 1 (inclusive) or if start>end</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void remove(final int start, final int end) {
+ this.checkWidget();
+ if (start > end) {
+ SWT.error(SWT.ERROR_INVALID_ARGUMENT);
+ }
+ for (int index = start; index <= end; index++) {
+ if (index <= 0 || index >= this.items.size()) {
+ SWT.error(SWT.ERROR_INVALID_ARGUMENT);
+ }
+ this.items.remove(index);
+ }
+ this.redrawTables();
+ }
+
+ /**
+ * Searches the receiver's list starting at the first item until an item is
+ * found that is equal to the argument, and removes that item from the list.
+ *
+ * @param item the item to remove
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the item is null</li>
+ * <li>ERROR_INVALID_ARGUMENT - if the item is not found in
+ * the list</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void remove(final DLItem item) {
+ this.checkWidget();
+ if (item == null) {
+ SWT.error(SWT.ERROR_NULL_ARGUMENT);
+ }
+ if (!this.items.contains(item)) {
+ SWT.error(SWT.ERROR_INVALID_ARGUMENT);
+ }
+ this.items.remove(item);
+ this.redrawTables();
+ }
+
+ /**
+ * Removes all of the items from the receiver.
+ * <p>
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li> <li>ERROR_THREAD_INVALID_ACCESS - if not
+ * called from the thread that created the receiver</li>
+ * </ul>
+ */
+ public void removeAll() {
+ this.checkWidget();
+ this.items.clear();
+ this.redrawTables();
+ }
+
+ /**
+ * Selects the item at the given zero-relative index in the receiver's list.
+ * If the item at the index was already selected, it remains selected.
+ * Indices that are out of range are ignored.
+ *
+ * @param index the index of the item to select
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void select(final int index) {
+ this.checkWidget();
+ if (index <= 0 || index >= this.items.size()) {
+ return;
+ }
+ this.selection.add(this.items.get(index));
+ this.fireEvents(this.items.get(index));
+ this.redrawTables();
+ }
+
+ /**
+ * Selects the items at the given zero-relative indices in the receiver. The
+ * current selection is not cleared before the new items are selected.
+ * <p>
+ * If the item at a given index is not selected, it is selected. If the item
+ * at a given index was already selected, it remains selected. Indices that
+ * are out of range and duplicate indices are ignored. If the receiver is
+ * single-select and multiple indices are specified, then all indices are
+ * ignored.
+ *
+ * @param indices the array of indices for the items to select
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the array of indices is null
+ * </li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li> <li>ERROR_THREAD_INVALID_ACCESS - if not
+ * called from the thread that created the receiver</li>
+ * </ul>
+ */
+ public void select(final int[] indices) {
+ this.checkWidget();
+ if (indices == null) {
+ SWT.error(SWT.ERROR_NULL_ARGUMENT);
+ }
+ for (final int index : indices) {
+ if (index <= 0 || index >= this.items.size()) {
+ continue;
+ }
+ this.selection.add(this.items.get(index));
+ this.fireEvents(this.items.get(index));
+ }
+ this.redrawTables();
+ }
+
+ /**
+ * Selects the items in the range specified by the given zero-relative
+ * indices in the receiver. The range of indices is inclusive. The current
+ * selection is not cleared before the new items are selected.
+ * <p>
+ * If an item in the given range is not selected, it is selected. If an item
+ * in the given range was already selected, it remains selected. Indices
+ * that are out of range are ignored and no items will be selected if start
+ * is greater than end. If the receiver is single-select and there is more
+ * than one item in the given range, then all indices are ignored.
+ *
+ * @param start the start of the range
+ * @param end the end of the range
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li> <li>ERROR_THREAD_INVALID_ACCESS - if not
+ * called from the thread that created the receiver</li>
+ * </ul>
+ *
+ * @see List#setSelection(int,int)
+ */
+ public void select(final int start, final int end) {
+ this.checkWidget();
+ if (start > end) {
+ SWT.error(SWT.ERROR_INVALID_RANGE);
+ }
+ for (int index = start; index <= end; index++) {
+ if (index <= 0 || index >= this.items.size()) {
+ continue;
+ }
+ this.selection.add(this.items.get(index));
+ this.fireEvents(this.items.get(index));
+ }
+ this.redrawTables();
+ }
+
+ /**
+ * Selects all of the items in the receiver.
+ * <p>
+ * If the receiver is single-select, do nothing.
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li> <li>ERROR_THREAD_INVALID_ACCESS - if not
+ * called from the thread that created the receiver</li>
+ * </ul>
+ */
+ public void selectAll() {
+ this.checkWidget();
+ this.selection.addAll(this.items);
+ for (final DLItem item : this.items) {
+ this.fireEvents(item);
+ }
+ this.items.clear();
+ this.redrawTables();
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Control#setBounds(int, int, int, int)
+ */
+ @Override
+ public void setBounds(final int x, final int y, final int width, final int height) {
+ super.setBounds(x, y, width, height);
+ final boolean itemsContainImage = this.itemsContainImage();
+ final Point itemsTableDefaultSize = this.itemsTable.computeSize(SWT.DEFAULT, SWT.DEFAULT);
+ final Point selectionTableDefaultSize = this.selectionTable.computeSize(SWT.DEFAULT, SWT.DEFAULT);
+
+ int itemsTableSize = this.itemsTable.getSize().x;
+ if (itemsTableDefaultSize.y > this.itemsTable.getSize().y) {
+ itemsTableSize -= this.itemsTable.getVerticalBar().getSize().x;
+ }
+
+ int selectionTableSize = this.selectionTable.getSize().x;
+ if (selectionTableDefaultSize.y > this.selectionTable.getSize().y) {
+ selectionTableSize -= this.selectionTable.getVerticalBar().getSize().x;
+ }
+
+ if (itemsContainImage) {
+ this.itemsTable.getColumn(0).pack();
+ this.itemsTable.getColumn(1).setWidth(itemsTableSize - this.itemsTable.getColumn(0).getWidth());
+
+ this.selectionTable.getColumn(0).pack();
+ this.selectionTable.getColumn(1).setWidth(selectionTableSize - this.selectionTable.getColumn(0).getWidth());
+
+ } else {
+ this.itemsTable.getColumn(0).setWidth(itemsTableSize);
+ this.selectionTable.getColumn(0).setWidth(selectionTableSize);
+ }
+ }
+
+ /**
+ * @return <code>true</code> if any item contains an image
+ */
+ private boolean itemsContainImage() {
+ for (final DLItem item : this.items) {
+ if (item.getImage() != null) {
+ return true;
+ }
+ }
+
+ for (final DLItem item : this.selection) {
+ if (item.getImage() != null) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ /**
+ * Sets the item in the receiver's list at the given zero-relative index to
+ * the item argument.
+ *
+ * @param index the index for the item
+ * @param item the new item
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_INVALID_RANGE - if the index is not between 0
+ * and the number of elements in the list minus 1 (inclusive)
+ * </li>
+ * <li>ERROR_NULL_ARGUMENT - if the item is null</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void setItem(final int index, final DLItem item) {
+ this.checkWidget();
+ if (item == null) {
+ SWT.error(SWT.ERROR_NULL_ARGUMENT);
+ }
+ if (index <= 0 || index >= this.items.size()) {
+ SWT.error(SWT.ERROR_INVALID_RANGE);
+ }
+ this.items.set(index, item);
+ this.redrawTables();
+ }
+
+ /**
+ * Sets the receiver's items to be the given array of items.
+ *
+ * @param items the array of items
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the items array is null</li>
+ * <li>ERROR_INVALID_ARGUMENT - if an item in the items array
+ * is null</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void setItems(final DLItem[] items) {
+ this.checkWidget();
+ if (items == null) {
+ SWT.error(SWT.ERROR_NULL_ARGUMENT);
+ }
+
+ final List<DLItem> temp = new ArrayList<DLItem>();
+ for (final DLItem item : items) {
+ if (item == null) {
+ SWT.error(SWT.ERROR_INVALID_ARGUMENT);
+ }
+ temp.add(item);
+ }
+ this.items.clear();
+ this.items.addAll(temp);
+ this.redrawTables();
+ }
+
+ /**
+ * Sets the receiver's items to be the given list of items.
+ *
+ * @param items the list of items
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the items list is null</li>
+ * <li>ERROR_INVALID_ARGUMENT - if an item in the items list
+ * is null</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void setItems(final List<DLItem> items) {
+ this.checkWidget();
+ this.checkWidget();
+ if (items == null) {
+ SWT.error(SWT.ERROR_NULL_ARGUMENT);
+ }
+
+ final List<DLItem> temp = new ArrayList<DLItem>();
+ for (final DLItem item : items) {
+ if (item == null) {
+ SWT.error(SWT.ERROR_INVALID_ARGUMENT);
+ }
+ temp.add(item);
+ }
+ this.items.clear();
+ this.items.addAll(temp);
+ this.redrawTables();
+ }
+
+ /**
+ * Redraws all tables that compose this widget
+ */
+ private void redrawTables() {
+ this.setRedraw(false);
+ this.redrawTable(this.itemsTable, false);
+ this.redrawTable(this.selectionTable, true);
+ this.setRedraw(true);
+ this.setBounds(this.getBounds());
+ }
+
+ /**
+ * Redraw a given table
+ *
+ * @param table table to be redrawned
+ * @param isSelected if <code>true</code>, fill the table with the
+ * selection. Otherwise, fill the table with the unselected
+ * items.
+ */
+ private void redrawTable(final Table table, final boolean isSelected) {
+ this.clean(table);
+ this.fillData(table, isSelected ? this.selection : this.items);
+ }
+
+ /**
+ * Cleans the content of a table
+ *
+ * @param table table to be emptied
+ */
+ private void clean(final Table table) {
+ if (table == null) {
+ return;
+ }
+
+ for (final TableItem item : table.getItems()) {
+ item.dispose();
+ }
+ }
+
+ /**
+ * Fill a table with data
+ *
+ * @param table table to be filled
+ * @param listOfData list of data
+ */
+ private void fillData(final Table table, final List<DLItem> listOfData) {
+ for (final DLItem item : listOfData) {
+ final TableItem tableItem = new TableItem(table, SWT.NONE);
+ tableItem.setData(item);
+
+ if (item.getBackground() != null) {
+ tableItem.setBackground(item.getBackground());
+ }
+
+ if (item.getForeground() != null) {
+ tableItem.setForeground(item.getForeground());
+ }
+
+ if (item.getImage() != null) {
+ tableItem.setImage(0, item.getImage());
+ }
+
+ if (item.getFont() != null) {
+ tableItem.setFont(item.getFont());
+ }
+
+ tableItem.setText(1, item.getText());
+ }
+
+ }
+
+ /**
+ * Move the selected item to the first position
+ */
+ protected void moveSelectionToFirstPosition() {
+ if (this.selectionTable.getSelectionCount() == 0) {
+ return;
+ }
+
+ int index = 0;
+ for (final TableItem tableItem : this.selectionTable.getSelection()) {
+ final DLItem item = (DLItem) tableItem.getData();
+ this.selection.remove(item);
+ this.selection.add(index++, item);
+ }
+
+ this.redrawTables();
+ this.selectionTable.select(0, index - 1);
+ this.selectionTable.forceFocus();
+ }
+
+ /**
+ * Select a given item
+ */
+ protected void selectItem() {
+ if (this.itemsTable.getSelectionCount() == 0) {
+ return;
+ }
+ for (final TableItem tableItem : this.itemsTable.getSelection()) {
+ final DLItem item = (DLItem) tableItem.getData();
+ this.selection.add(item);
+ this.items.remove(item);
+ }
+ this.redrawTables();
+ }
+
+ /**
+ * Move the selected item up
+ */
+ protected void moveUpItem() {
+ if (this.selectionTable.getSelectionCount() == 0) {
+ return;
+ }
+
+ for (final int index : this.selectionTable.getSelectionIndices()) {
+ if (index == 0) {
+ this.selectionTable.forceFocus();
+ return;
+ }
+ }
+
+ final int[] newSelection = new int[this.selectionTable.getSelectionCount()];
+ int newSelectionIndex = 0;
+ for (final TableItem tableItem : this.selectionTable.getSelection()) {
+ final int position = this.selection.indexOf(tableItem.getData());
+ this.swap(position, position - 1);
+ newSelection[newSelectionIndex++] = position - 1;
+ }
+
+ this.redrawTables();
+ this.selectionTable.select(newSelection);
+ this.selectionTable.forceFocus();
+ }
+
+ /**
+ * Deselect a given item
+ */
+ protected void deselectItem() {
+ if (this.selectionTable.getSelectionCount() == 0) {
+ return;
+ }
+ for (final TableItem tableItem : this.selectionTable.getSelection()) {
+ final DLItem item = (DLItem) tableItem.getData();
+ this.items.add(item);
+ this.selection.remove(item);
+ }
+ this.redrawTables();
+ }
+
+ /**
+ * Move the selected item down
+ */
+ protected void moveDownItem() {
+ if (this.selectionTable.getSelectionCount() == 0) {
+ return;
+ }
+
+ for (final int index : this.selectionTable.getSelectionIndices()) {
+ if (index == this.selectionTable.getItemCount() - 1) {
+ this.selectionTable.forceFocus();
+ return;
+ }
+ }
+
+ final int[] newSelection = new int[this.selectionTable.getSelectionCount()];
+ int newSelectionIndex = 0;
+ for (final TableItem tableItem : this.selectionTable.getSelection()) {
+ final int position = this.selection.indexOf(tableItem.getData());
+ this.swap(position, position + 1);
+ newSelection[newSelectionIndex++] = position + 1;
+ }
+
+ this.redrawTables();
+ this.selectionTable.select(newSelection);
+ this.selectionTable.forceFocus();
+
+ }
+
+ /**
+ * Swap 2 items
+ *
+ * @param first position of the first item to swap
+ * @param second position of the second item to swap
+ */
+ private void swap(final int first, final int second) {
+ final DLItem temp = this.selection.get(first);
+ this.selection.set(first, this.selection.get(second));
+ this.selection.set(second, temp);
+ }
+
+ /**
+ * Move the selected item to the last position
+ */
+ protected void moveSelectionToLastPosition() {
+ if (this.selectionTable.getSelectionCount() == 0) {
+ return;
+ }
+
+ final int numberOfSelectedElements = this.selectionTable.getSelectionCount();
+ for (final TableItem tableItem : this.selectionTable.getSelection()) {
+ final DLItem item = (DLItem) tableItem.getData();
+ this.selection.remove(item);
+ this.selection.add(item);
+ }
+
+ this.redrawTables();
+ final int numberOfElements = this.selectionTable.getItemCount();
+ this.selectionTable.select(numberOfElements - numberOfSelectedElements, numberOfElements - 1);
+ this.selectionTable.forceFocus();
+ }
+
+ /**
+ * Call all selection listeners
+ *
+ * @param item selected item
+ */
+ private void fireEvents(final DLItem item) {
+ if (this.eventTable == null) {
+ return;
+ }
+
+ final Event event = new Event();
+ event.button = 1;
+ event.display = this.getDisplay();
+ event.item = null;
+ event.widget = this;
+ event.data = item;
+ final SelectionEvent selectionEvent = new SelectionEvent(event);
+
+ for (final SelectionListener listener : this.eventTable) {
+ listener.widgetSelected(selectionEvent);
+ }
+
+ }
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/launcher/LLabel.java b/org.tizen.common.externals/src/org/mihalis/opal/launcher/LLabel.java
new file mode 100644
index 000000000..d6aa5e577
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/launcher/LLabel.java
@@ -0,0 +1,277 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON
+ * 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:
+ * Laurent CARON (laurent.caron at gmail dot com) - Initial implementation and API
+ *******************************************************************************/
+package org.mihalis.opal.launcher;
+
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.SWTException;
+import org.eclipse.swt.events.PaintEvent;
+import org.eclipse.swt.events.PaintListener;
+import org.eclipse.swt.graphics.Font;
+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.Event;
+import org.eclipse.swt.widgets.Listener;
+import org.mihalis.opal.utils.SWTGraphicUtil;
+
+/**
+ * Instance of this class are a button with text, image and a nice animation
+ * effect
+ */
+class LLabel extends Canvas {
+
+ private String text;
+ private Image image;
+ private Font font;
+
+ private static final int GAP = 12;
+ private static int DRAW_FLAGS = SWT.DRAW_MNEMONIC | SWT.DRAW_TAB | SWT.DRAW_TRANSPARENT | SWT.DRAW_DELIMITER;
+ private static final int DEFAULT_MARGIN = 5;
+ private final int leftMargin = DEFAULT_MARGIN;
+ private final int topMargin = DEFAULT_MARGIN;
+ private final int rightMargin = DEFAULT_MARGIN;
+ private final int bottomMargin = DEFAULT_MARGIN;
+ private Point textSize;
+
+ private static final int MAX_NUMBER_OF_STEPS = 10;
+ private int animationStep = 0;
+
+ /**
+ * Constructs a new instance of this class given its parent and a style
+ * value describing its behavior and appearance.
+ * <p>
+ * The style value is either one of the style constants defined in class
+ * <code>SWT</code> which is applicable to instances of this class, or must
+ * be built by <em>bitwise OR</em>'ing together (that is, using the
+ * <code>int</code> "|" operator) two or more of those <code>SWT</code>
+ * style constants. The class description lists the style constants that are
+ * applicable to the class. Style bits are also inherited from superclasses.
+ * </p>
+ *
+ * @param parent a composite control which will be the parent of the new
+ * instance (cannot be null)
+ * @param style the style of control to construct
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the parent is null</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the parent</li>
+ * </ul>
+ *
+ */
+ LLabel(final Composite parent, final int style) {
+ super(parent, style | SWT.BORDER | SWT.DOUBLE_BUFFERED);
+
+ final Font original = super.getFont();
+
+ this.font = new Font(getDisplay(), original.getFontData()[0].getName(), 18, SWT.BOLD);
+
+ addPaintListener(new PaintListener() {
+ @Override
+ public void paintControl(final PaintEvent event) {
+ onPaint(event);
+ }
+ });
+
+ addListener(SWT.Dispose, new Listener() {
+ @Override
+ public void handleEvent(final Event event) {
+ onDispose(event);
+ }
+ });
+ }
+
+ /**
+ * Draw the content of the LLabel
+ *
+ * @param event paintevent
+ */
+ private void onPaint(final PaintEvent event) {
+ final Rectangle rect = getClientArea();
+ if (rect.width == 0 || rect.height == 0) {
+ return;
+ }
+
+ final Image bufferImage = new Image(getDisplay(), Math.max(1, rect.width), Math.max(1, rect.height));
+
+ final GC gc = new GC(bufferImage);
+ gc.setForeground(getForeground());
+ gc.setBackground(getBackground());
+
+ gc.fillRectangle(rect);
+
+ final Point extent = getTotalSize(this.image.getBounds().width, this.image.getBounds().height);
+ final int xImage = (rect.width - this.image.getBounds().width) / 2;
+ final int yImage = (rect.height - extent.y) / 2;
+ gc.drawImage(this.image, xImage, yImage);
+
+ gc.setFont(this.font);
+ final int xText = (rect.width - this.textSize.x) / 2;
+ final int yText = yImage + this.image.getBounds().height + GAP - this.textSize.y / 2;
+ gc.drawString(this.text, xText, yText);
+
+ if (this.animationStep != 0) {
+ final float zoom = 1f + this.animationStep * (Math.max(extent.x, extent.y) - Math.max(this.image.getBounds().width, this.image.getBounds().height)) / MAX_NUMBER_OF_STEPS / 100f;
+
+ final int newSizeX = (int) (this.image.getBounds().width * zoom);
+ final int newSizeY = (int) (this.image.getBounds().height * zoom);
+
+ gc.setAntialias(SWT.ON);
+ gc.setInterpolation(SWT.HIGH);
+
+ gc.setAlpha(255 - 255 / MAX_NUMBER_OF_STEPS * this.animationStep);
+
+ final Point extentZoomedImage = getTotalSize(newSizeX, newSizeY);
+ final int xZoomedImage = (rect.width - newSizeX) / 2;
+ final int yZoomedImage = (rect.height - extentZoomedImage.y) / 2;
+ gc.drawImage(this.image, 0, 0, this.image.getBounds().width, this.image.getBounds().height, xZoomedImage, yZoomedImage, (int) (this.image.getBounds().width * zoom), (int) (this.image.getBounds().height * zoom));
+
+ }
+
+ gc.dispose();
+
+ event.gc.drawImage(bufferImage, 0, 0);
+
+ bufferImage.dispose();
+
+ }
+
+ /**
+ * Dispose elements when the widget is disposed
+ *
+ * @param event dispose event
+ */
+ private void onDispose(final Event event) {
+ SWTGraphicUtil.dispose(this.image);
+ SWTGraphicUtil.dispose(this.font);
+ this.text = null;
+ this.image = null;
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Composite#computeSize(int, int, boolean)
+ */
+ @Override
+ public Point computeSize(final int wHint, final int hHint, final boolean changed) {
+ checkWidget();
+ final Point e = getTotalSize(this.image.getBounds().width, this.image.getBounds().height);
+ if (wHint == SWT.DEFAULT) {
+ e.x += this.leftMargin + this.rightMargin;
+ } else {
+ e.x = wHint;
+ }
+ if (hHint == SWT.DEFAULT) {
+ e.y += this.topMargin + this.bottomMargin;
+ } else {
+ e.y = hHint;
+ }
+ return e;
+ }
+
+ /**
+ * Compute the size of the content (image + text + gap)
+ *
+ * @param imgWidth image width
+ * @param imgHeight image height
+ * @return the size of the content
+ */
+ private Point getTotalSize(final int imgWidth, final int imgHeight) {
+ final Point size = new Point(0, 0);
+
+ int textWidth = 0;
+ int textHeight = 0;
+
+ if (this.textSize == null) {
+ final GC gc = new GC(this);
+ gc.setFont(this.font);
+
+ this.textSize = gc.textExtent(this.text, DRAW_FLAGS);
+ gc.dispose();
+
+ }
+ textWidth = this.textSize.x;
+ textHeight = this.textSize.y;
+
+ size.x = Math.max(imgWidth, textWidth);
+ size.y = imgHeight + GAP + textHeight;
+
+ return size;
+ }
+
+ /**
+ * @return the text
+ */
+ String getText() {
+ return this.text;
+ }
+
+ /**
+ * @param text the text to set
+ */
+ void setText(final String text) {
+ this.text = text;
+ }
+
+ /**
+ * @return the image
+ */
+ Image getImage() {
+ return this.image;
+ }
+
+ /**
+ * @param image the image to set
+ */
+ void setImage(final Image image) {
+ this.image = image;
+ }
+
+ /**
+ * @return the font
+ */
+ @Override
+ public Font getFont() {
+ return this.font;
+ }
+
+ /**
+ * @param font the font to set
+ */
+ @Override
+ public void setFont(final Font font) {
+ SWTGraphicUtil.dispose(font);
+ this.font = font;
+ }
+
+ /**
+ * Increment the steps of the animation
+ *
+ * @return true if animation keeps running, false otherwise
+ */
+ boolean incrementAnimation() {
+ this.animationStep++;
+ final boolean stopAnimation = this.animationStep > MAX_NUMBER_OF_STEPS;
+
+ if (stopAnimation) {
+ this.animationStep = 0;
+ }
+ if (!isDisposed()) {
+ redraw();
+ }
+ return !stopAnimation;
+ }
+
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/launcher/Launcher.java b/org.tizen.common.externals/src/org/mihalis/opal/launcher/Launcher.java
new file mode 100755
index 000000000..42bf7b1f8
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/launcher/Launcher.java
@@ -0,0 +1,428 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON
+ * 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:
+ * Laurent CARON (laurent.caron at gmail dot com) - Initial implementation and API
+ *******************************************************************************/
+package org.mihalis.opal.launcher;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.SWTException;
+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.Control;
+import org.eclipse.swt.widgets.Event;
+import org.eclipse.swt.widgets.Listener;
+import org.mihalis.opal.utils.SWTGraphicUtil;
+
+/**
+ * Instances of this class are a launcher composed of buttons. When one clicks
+ * on the button, an animation is started and a selection event is fired
+ * <dl>
+ * <dt><b>Styles:</b></dt>
+ * <dd>(none)</dd>
+ * <dt><b>Events:</b></dt>
+ * <dd>Selection</dd>
+ * </dl>
+ */
+public class Launcher extends Composite {
+
+ private final List<LauncherItem> items;
+ private final List<SelectionListener> selectionListeners;
+ private boolean needRedraw;
+ private int selection = -1;
+
+ /**
+ * Constructs a new instance of this class given its parent and a style
+ * value describing its behavior and appearance.
+ * <p>
+ * The style value is either one of the style constants defined in class
+ * <code>SWT</code> which is applicable to instances of this class, or must
+ * be built by <em>bitwise OR</em>'ing together (that is, using the
+ * <code>int</code> "|" operator) two or more of those <code>SWT</code>
+ * style constants. The class description lists the style constants that are
+ * applicable to the class. Style bits are also inherited from superclasses.
+ * </p>
+ *
+ * @param parent a composite control which will be the parent of the new
+ * instance (cannot be null)
+ * @param style the style of control to construct
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the parent is null</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the parent</li>
+ * </ul>
+ *
+ */
+ public Launcher(final Composite parent, final int style) {
+ super(parent, style | SWT.BORDER);
+ this.items = new ArrayList<LauncherItem>();
+ this.selectionListeners = new ArrayList<SelectionListener>();
+ this.needRedraw = true;
+ setBackground(getDisplay().getSystemColor(SWT.COLOR_WHITE));
+
+ this.addListener(SWT.Resize, new Listener() {
+ @Override
+ public void handleEvent(final Event event) {
+ drawLauncher();
+ }
+ });
+
+ this.addListener(SWT.KeyUp, new Listener() {
+
+ @Override
+ public void handleEvent(final Event event) {
+ OnKeyPressed(event);
+ }
+ });
+
+ }
+
+ /**
+ * Draw the launcher
+ */
+ private void drawLauncher() {
+ if (!this.needRedraw) {
+ return;
+ }
+
+ disposePreviousContent();
+ createButtons();
+ pack();
+
+ this.needRedraw = false;
+ }
+
+ /**
+ * Dispose the content before a redraw
+ */
+ private void disposePreviousContent() {
+ for (final Control c : this.getChildren()) {
+ c.dispose();
+ }
+ }
+
+ /**
+ * Create the buttons that will compose the launcher
+ */
+ private void createButtons() {
+ final GridLayout gridLayout = new GridLayout(this.items.size() / 2, true);
+ gridLayout.horizontalSpacing = gridLayout.verticalSpacing = 0;
+ this.setLayout(gridLayout);
+ for (final LauncherItem item : this.items) {
+ final LLabel label = new LLabel(this, SWT.CENTER);
+ label.setText(item.title);
+ label.setImage(SWTGraphicUtil.createImage(item.image));
+ label.setBackground(getDisplay().getSystemColor(SWT.COLOR_WHITE));
+ final GridData gd = new GridData(GridData.FILL, GridData.FILL, true, false);
+ gd.widthHint = 192;
+ gd.heightHint = 220;
+ label.setLayoutData(gd);
+ item.label = label;
+
+ label.addListener(SWT.KeyUp, new Listener() {
+
+ @Override
+ public void handleEvent(final Event event) {
+ OnKeyPressed(event);
+ }
+ });
+
+ label.addListener(SWT.MouseUp, new Listener() {
+
+ @Override
+ public void handleEvent(final Event event) {
+ OnClick(event);
+ }
+ });
+
+ label.addListener(SWT.MouseDoubleClick, new Listener() {
+
+ @Override
+ public void handleEvent(final Event event) {
+ OnDoubleClick(event);
+ }
+ });
+
+ }
+ }
+
+ /**
+ * Code executed when a key is pressed
+ *
+ * @param event Event
+ */
+ private void OnKeyPressed(final Event event) {
+ switch (event.keyCode) {
+ case SWT.ARROW_LEFT:
+ if (this.selection == -1) {
+ this.selection = 0;
+ changeColor(this.selection, true);
+ return;
+ }
+
+ if (this.selection % 2 == 1) {
+ changeColor(this.selection, false);
+ this.selection--;
+ changeColor(this.selection, true);
+ }
+ break;
+ case SWT.ARROW_UP:
+ if (this.selection == -1) {
+ this.selection = 0;
+ changeColor(this.selection, true);
+ return;
+ }
+ if (this.selection >= 2) {
+ changeColor(this.selection, false);
+ this.selection -= 2;
+ changeColor(this.selection, true);
+ }
+ break;
+ case SWT.ARROW_RIGHT:
+ if (this.selection == -1) {
+ this.selection = 0;
+ changeColor(this.selection, true);
+ return;
+ }
+ if (this.selection % 2 == 0) {
+ changeColor(this.selection, false);
+ this.selection++;
+ changeColor(this.selection, true);
+ }
+ break;
+ case SWT.ARROW_DOWN:
+ if (this.selection == -1) {
+ this.selection = 0;
+ changeColor(this.selection, true);
+ return;
+ }
+ if (this.selection <= this.items.size() - 2) {
+ changeColor(this.selection, false);
+ this.selection += 2;
+ changeColor(this.selection, true);
+ }
+ break;
+ case SWT.HOME:
+ changeColor(this.selection, false);
+ this.selection = 0;
+ changeColor(this.selection, true);
+ break;
+ case SWT.END:
+ changeColor(this.selection, false);
+ this.selection = this.items.size() - 1;
+ changeColor(this.selection, true);
+ break;
+ default:
+ break;
+ }
+
+ }
+
+ /**
+ * Code executed when one clicks on the button
+ *
+ * @param event Event
+ */
+ private void OnClick(final Event event) {
+ for (int i = 0; i < this.items.size(); i++) {
+ final LauncherItem item = this.items.get(i);
+ if (item.label != null && item.label.equals(event.widget)) {
+ if (this.selection != i) {
+ changeColor(this.selection, false);
+ this.selection = i;
+ changeColor(this.selection, true);
+ }
+ return;
+ }
+ }
+ }
+
+ /**
+ * Change the background color of a given button
+ *
+ * @param index index of the button
+ * @param isSelected if <code>true</code>, the background is the light
+ * shadow. Otherwise, the background color is white
+ */
+ private void changeColor(final int index, final boolean isSelected) {
+ if (index != -1 && this.items.get(index).label != null) {
+ this.items.get(index).label.setBackground(isSelected ? getDisplay().getSystemColor(SWT.COLOR_WIDGET_LIGHT_SHADOW) : getDisplay().getSystemColor(SWT.COLOR_WHITE));
+ }
+ }
+
+ /**
+ * Code executed when one double-clicks on a button
+ *
+ * @param event Event
+ */
+ private void OnDoubleClick(final Event event) {
+ for (int i = 0; i < this.items.size(); i++) {
+ final LauncherItem item = this.items.get(i);
+ if (item.label != null && item.label.equals(event.widget)) {
+ if (this.selection != i) {
+ changeColor(this.selection, false);
+ this.selection = i;
+ changeColor(this.selection, true);
+ }
+ startAnimation(i, event);
+ return;
+ }
+ }
+ }
+
+ /**
+ * Start the animation for a given button
+ *
+ * @param index index of the selected button
+ * @param event event (propagated to the selection listeners)
+ */
+ private void startAnimation(final int index, final Event event) {
+ final LLabel label = this.items.get(index).label;
+ getDisplay().timerExec(0, new Runnable() {
+
+ @Override
+ public void run() {
+ if (label.incrementAnimation()) {
+ getDisplay().timerExec(20, this);
+ } else {
+ fireSelectionListeners(event);
+ }
+ }
+ });
+
+ }
+
+ /**
+ * Fire the selection listeners
+ *
+ * @param originalEvent mouse event
+ * @return <code>true</code> if the selection could be changed,
+ * <code>false</code> otherwise
+ */
+ private boolean fireSelectionListeners(final Event originalEvent) {
+ for (final SelectionListener listener : this.selectionListeners) {
+ final Event event = new Event();
+
+ event.button = originalEvent.button;
+ event.display = this.getDisplay();
+ event.item = null;
+ event.widget = this;
+ event.data = null;
+ event.time = originalEvent.time;
+ event.x = originalEvent.x;
+ event.y = originalEvent.y;
+
+ final SelectionEvent selEvent = new SelectionEvent(event);
+ listener.widgetSelected(selEvent);
+ if (!selEvent.doit) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Add an item to the launcher
+ *
+ * @param title text associated to this item
+ * @param image image associated to this item
+ */
+ public void addItem(final String title, final String image) {
+ checkWidget();
+ this.items.add(new LauncherItem(title, image));
+ this.needRedraw = true;
+ }
+
+ /**
+ * Adds the listener to the collection of listeners who will be notified
+ * when the control is selected by the user, by sending it one of the
+ * messages defined in the <code>SelectionListener</code> interface.
+ * <p>
+ * <code>widgetSelected</code> is called when the control is selected by the
+ * user. <code>widgetDefaultSelected</code> is not called.
+ * </p>
+ *
+ * @param listener the listener which should be notified
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the listener is null</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ *
+ * @see SelectionListener
+ * @see #removeSelectionListener
+ * @see SelectionEvent
+ */
+ public void addSelectionListener(final SelectionListener listener) {
+ checkWidget();
+ if (listener == null) {
+ SWT.error(SWT.ERROR_NULL_ARGUMENT);
+ }
+ this.selectionListeners.add(listener);
+
+ }
+
+ /**
+ * Removes the listener from the collection of listeners who will be
+ * notified when the control is selected by the user.
+ *
+ * @param listener the listener which should no longer be notified
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the listener is null</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ *
+ * @see SelectionListener
+ * @see #addSelectionListener
+ */
+ public void removeSelectionListener(final SelectionListener listener) {
+ checkWidget();
+ if (listener == null) {
+ SWT.error(SWT.ERROR_NULL_ARGUMENT);
+ }
+ this.selectionListeners.remove(listener);
+ }
+
+ /**
+ * Return the selected button
+ *
+ * @return the index of the selected button
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ *
+ */
+ public int getSelection() {
+ checkWidget();
+ return this.selection;
+ }
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/launcher/LauncherItem.java b/org.tizen.common.externals/src/org/mihalis/opal/launcher/LauncherItem.java
new file mode 100644
index 000000000..bb5dc13db
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/launcher/LauncherItem.java
@@ -0,0 +1,32 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON
+ * 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:
+ * Laurent CARON (laurent.caron at gmail dot com) - Initial implementation and API
+ *******************************************************************************/
+package org.mihalis.opal.launcher;
+
+/**
+ * Instances of this class are POJO to store information handled by the Launcher
+ * widget I could have used a inner class but I prefer this solution :)
+ */
+class LauncherItem {
+ String title;
+ String image;
+ LLabel label;
+
+ /**
+ * Constructor
+ *
+ * @param title text associated to the item
+ * @param image image associated to the item
+ */
+ LauncherItem(final String title, final String image) {
+ this.title = title;
+ this.image = image;
+ }
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/login/LoginDialog.java b/org.tizen.common.externals/src/org/mihalis/opal/login/LoginDialog.java
new file mode 100644
index 000000000..b811971ab
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/login/LoginDialog.java
@@ -0,0 +1,511 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON
+ * 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:
+ * Laurent CARON (laurent.caron at gmail dot com) - initial API and implementation
+ *******************************************************************************/
+package org.mihalis.opal.login;
+
+import java.util.Arrays;
+import java.util.List;
+
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.ModifyEvent;
+import org.eclipse.swt.events.ModifyListener;
+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.Font;
+import org.eclipse.swt.graphics.GC;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.graphics.Path;
+import org.eclipse.swt.graphics.Pattern;
+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.Canvas;
+import org.eclipse.swt.widgets.Combo;
+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.mihalis.opal.opalDialog.Dialog;
+import org.mihalis.opal.utils.ResourceManager;
+import org.mihalis.opal.utils.SWTGraphicUtil;
+
+/**
+ * Instances of this class are Login Dialog box, which is composed of
+ * <p>
+ * <dl>
+ * <dt><b>A login</b></dt>
+ * <dt><b>A password</b></dt>
+ * <dt><b>An image</b></dt>
+ * <dd>(optional)</dd>
+ * <dt><b>A description</b></dt>
+ * <dd>(optional)</dd>
+ * <dt><b>A checkbox "remember the password"</b></dt>
+ * <dd>(optional)</dd>
+ * </dl>
+ * </p>
+ */
+public class LoginDialog {
+ private Image image;
+ private String description;
+ private String login;
+ private String password;
+ private List<String> autorizedLogin;
+ private boolean displayRememberPassword;
+ private boolean rememberPassword;
+ private LoginDialogVerifier verifier;
+
+ private Shell shell;
+ private boolean returnedValue;
+ private Button buttonOk;
+
+ /**
+ * Constructor
+ */
+ public LoginDialog() {
+ this.displayRememberPassword = true;
+ }
+
+ /**
+ * Open the Login box
+ *
+ * @return <code>true</code> if the authentication is OK, <code>false</code>
+ * if the user pressed on cancel.
+ */
+ public boolean open() {
+ if (this.verifier == null) {
+ throw new IllegalArgumentException("Please set a verifier before opening the dialog box");
+ }
+
+ buildDialog();
+ openShell();
+
+ return this.returnedValue;
+ }
+
+ /**
+ * Build the dialog box
+ */
+ private void buildDialog() {
+ buildShell();
+ buildImage();
+ buildDescription();
+ buildLogin();
+ buildPassword();
+ if (this.displayRememberPassword) {
+ buildRememberPassword();
+ }
+ buildButtons();
+ }
+
+ /**
+ * Build the shell
+ */
+ private void buildShell() {
+ this.shell = new Shell(SWT.SYSTEM_MODAL | SWT.TITLE | SWT.BORDER);
+ this.shell.setText(ResourceManager.getLabel(ResourceManager.LOGIN));
+ this.shell.setLayout(new GridLayout(4, false));
+ }
+
+ /**
+ * Build the image on top of the login box. If no image has been set, create
+ * a default image
+ */
+ private void buildImage() {
+ final Canvas canvas = new Canvas(this.shell, SWT.DOUBLE_BUFFERED);
+ final GridData gridData = new GridData(GridData.FILL, GridData.FILL, true, false, 4, 1);
+ gridData.widthHint = 400;
+ gridData.heightHint = 60;
+ canvas.setLayoutData(gridData);
+ canvas.addPaintListener(new PaintListener() {
+
+ @Override
+ public void paintControl(final PaintEvent e) {
+ e.gc.drawImage(LoginDialog.this.image == null ? createDefaultImage(e.width, e.height) : LoginDialog.this.image, 0, 0);
+ }
+ });
+
+ }
+
+ /**
+ * Create a default image. It is a port of the image used by the Login Box
+ * in the project SwingX
+ *
+ * @param w width
+ * @param h height
+ * @return a default image (blue wave)
+ */
+ private Image createDefaultImage(final int w, final int h) {
+ final Display display = Display.getCurrent();
+ final Color backgroundColor = new Color(display, 49, 121, 242);
+ final Color gradientColor1 = new Color(display, 155, 185, 245);
+ final Color gradientColor2 = new Color(display, 53, 123, 242);
+
+ final Image img = new Image(display, w, h);
+ final GC gc = new GC(img);
+ gc.setAdvanced(true);
+ gc.setAntialias(SWT.ON);
+ gc.setBackground(backgroundColor);
+ gc.fillRectangle(0, 0, w, h);
+
+ final Path curveShape = new Path(display);
+ curveShape.moveTo(0, h * .6f);
+ curveShape.cubicTo(w * .167f, h * 1.2f, w * .667f, h * -.5f, w, h * .75f);
+ curveShape.lineTo(w, h);
+ curveShape.lineTo(0, h);
+ curveShape.lineTo(0, h * .8f);
+ curveShape.close();
+
+ final Pattern pattern = new Pattern(display, 0, 0, 1, h * 1.2f, gradientColor1, gradientColor2);
+ gc.setBackgroundPattern(pattern);
+ gc.fillPath(curveShape);
+
+ final Font font = new Font(display, "Arial Bold", 30, SWT.NONE);
+ gc.setFont(font);
+ gc.setForeground(display.getSystemColor(SWT.COLOR_WHITE));
+ final Point textSize = gc.stringExtent(ResourceManager.getLabel(ResourceManager.LOGIN));
+ gc.drawString(ResourceManager.getLabel(ResourceManager.LOGIN), (int) (w * .05f), (h - textSize.y) / 2, true);
+
+ font.dispose();
+ curveShape.dispose();
+ pattern.dispose();
+ backgroundColor.dispose();
+ gradientColor1.dispose();
+ gradientColor2.dispose();
+ gc.dispose();
+ return img;
+ }
+
+ /**
+ * Build the description part of the box
+ */
+ private void buildDescription() {
+ final Label label = new Label(this.shell, SWT.NONE);
+ final GridData gridData = new GridData(GridData.FILL, GridData.BEGINNING, true, false, 4, 1);
+ gridData.verticalIndent = 5;
+ gridData.horizontalIndent = 5;
+ label.setLayoutData(gridData);
+ final Font bold = SWTGraphicUtil.buildFontFrom(label, SWT.BOLD);
+ label.setFont(bold);
+ label.addListener(SWT.Dispose, new Listener() {
+
+ @Override
+ public void handleEvent(final Event event) {
+ SWTGraphicUtil.dispose(bold);
+ }
+ });
+
+ if (this.description == null || this.description.trim().equals("")) {
+ label.setText(" ");
+ } else {
+ label.setText(this.description);
+ }
+ }
+
+ /**
+ * Build the login part of the box
+ */
+ private void buildLogin() {
+ final Label label = new Label(this.shell, SWT.NONE);
+ final GridData gridData = new GridData(GridData.END, GridData.END, false, false, 1, 1);
+ gridData.horizontalIndent = 35;
+ gridData.verticalIndent = 15;
+ label.setLayoutData(gridData);
+ label.setText(ResourceManager.getLabel(ResourceManager.NAME));
+
+ if (this.autorizedLogin != null && !this.autorizedLogin.isEmpty()) {
+ // Combo
+ final Combo combo = new Combo(this.shell, SWT.BORDER | SWT.READ_ONLY);
+
+ combo.setLayoutData(new GridData(GridData.FILL, GridData.END, true, false, 3, 1));
+ for (final String loginToAdd : this.autorizedLogin) {
+ combo.add(loginToAdd);
+ }
+ combo.setText(this.login == null ? "" : this.login);
+ combo.setFocus();
+ combo.addModifyListener(new ModifyListener() {
+
+ @Override
+ public void modifyText(final ModifyEvent e) {
+ LoginDialog.this.login = combo.getText();
+ changeButtonOkState();
+ }
+ });
+ } else {
+ // Text
+ final Text text = new Text(this.shell, SWT.BORDER);
+ text.setText(this.login == null ? "" : this.login);
+ text.setLayoutData(new GridData(GridData.FILL, GridData.END, true, false, 3, 1));
+ text.setFocus();
+ text.addModifyListener(new ModifyListener() {
+
+ @Override
+ public void modifyText(final ModifyEvent e) {
+ LoginDialog.this.login = text.getText();
+ changeButtonOkState();
+ }
+ });
+ }
+
+ }
+
+ /**
+ * Build the password part of the box
+ */
+ private void buildPassword() {
+ final Label label = new Label(this.shell, SWT.NONE);
+ final GridData gridData = new GridData(GridData.END, GridData.CENTER, false, false, 1, 1);
+ gridData.horizontalIndent = 35;
+ label.setLayoutData(gridData);
+ label.setText(ResourceManager.getLabel(ResourceManager.PASSWORD));
+
+ final Text text = new Text(this.shell, SWT.PASSWORD | SWT.BORDER);
+ text.setText(this.password == null ? "" : this.password);
+ text.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false, 3, 1));
+ text.addModifyListener(new ModifyListener() {
+
+ @Override
+ public void modifyText(final ModifyEvent e) {
+ LoginDialog.this.password = text.getText();
+ changeButtonOkState();
+ }
+ });
+
+ }
+
+ /**
+ * Enable/Disable the button when the login and the password is empty (or
+ * not)
+ */
+ private void changeButtonOkState() {
+ final boolean loginEntered = this.login != null && !this.login.trim().equals("");
+ final boolean passwordEntered = this.password != null && !this.password.trim().equals("");
+ this.buttonOk.setEnabled(loginEntered && passwordEntered);
+
+ }
+
+ /**
+ * Build the "remember password" part of the box
+ */
+ private void buildRememberPassword() {
+ final Button checkbox = new Button(this.shell, SWT.CHECK);
+ final GridData gridData = new GridData(GridData.BEGINNING, GridData.CENTER, true, false, 4, 1);
+ gridData.horizontalIndent = 35;
+ checkbox.setLayoutData(gridData);
+ checkbox.setText(ResourceManager.getLabel(ResourceManager.REMEMBER_PASSWORD));
+ checkbox.setSelection(this.rememberPassword);
+
+ }
+
+ /**
+ * Build the buttons
+ */
+ private void buildButtons() {
+ this.buttonOk = new Button(this.shell, SWT.PUSH);
+ final GridData gdOk = new GridData(GridData.END, GridData.CENTER, true, false, 3, 1);
+ gdOk.verticalIndent = 60;
+ gdOk.minimumWidth = 80;
+ this.buttonOk.setLayoutData(gdOk);
+ this.buttonOk.setText(ResourceManager.getLabel(ResourceManager.OK));
+ this.buttonOk.setEnabled(false);
+
+ this.buttonOk.addSelectionListener(new SelectionAdapter() {
+
+ /**
+ * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
+ */
+ @Override
+ public void widgetSelected(final SelectionEvent selectionEvent) {
+ try {
+ LoginDialog.this.verifier.authenticate(LoginDialog.this.login, LoginDialog.this.password);
+ LoginDialog.this.returnedValue = true;
+ LoginDialog.this.shell.dispose();
+ } catch (final Exception e) {
+ Dialog.error(ResourceManager.getLabel(ResourceManager.LOGIN_FAILED), e.getMessage());
+ for (final Control control : LoginDialog.this.shell.getChildren()) {
+ if (control instanceof Text || control instanceof Combo) {
+ control.setFocus();
+ break;
+ }
+ }
+
+ }
+ }
+
+ });
+
+ final Button buttonCancel = new Button(this.shell, SWT.PUSH);
+ final GridData gdCancel = new GridData(GridData.FILL, GridData.CENTER, false, false);
+ gdCancel.widthHint = 80;
+ gdCancel.verticalIndent = 60;
+ buttonCancel.setLayoutData(gdCancel);
+ buttonCancel.setText(ResourceManager.getLabel(ResourceManager.CANCEL));
+ buttonCancel.addSelectionListener(new SelectionAdapter() {
+
+ /**
+ * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
+ */
+ @Override
+ public void widgetSelected(final SelectionEvent e) {
+ LoginDialog.this.returnedValue = false;
+ LoginDialog.this.shell.dispose();
+ }
+
+ });
+
+ }
+
+ /**
+ * Open the shell
+ */
+ private void openShell() {
+ this.shell.setDefaultButton(this.buttonOk);
+ this.shell.pack();
+ this.shell.open();
+ SWTGraphicUtil.centerShell(this.shell);
+
+ while (!this.shell.isDisposed()) {
+ if (!this.shell.getDisplay().readAndDispatch()) {
+ this.shell.getDisplay().sleep();
+ }
+ }
+ }
+
+ // ------------- Getters & Setters
+ /**
+ * @return the image
+ */
+ public Image getImage() {
+ return this.image;
+ }
+
+ /**
+ * @return the description
+ */
+ public String getDescription() {
+ return this.description;
+ }
+
+ /**
+ * @return the login
+ */
+ public String getLogin() {
+ return this.login == null ? null : this.login.trim();
+ }
+
+ /**
+ * @return the password
+ */
+ public String getPassword() {
+ return this.password == null ? null : this.password.trim();
+ }
+
+ /**
+ * @return the list of autorized logins
+ */
+ public List<String> getAutorizedLogin() {
+ return this.autorizedLogin;
+ }
+
+ /**
+ * @return <code>true</code> if the checkbox "remember the password" is
+ * displayed, <code>false</code> otherwise
+ */
+ public boolean isDisplayRememberPassword() {
+ return this.displayRememberPassword;
+ }
+
+ /**
+ * @return <code>true</code> if the checkbox "remember the password" is
+ * checked, <code>false</code> otherwise
+ */
+ public boolean isRememberPassword() {
+ return this.rememberPassword;
+ }
+
+ /**
+ * @return the verifier associated to this box
+ */
+ public LoginDialogVerifier getVerifier() {
+ return this.verifier;
+ }
+
+ /**
+ * @param image the image to set
+ */
+ public void setImage(final Image image) {
+ this.image = image;
+ }
+
+ /**
+ * @param description the description to set
+ */
+ public void setDescription(final String description) {
+ this.description = description;
+ }
+
+ /**
+ * @param login the login to set
+ */
+ public void setLogin(final String login) {
+ this.login = login;
+ }
+
+ /**
+ * @param password the password to set
+ */
+ public void setPassword(final String password) {
+ this.password = password;
+ }
+
+ /**
+ * @param autorizedLogin the list of autorized logins to set
+ */
+ public void setAutorizedLogin(final List<String> autorizedLogin) {
+ this.autorizedLogin = autorizedLogin;
+ }
+
+ /**
+ * @param autorizedLogin the list of autorized logins to set
+ */
+ public void setAutorizedLogin(final String... autorizedLogin) {
+ this.autorizedLogin = Arrays.asList(autorizedLogin);
+ }
+
+ /**
+ * @param displayRememberPassword if <code>true</code>, the checkbox
+ * "remember the password" is displayed
+ */
+ public void setDisplayRememberPassword(final boolean displayRememberPassword) {
+ this.displayRememberPassword = displayRememberPassword;
+ }
+
+ /**
+ * @param rememberPassword if <code>true</code>, the checkbox
+ * "remember the password" is selected
+ */
+ public void setRememberPassword(final boolean rememberPassword) {
+ this.rememberPassword = rememberPassword;
+ }
+
+ /**
+ * @param verifier the verifier to set
+ */
+ public void setVerifier(final LoginDialogVerifier verifier) {
+ this.verifier = verifier;
+ }
+
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/login/LoginDialogVerifier.java b/org.tizen.common.externals/src/org/mihalis/opal/login/LoginDialogVerifier.java
new file mode 100644
index 000000000..14ec22cb8
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/login/LoginDialogVerifier.java
@@ -0,0 +1,29 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON
+ * 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:
+ * Laurent CARON (laurent.caron at gmail dot com) - initial API and implementation
+ *******************************************************************************/
+package org.mihalis.opal.login;
+
+/**
+ * This interface describes a verifier for the LoginDialogWidget
+ */
+public interface LoginDialogVerifier {
+ /**
+ * Check if the couple login/password is correct
+ *
+ * @param login login entered by the user
+ * @param password password entered by the user
+ * @throws Exception if the couple login/password is wrong. The description
+ * of the exception contains the error message that is gonna be
+ * displayed. For instance, an implementation can throw the
+ * exception *
+ * <code>new Exception("Unable to connect to the LDAP Server")</code>
+ */
+ void authenticate(String login, String password) throws Exception;
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/multiChoice/MultiChoice.java b/org.tizen.common.externals/src/org/mihalis/opal/multiChoice/MultiChoice.java
new file mode 100755
index 000000000..3a5cb0e6b
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/multiChoice/MultiChoice.java
@@ -0,0 +1,1195 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON.
+ * 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:
+ * Laurent CARON (laurent.caron@gmail.com) - initial API and implementation
+ *******************************************************************************/
+
+package org.mihalis.opal.multiChoice;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Set;
+
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.SWTException;
+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.GC;
+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.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.mihalis.opal.utils.SimpleSelectionAdapter;
+
+/**
+ * The MultiChoice class represents a selectable user interface object that
+ * combines a read-only text-field and a set of checkboxes.
+ *
+ * <p>
+ * Note that although this class is a subclass of <code>Composite</code>, it
+ * does not make sense to add children to it, or set a layout on it.
+ * </p>
+ * <dl>
+ * <dt><b>Styles:</b>
+ * <dd>NONE</dd>
+ * <dt><b>Events:</b>
+ * <dd>Selection</dd>
+ * </dl>
+ *
+ * @param <T> Class of objects represented by this widget
+ */
+public class MultiChoice<T> extends Composite {
+
+ private Label text;
+ private Button arrow;
+ private Shell popup;
+ private Listener listener, filter;
+ private int numberOfColumns = 2;
+ private List<T> elements;
+ private Set<T> selection;
+ private List<Button> checkboxes;
+ private boolean hasFocus;
+ private MultiChoiceSelectionListener<T> selectionListener;
+ private T lastModified;
+ private Color foreground, background;
+ private Font font;
+ private String separator;
+
+ /**
+ * Constructs a new instance of this class given its parent.
+ *
+ * @param parent a widget which will be the parent of the new instance
+ * (cannot be null)
+ * @param style not used
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the parent is null</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the parent</li>
+ * </ul>
+ */
+ public MultiChoice(final Composite parent, final int style) {
+ this(parent, style, null);
+ }
+
+ /**
+ * Constructs a new instance of this class given its parent.
+ *
+ * @param parent a widget which will be the parent of the new instance
+ * (cannot be null)
+ * @param style not used
+ * @param elements list of elements displayed by this widget
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the parent is null</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the parent</li>
+ * </ul>
+ */
+ public MultiChoice(final Composite parent, final int style, final List<T> elements) {
+ super(parent, style);
+
+ final GridLayout gridLayout = new GridLayout(2, false);
+ gridLayout.horizontalSpacing = gridLayout.verticalSpacing = gridLayout.marginWidth = gridLayout.marginHeight = 0;
+ this.setLayout(gridLayout);
+
+ this.text = new Label(this, SWT.SINGLE | SWT.READ_ONLY | SWT.BORDER);
+ this.text.setBackground(this.getDisplay().getSystemColor(SWT.COLOR_LIST_BACKGROUND));
+ this.text.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, false));
+
+ this.arrow = new Button(this, SWT.ARROW | SWT.RIGHT);
+ this.arrow.setLayoutData(new GridData(GridData.FILL, GridData.FILL, false, false));
+
+ this.listener = new Listener() {
+ @Override
+ public void handleEvent(final Event event) {
+ if (MultiChoice.this.popup == event.widget) {
+ popupEvent(event);
+ return;
+ }
+
+ if (MultiChoice.this.arrow == event.widget) {
+ buttonEvent(event);
+ return;
+ }
+
+ if (MultiChoice.this == event.widget) {
+ multiChoiceEvent(event);
+ return;
+ }
+
+ if (getShell() == event.widget) {
+ getDisplay().asyncExec(new Runnable() {
+ @Override
+ public void run() {
+ if (isDisposed()) {
+ return;
+ }
+ handleFocus(SWT.FocusOut);
+ }
+ });
+ }
+ }
+ };
+
+ final int[] multiChoiceEvent = { SWT.Dispose, SWT.Move, SWT.Resize };
+ for (int i = 0; i < multiChoiceEvent.length; i++) {
+ this.addListener(multiChoiceEvent[i], this.listener);
+ }
+
+ final int[] buttonEvents = { SWT.Selection, SWT.FocusIn };
+ for (int i = 0; i < buttonEvents.length; i++) {
+ this.arrow.addListener(buttonEvents[i], this.listener);
+ }
+
+ this.filter = new Listener() {
+ @Override
+ public void handleEvent(final Event event) {
+ final Shell shell = ((Control) event.widget).getShell();
+ if (shell == MultiChoice.this.getShell()) {
+ handleFocus(SWT.FocusOut);
+ }
+ }
+ };
+
+ this.selection = new LinkedHashSet<T>();
+ this.elements = elements;
+ this.separator = ",";
+
+ createPopup();
+ setLabel();
+ }
+
+ /**
+ * Adds the argument to the end of the receiver's list.
+ *
+ * @param values new item
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the string is null</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void add(final T value) {
+ checkWidget();
+ if (value == null) {
+ SWT.error(SWT.ERROR_NULL_ARGUMENT);
+ }
+
+ if (this.elements == null) {
+ this.elements = new ArrayList<T>();
+ }
+ this.elements.add(value);
+ refresh();
+ }
+
+ /**
+ * Adds the argument to the receiver's list at the given zero-relative
+ * index.
+ *
+ * @param values new item
+ * @param index the index for the item
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the string is null</li>
+ * <li>ERROR_INVALID_RANGE - if the index is not between 0
+ * and the number of elements in the list minus 1 (inclusive)
+ * </li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void add(final T value, final int index) {
+ checkWidget();
+ checkNullElement();
+ if (value == null) {
+ SWT.error(SWT.ERROR_NULL_ARGUMENT);
+ }
+
+ checkRange(index);
+
+ this.elements.add(index, value);
+ refresh();
+ }
+
+ /**
+ * Adds the argument to the end of the receiver's list.
+ *
+ * @param values new items
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the string is null</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void addAll(final List<T> values) {
+ checkWidget();
+ if (values == null) {
+ SWT.error(SWT.ERROR_NULL_ARGUMENT);
+ }
+
+ if (this.elements == null) {
+ this.elements = new ArrayList<T>();
+ }
+ this.elements.addAll(values);
+ refresh();
+ }
+
+ /**
+ * Adds the argument to the end of the receiver's list.
+ *
+ * @param values new items
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the string is null</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void addAll(final T[] values) {
+ checkWidget();
+ if (values == null) {
+ SWT.error(SWT.ERROR_NULL_ARGUMENT);
+ }
+ if (this.elements == null) {
+ this.elements = new ArrayList<T>();
+ }
+ for (final T value : values) {
+ this.elements.add(value);
+ }
+ refresh();
+ }
+
+ /**
+ * Returns the item at the given, zero-relative index in the receiver's
+ * list. Throws an exception if the index is out of range.
+ *
+ * @param index the index of the item to return
+ * @return the item at the given index
+ *
+ * @exception NullPointerException if there is no item in the receiver
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_INVALID_RANGE - if the index is not between 0
+ * and the number of elements in the list minus 1 (inclusive)
+ * </li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public T getItem(final int index) {
+ checkWidget();
+ checkNullElement();
+ checkRange(index);
+
+ return this.elements.get(index);
+ }
+
+ /**
+ * Returns the number of items contained in the receiver's list.
+ *
+ * @return the number of items
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public int getItemCount() {
+ checkWidget();
+ if (this.elements == null) {
+ return 0;
+ }
+
+ return this.elements.size();
+
+ }
+
+ /**
+ * Returns the list of items in the receiver's list.
+ * <p>
+ * Note: This is not the actual structure used by the receiver to maintain
+ * its list of items, so modifying the array will not affect the receiver.
+ * </p>
+ *
+ * @return the items in the receiver's list
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public List<T> getItems() {
+ checkWidget();
+ if (this.elements == null) {
+ return null;
+ }
+ return new ArrayList<T>(this.elements);
+ }
+
+ /**
+ * Removes the item from the receiver's list at the given zero-relative
+ * index.
+ *
+ * @param index the index for the item
+ * @exception NullPointerException if there is no item in the receiver
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_INVALID_RANGE - if the index is not between 0
+ * and the number of elements in the list minus 1 (inclusive)
+ * </li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void removeAt(final int index) {
+ checkWidget();
+ checkNullElement();
+ checkRange(index);
+ final Object removedElement = this.elements.remove(index);
+ this.selection.remove(removedElement);
+ refresh();
+ }
+
+ /**
+ * Searches the receiver's list starting at the first item until an item is
+ * found that is equal to the argument, and removes that item from the list.
+ *
+ * @param object the item to remove
+ * @exception NullPointerException if there is no item in the receiver
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the object is null</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void remove(final T object) {
+ if (object == null) {
+ SWT.error(SWT.ERROR_NULL_ARGUMENT);
+ }
+ checkWidget();
+ checkNullElement();
+ this.elements.remove(object);
+ this.selection.remove(object);
+ refresh();
+ }
+
+ /**
+ * Remove all items of the receiver
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void removeAll() {
+ checkWidget();
+ checkNullElement();
+ if (this.elements != null) {
+ this.elements.clear();
+ }
+ this.selection.clear();
+ refresh();
+ }
+
+ /**
+ * Sets the selection of the receiver. If the item was already selected, it
+ * remains selected.
+ *
+ * @param selection the new selection
+ * @exception NullPointerException if there is no item in the receiver
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the selection is null</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+
+ public void setSelection(final Set<T> selection) {
+ checkWidget();
+ checkNullElement();
+ if (selection == null) {
+ SWT.error(SWT.ERROR_NULL_ARGUMENT);
+ }
+ this.selection = selection;
+ updateSelection();
+ }
+
+ /**
+ * Selects all selected items in the receiver's list.
+ *
+ * @exception NullPointerException if there is no item in the receiver
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void selectAll() {
+ checkWidget();
+ checkNullElement();
+ this.selection.addAll(this.elements);
+ updateSelection();
+ }
+
+ /**
+ * Selects the item at the given zero-relative index in the receiver's list.
+ * If the item at the index was already selected, it remains selected.
+ *
+ * @param index the index of the item to select
+ * @exception NullPointerException if there is no item in the receiver
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_INVALID_RANGE - if the index is not between 0
+ * and the number of elements in the list minus 1 (inclusive)
+ * </li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void selectAt(final int index) {
+ checkWidget();
+ checkNullElement();
+ checkRange(index);
+ this.selection.add(this.elements.get(index));
+ updateSelection();
+ }
+
+ /**
+ * Selects an item the receiver's list. If the item was already selected, it
+ * remains selected.
+ *
+ * @param index the index of the item to select
+ * @exception NullPointerException if there is no item in the receiver
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the selection is null</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void select(final T value) {
+ checkWidget();
+ checkNullElement();
+ if (!this.elements.contains(value)) {
+ throw new IllegalArgumentException("Value not present in the widget");
+ }
+ this.selection.add(value);
+ updateSelection();
+ }
+
+ /**
+ * Selects items in the receiver. If the items were already selected, they
+ * remain selected.
+ *
+ * @param index the indexes of the items to select
+ * @exception NullPointerException if there is no item in the receiver
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the selection is null</li>
+ * <li>ERROR_INVALID_RANGE - if the index is not between 0
+ * and the number of elements in the list minus 1 (inclusive)
+ * </li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void setSelectedIndex(final int[] index) {
+ checkWidget();
+ checkNullElement();
+ for (final int i : index) {
+ checkRange(i);
+ this.selection.add(this.elements.get(i));
+ }
+ updateSelection();
+ }
+
+ /**
+ * Returns the zero-relative indices of the items which are currently
+ * selected in the receiver. The order of the indices is unspecified. The
+ * array is empty if no items are selected.
+ * <p>
+ * Note: This is not the actual structure used by the receiver to maintain
+ * its selection, so modifying the array will not affect the receiver.
+ * </p>
+ *
+ * @return the array of indices of the selected items
+ * @exception NullPointerException if there is no item in the receiver
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public int[] getSelectedIndex() {
+ checkWidget();
+ checkNullElement();
+ final List<Integer> selectedIndex = new ArrayList<Integer>();
+ for (int i = 0; i < this.elements.size(); i++) {
+ if (this.selection.contains(this.elements.get(i))) {
+ selectedIndex.add(i);
+ }
+ }
+
+ final int[] returned = new int[selectedIndex.size()];
+ for (int i = 0; i < selectedIndex.size(); i++) {
+ returned[i] = selectedIndex.get(i);
+ }
+
+ return returned;
+ }
+
+ /**
+ * Returns an array of <code>Object</code>s that are currently selected in
+ * the receiver. The order of the items is unspecified. An empty array
+ * indicates that no items are selected.
+ * <p>
+ * Note: This is not the actual structure used by the receiver to maintain
+ * its selection, so modifying the array will not affect the receiver.
+ * </p>
+ *
+ * @return an array representing the selection
+ * @exception NullPointerException if there is no item in the receiver
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public List<T> getSelection() {
+ checkWidget();
+ checkNullElement();
+ return new ArrayList<T>(this.selection);
+ }
+
+ /**
+ * Deselects the item at the given zero-relative index in the receiver's
+ * list. If the item at the index was already deselected, it remains
+ * deselected. Indices that are out of range are ignored.
+ *
+ * @param index the index of the item to deselect
+ * @exception NullPointerException if there is no item in the receiver
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_INVALID_RANGE - if the index is not between 0
+ * and the number of elements in the list minus 1 (inclusive)
+ * </li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void deselectAt(final int index) {
+ checkWidget();
+ checkNullElement();
+
+ if (index < 0 || index >= this.elements.size()) {
+ SWT.error(SWT.ERROR_INVALID_RANGE);
+ }
+
+ this.selection.remove(index);
+ updateSelection();
+ }
+
+ /**
+ * Deselects the item in the receiver's list. If the item at the index was
+ * already deselected, it remains deselected.
+ *
+ * @param value the item to deselect
+ * @exception NullPointerException if there is no item in the receiver
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_INVALID_RANGE - if the index is not between 0
+ * and the number of elements in the list minus 1 (inclusive)
+ * </li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void deselect(final T value) {
+ checkWidget();
+ checkNullElement();
+ this.selection.remove(value);
+ updateSelection();
+ }
+
+ /**
+ * Deselects all items in the receiver's list.
+ *
+ * @param value the item to deselect
+ * @exception NullPointerException if there is no item in the receiver
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void deselectAll() {
+ checkWidget();
+ checkNullElement();
+ this.selection.clear();
+ updateSelection();
+ }
+
+ /**
+ * @return the number of columns
+ */
+ public int getNumberOfColumns() {
+ checkWidget();
+ return this.numberOfColumns;
+ }
+
+ /**
+ * @param numberOfColumns the number of columns
+ */
+ public void setNumberOfColumns(final int numberOfColumns) {
+ checkWidget();
+ this.numberOfColumns = numberOfColumns;
+ this.popup.dispose();
+ this.popup = null;
+ createPopup();
+ }
+
+ /**
+ * @return the separator used in the text field. Default value is ","
+ */
+ public String getSeparator() {
+ return this.separator;
+ }
+
+ /**
+ * @param separator the new value of the separator
+ */
+ public void setSeparator(final String separator) {
+ this.separator = separator;
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Control#getForeground()
+ */
+ @Override
+ public Color getForeground() {
+ return this.foreground;
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Control#setForeground(org.eclipse.swt.graphics.Color)
+ */
+ @Override
+ public void setForeground(final Color foreground) {
+ this.foreground = foreground;
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Control#getBackground()
+ */
+ @Override
+ public Color getBackground() {
+ return this.background;
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Control#setBackground(org.eclipse.swt.graphics.Color)
+ */
+ @Override
+ public void setBackground(final Color background) {
+ this.background = background;
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Control#getFont()
+ */
+ @Override
+ public Font getFont() {
+ return this.font;
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Control#setFont(org.eclipse.swt.graphics.Font)
+ */
+ @Override
+ public void setFont(final Font font) {
+ this.font = font;
+ }
+
+ /**
+ * Refresh the widget (after the add of a new element for example)
+ */
+ public void refresh() {
+ checkWidget();
+ this.popup.dispose();
+ this.popup = null;
+ createPopup();
+ updateSelection();
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Composite#computeSize(int, int, boolean)
+ */
+ @Override
+ public Point computeSize(final int wHint, final int hHint, final boolean changed) {
+ checkWidget();
+ int width = 0, height = 0;
+
+ final GC gc = new GC(this.text);
+ final int spacer = gc.stringExtent(" ").x;
+ final int textWidth = gc.stringExtent(this.text.getText()).x;
+ gc.dispose();
+ final Point textSize = this.text.computeSize(SWT.DEFAULT, SWT.DEFAULT, changed);
+ final Point arrowSize = this.arrow.computeSize(SWT.DEFAULT, SWT.DEFAULT, changed);
+ final int borderWidth = getBorderWidth();
+
+ height = Math.max(textSize.y, arrowSize.y);
+ width = textWidth + 2 * spacer + arrowSize.x + 2 * borderWidth;
+ if (wHint != SWT.DEFAULT) {
+ width = wHint;
+ }
+ if (hHint != SWT.DEFAULT) {
+ height = hHint;
+ }
+ return new Point(width + 2 * borderWidth, height + 2 * borderWidth);
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Control#setEnabled(boolean)
+ */
+ @Override
+ public void setEnabled(final boolean enabled) {
+ checkWidget();
+ this.arrow.setEnabled(enabled);
+ this.text.setEnabled(enabled);
+ super.setEnabled(enabled);
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Control#setToolTipText(java.lang.String)
+ */
+ @Override
+ public void setToolTipText(final String txt) {
+ checkWidget();
+ this.text.setToolTipText(txt);
+ }
+
+ /**
+ * @return the selection listener
+ */
+ public SelectionListener getSelectionListener() {
+ checkWidget();
+ return this.selectionListener;
+ }
+
+ /**
+ * @param selectionListener the new selection listener
+ */
+ public void setSelectionListener(final MultiChoiceSelectionListener<T> selectionListener) {
+ checkWidget();
+ this.selectionListener = selectionListener;
+ refresh();
+ }
+
+ /**
+ * Update the selection
+ */
+ public void updateSelection() {
+ checkWidget();
+ if (isDisposed()) {
+ return;
+ }
+
+ if (this.popup == null || this.popup.isDisposed()) {
+ return;
+ }
+
+ for (int i = 0; i < this.checkboxes.size(); i++) {
+ final Button currentButton = this.checkboxes.get(i);
+ if (!currentButton.isDisposed()) {
+ final Object content = currentButton.getData();
+ currentButton.setSelection(this.selection.contains(content));
+ }
+ }
+ setLabel();
+
+ }
+
+ /**
+ * @return the last modified item
+ */
+ T getLastModified() {
+ return this.lastModified;
+ }
+
+ /**
+ * @return the popup
+ */
+ Shell getPopup() {
+ return this.popup;
+ }
+
+ /**
+ * Create the popup that contains all checkboxes
+ */
+ private void createPopup() {
+ this.popup = new Shell(getShell(), SWT.NO_TRIM | SWT.ON_TOP);
+ this.popup.setLayout(new GridLayout(this.numberOfColumns, true));
+
+ final int[] popupEvents = { SWT.Close, SWT.Paint, SWT.Deactivate, SWT.Dispose };
+ for (int i = 0; i < popupEvents.length; i++) {
+ this.popup.addListener(popupEvents[i], this.listener);
+ }
+
+ if (this.elements == null) {
+ return;
+ }
+
+ this.checkboxes = new ArrayList<Button>(this.elements.size());
+ for (final T o : this.elements) {
+ final Button checkBoxButton = new Button(this.popup, SWT.CHECK);
+
+ if (this.font != null) {
+ checkBoxButton.setFont(this.font);
+ }
+ if (this.foreground != null) {
+ checkBoxButton.setForeground(this.foreground);
+ }
+ if (this.background != null) {
+ checkBoxButton.setBackground(this.background);
+ }
+
+ checkBoxButton.setData(o);
+ checkBoxButton.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, false, false));
+ checkBoxButton.setText(o.toString());
+ checkBoxButton.addSelectionListener(new SimpleSelectionAdapter() {
+ @Override
+ public void handle(final SelectionEvent e) {
+ if (checkBoxButton.getSelection()) {
+ MultiChoice.this.selection.add(o);
+ } else {
+ MultiChoice.this.selection.remove(o);
+ }
+ MultiChoice.this.lastModified = o;
+ setLabel();
+ }
+ });
+
+ if (this.selectionListener != null) {
+ checkBoxButton.addSelectionListener(this.selectionListener);
+ }
+
+ checkBoxButton.setSelection(this.selection.contains(o));
+ this.checkboxes.add(checkBoxButton);
+ }
+ this.popup.layout();
+ }
+
+ /**
+ * Set the value of the label, based on the selected items
+ */
+ private void setLabel() {
+ if (this.checkboxes == null) {
+ this.text.setText("");
+ return;
+ }
+
+ final List<String> values = new ArrayList<String>();
+ for (final Button current : this.checkboxes) {
+ if (current.getSelection()) {
+ values.add(current.getText());
+ }
+ }
+
+ final StringBuffer sb = new StringBuffer();
+ final Iterator<String> it = values.iterator();
+ while (it.hasNext()) {
+ sb.append(it.next());
+ if (it.hasNext()) {
+ sb.append(this.separator);
+ }
+ }
+
+ this.text.setText(sb.toString());
+ }
+
+ /**
+ * Handle a focus event
+ *
+ * @param type type of the event to handle
+ */
+ private void handleFocus(final int type) {
+ if (isDisposed()) {
+ return;
+ }
+ switch (type) {
+ case SWT.FocusIn: {
+ if (this.hasFocus) {
+ return;
+ }
+ this.hasFocus = true;
+ final Shell shell = getShell();
+ shell.removeListener(SWT.Deactivate, this.listener);
+ shell.addListener(SWT.Deactivate, this.listener);
+ final Display display = getDisplay();
+ display.removeFilter(SWT.FocusIn, this.filter);
+ display.addFilter(SWT.FocusIn, this.filter);
+ final Event e = new Event();
+ notifyListeners(SWT.FocusIn, e);
+ break;
+ }
+ case SWT.FocusOut: {
+ if (!this.hasFocus) {
+ return;
+ }
+ final Control focusControl = getDisplay().getFocusControl();
+ if (focusControl == this.arrow) {
+ return;
+ }
+ this.hasFocus = false;
+ final Shell shell = getShell();
+ shell.removeListener(SWT.Deactivate, this.listener);
+ final Display display = getDisplay();
+ display.removeFilter(SWT.FocusIn, this.filter);
+ final Event e = new Event();
+ notifyListeners(SWT.FocusOut, e);
+ break;
+ }
+ default:
+ break;
+ }
+ }
+
+ /**
+ * Handle a multichoice event
+ *
+ * @param event event to handle
+ */
+ private void multiChoiceEvent(final Event event) {
+ switch (event.type) {
+ case SWT.Dispose:
+ if (this.popup != null && !this.popup.isDisposed()) {
+ this.popup.dispose();
+ }
+ final Shell shell = getShell();
+ shell.removeListener(SWT.Deactivate, this.listener);
+ final Display display = getDisplay();
+ display.removeFilter(SWT.FocusIn, this.filter);
+ this.popup = null;
+ this.arrow = null;
+ break;
+ case SWT.Move:
+ dropDown(false);
+ break;
+ case SWT.Resize:
+ if (isDropped()) {
+ dropDown(false);
+ }
+ break;
+ default:
+ break;
+ }
+
+ }
+
+ /**
+ * Handle a button event
+ *
+ * @param event event to hangle
+ */
+ private void buttonEvent(final Event event) {
+ switch (event.type) {
+ case SWT.FocusIn: {
+ handleFocus(SWT.FocusIn);
+ break;
+ }
+ case SWT.Selection: {
+ dropDown(!isDropped());
+ break;
+ }
+ default:
+ break;
+ }
+ }
+
+ /**
+ * @return <code>true</code> if the popup is visible and not dropped,
+ * <code>false</code> otherwise
+ */
+ private boolean isDropped() {
+ return !this.popup.isDisposed() && this.popup.getVisible();
+ }
+
+ /**
+ * Handle a popup event
+ *
+ * @param event event to handle
+ */
+ private void popupEvent(final Event event) {
+ switch (event.type) {
+ case SWT.Paint:
+ final Rectangle listRect = this.popup.getBounds();
+ final Color black = getDisplay().getSystemColor(SWT.COLOR_BLACK);
+ event.gc.setForeground(black);
+ event.gc.drawRectangle(0, 0, listRect.width - 1, listRect.height - 1);
+ break;
+ case SWT.Close:
+ event.doit = false;
+ dropDown(false);
+ break;
+ case SWT.Deactivate:
+ dropDown(false);
+ break;
+ case SWT.Dispose:
+ if (this.checkboxes != null) {
+ this.checkboxes.clear();
+ }
+ this.checkboxes = null;
+ break;
+ default:
+ break;
+ }
+
+ }
+
+ /**
+ * Display/Hide the popup window
+ *
+ * @param drop if <code>true</code>, displays the popup window. If
+ * <code>false</code>, hide the popup window
+ */
+ private void dropDown(final boolean drop) {
+ if (drop == isDropped()) {
+ return;
+ }
+
+ if (!drop) {
+ this.popup.setVisible(false);
+ if (!isDisposed()) {
+ this.text.setFocus();
+ }
+ return;
+ }
+
+ if (getShell() != this.popup.getParent()) {
+ this.popup.dispose();
+ this.popup = null;
+ createPopup();
+ }
+
+ final Point arrowRect = this.arrow.toDisplay(this.arrow.getSize().x - 5, this.arrow.getSize().y + this.arrow.getBorderWidth() - 3);
+ int x = arrowRect.x;
+ int y = arrowRect.y;
+
+ final Rectangle displayRect = getMonitor().getClientArea();
+ final Rectangle parentRect = getDisplay().map(getParent(), null, getBounds());
+ this.popup.pack();
+ final int width = this.popup.getBounds().width;
+ final int height = this.popup.getBounds().height;
+
+ if (y + height > displayRect.y + displayRect.height) {
+ y = parentRect.y - height;
+ }
+ if (x + width > displayRect.x + displayRect.width) {
+ x = displayRect.x + displayRect.width - width;
+ }
+
+ this.popup.setLocation(x, y);
+ this.popup.setVisible(true);
+ this.popup.setFocus();
+ }
+
+ /**
+ * Check if the elements attributes is not null
+ *
+ * @exception NullPointerException if there is no item in the receiver
+ */
+ private void checkNullElement() {
+ if (this.elements == null) {
+ throw new NullPointerException("There is no element associated to this widget");
+ }
+ }
+
+ /**
+ * @param index
+ * @throws NullPointerException
+ * @throws IllegalArgumentException
+ */
+ private void checkRange(final int index) throws NullPointerException {
+ checkNullElement();
+ if (index < 0 || index >= this.elements.size()) {
+ SWT.error(SWT.ERROR_INVALID_RANGE);
+ }
+ }
+
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/multiChoice/MultiChoiceSelectionListener.java b/org.tizen.common.externals/src/org/mihalis/opal/multiChoice/MultiChoiceSelectionListener.java
new file mode 100644
index 000000000..ac5ca79c4
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/multiChoice/MultiChoiceSelectionListener.java
@@ -0,0 +1,56 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON.
+ * 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:
+ * Laurent CARON (laurent.caron@gmail.com) - initial API and implementation
+ *******************************************************************************/
+
+package org.mihalis.opal.multiChoice;
+
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.events.SelectionListener;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Shell;
+
+/**
+ * Classes which extend this abstract class provide methods that deal with the
+ * events that are generated when selection occurs in a MultiChoice control.
+ */
+public abstract class MultiChoiceSelectionListener<T> implements SelectionListener {
+ private final MultiChoice<T> parent;
+
+ public MultiChoiceSelectionListener(final MultiChoice<T> parent) {
+ this.parent = parent;
+ }
+
+ /**
+ * @see org.eclipse.swt.events.SelectionListener#widgetSelected(org.eclipse.swt.events.SelectionEvent)
+ */
+ @Override
+ public final void widgetSelected(final SelectionEvent e) {
+ final Button button = (Button) e.widget;
+ handle(this.parent, this.parent.getLastModified(), button.getSelection(), this.parent.getPopup());
+ }
+
+ /**
+ * @see org.eclipse.swt.events.SelectionListener#widgetDefaultSelected(org.eclipse.swt.events.SelectionEvent)
+ */
+ @Override
+ public final void widgetDefaultSelected(final SelectionEvent inutile) {
+ }
+
+ /**
+ * This method contains the code that is called when the selection has
+ * changed
+ *
+ * @param parent MultiChoice responsible of the event
+ * @param receiver Object modified
+ * @param selected If <code>true</code>, the check box has been checked
+ * @param popup the popup window that contains all checkboxes
+ */
+ public abstract void handle(MultiChoice<T> parent, T receiver, boolean selected, Shell popup);
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/notify/Notifier.java b/org.tizen.common.externals/src/org/mihalis/opal/notify/Notifier.java
new file mode 100644
index 000000000..014a19cec
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/notify/Notifier.java
@@ -0,0 +1,347 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON
+ * 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:
+ * Laurent CARON (laurent.caron at gmail dot com) - initial API and implementation
+ *******************************************************************************/
+package org.mihalis.opal.notify;
+
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.custom.StyledText;
+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.Rectangle;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+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.mihalis.opal.notify.NotifierColorsFactory.NotifierTheme;
+import org.mihalis.opal.utils.SWTGraphicUtil;
+
+/**
+ * This class provides a notifier window, which is a window that appears in the
+ * bottom of the screen and slides.
+ */
+public class Notifier {
+ private static final int FONT_SIZE = 10;
+ private static final int MAX_DURATION_FOR_OPENING = 500;
+ private static final int DISPLAY_TIME = 4500;
+
+ private static final int FADE_TIMER = 50;
+ private static final int FADE_OUT_STEP = 8;
+
+ private static final int STEP = 5;
+
+ /**
+ * Starts a notification. A window will appear in the bottom of the screen,
+ * then will disappear after 4.5 s
+ *
+ * @param title the title of the popup window
+ * @param text the text of the notification
+ *
+ */
+ public static void notify(final String title, final String text) {
+ notify(null, title, text, NotifierTheme.YELLOW_THEME);
+ }
+
+ /**
+ * Starts a notification. A window will appear in the bottom of the screen,
+ * then will disappear after 4.5 s
+ *
+ * @param image the image to display (if <code>null</code>, a default image
+ * is displayed)
+ * @param title the title of the popup window
+ * @param text the text of the notification
+ *
+ */
+ public static void notify(final Image image, final String title, final String text) {
+ notify(image, title, text, NotifierTheme.YELLOW_THEME);
+
+ }
+
+ /**
+ * Starts a notification. A window will appear in the bottom of the screen,
+ * then will disappear after 4.5 s
+ *
+ * @param title the title of the popup window
+ * @param text the text of the notification
+ * @param theme the graphical theme. If <code>null</code>, the yellow theme
+ * is used
+ *
+ * @see NotifierTheme
+ */
+ public static void notify(final String title, final String text, final NotifierTheme theme) {
+ notify(null, title, text, theme);
+ }
+
+ /**
+ * Starts a notification. A window will appear in the bottom of the screen,
+ * then will disappear after 4.5 s
+ *
+ * @param image the image to display (if <code>null</code>, a default image
+ * is displayed)
+ * @param title the title of the popup window
+ * @param text the text of the notification
+ * @param theme the graphical theme. If <code>null</code>, the yellow theme
+ * is used
+ *
+ * @see NotifierTheme
+ */
+ public static void notify(final Image image, final String title, final String text, final NotifierTheme theme) {
+ final Shell shell = createNotificationWindow(image, title, text, NotifierColorsFactory.getColorsForTheme(theme));
+ makeShellAppears(shell);
+
+ }
+
+ /**
+ * Creates a notification window
+ *
+ * @param image image. If <code>null</code>, a default image is used
+ * @param title title, the title of the window
+ * @param text text of the window
+ * @param colors color set
+ * @return the notification window as a shell object
+ */
+ private static Shell createNotificationWindow(final Image image, final String title, final String text, final NotifierColors colors) {
+ final Shell shell = new Shell(SWT.NO_TRIM | SWT.NO_FOCUS);
+ shell.setLayout(new GridLayout(2, false));
+ shell.setBackgroundMode(SWT.INHERIT_FORCE);
+
+ createTitle(shell, title, colors);
+ createImage(shell, image);
+ createText(shell, text, colors);
+ createBackground(shell, colors);
+ createCloseAction(shell);
+
+ shell.addListener(SWT.Dispose, new Listener() {
+
+ @Override
+ public void handleEvent(final Event event) {
+ colors.dispose();
+ }
+ });
+
+ shell.pack();
+ shell.setMinimumSize(320, 100);
+ return shell;
+ }
+
+ /**
+ * Creates the title part of the window
+ *
+ * @param shell the window
+ * @param title the title
+ * @param colors the color set
+ */
+ private static void createTitle(final Shell shell, final String title, final NotifierColors colors) {
+ final Label titleLabel = new Label(shell, SWT.NONE);
+ final GridData gdLabel = new GridData(GridData.BEGINNING, GridData.BEGINNING, true, false, 2, 1);
+ gdLabel.horizontalIndent = 40;
+ titleLabel.setLayoutData(gdLabel);
+ final Color titleColor = colors.titleColor;
+ titleLabel.setForeground(titleColor);
+
+ final Font titleFont = SWTGraphicUtil.buildFontFrom(titleLabel, SWT.BOLD, FONT_SIZE);
+ titleLabel.setFont(titleFont);
+ titleLabel.setText(title);
+ SWTGraphicUtil.dispose(shell, titleFont);
+ }
+
+ /**
+ * Creates the image part of the window
+ *
+ * @param shell the window
+ * @param image the image
+ */
+ private static void createImage(final Shell shell, final Image image) {
+ final Label labelImage = new Label(shell, SWT.NONE);
+ final GridData gdImage = new GridData(GridData.CENTER, GridData.BEGINNING, false, true);
+ gdImage.horizontalIndent = 10;
+ labelImage.setLayoutData(gdImage);
+ if (image == null) {
+ final Image temp = SWTGraphicUtil.createImage("images/information.png");
+ labelImage.setImage(temp);
+ SWTGraphicUtil.dispose(shell, temp);
+ } else {
+ labelImage.setImage(image);
+ }
+
+ }
+
+ /**
+ * Creates the text part of the window
+ *
+ * @param shell the window
+ * @param text the text
+ * @param colors the color set
+ */
+ private static void createText(final Shell shell, final String text, final NotifierColors colors) {
+ final StyledText textLabel = new StyledText(shell, SWT.WRAP | SWT.READ_ONLY);
+ final GridData gdText = new GridData(GridData.FILL, GridData.FILL, true, true);
+ gdText.horizontalIndent = 15;
+ textLabel.setLayoutData(gdText);
+ textLabel.setEnabled(false);
+ final Font textFont = SWTGraphicUtil.buildFontFrom(textLabel, SWT.NONE, 10);
+ textLabel.setFont(textFont);
+
+ final Color textColor = colors.textColor;
+ textLabel.setForeground(textColor);
+
+ textLabel.setText("<html><body>" + text + "</body></html>");
+ SWTGraphicUtil.applyHTMLFormating(textLabel);
+
+ SWTGraphicUtil.dispose(shell, textFont);
+
+ }
+
+ /**
+ * Creates the background of the window
+ *
+ * @param shell the window
+ * @param colors the color set of the window
+ */
+ private static void createBackground(final Shell shell, final NotifierColors colors) {
+ shell.addListener(SWT.Resize, new Listener() {
+
+ @Override
+ public void handleEvent(final Event event) {
+ final Rectangle rect = shell.getClientArea();
+ final Image newImage = new Image(Display.getDefault(), Math.max(1, rect.width), rect.height);
+ final GC gc = new GC(newImage);
+ gc.setAntialias(SWT.ON);
+
+ final Color borderColor = colors.borderColor;
+ final Color fillColor1 = colors.leftColor;
+ final Color fillColor2 = colors.rightColor;
+
+ gc.setBackground(borderColor);
+ gc.fillRoundRectangle(0, 0, rect.width, rect.height, 8, 8);
+
+ gc.setBackground(fillColor1);
+ gc.fillRoundRectangle(1, 1, rect.width - 2, rect.height - 2, 8, 8);
+
+ gc.setBackground(fillColor2);
+ gc.fillRoundRectangle(30, 1, rect.width - 32, rect.height - 2, 8, 8);
+ gc.fillRectangle(30, 1, 10, rect.height - 2);
+
+ final Image closeImage = SWTGraphicUtil.createImage("images/close.png");
+ gc.drawImage(closeImage, rect.width - 21, 13);
+
+ gc.dispose();
+ closeImage.dispose();
+
+ shell.setBackgroundImage(newImage);
+
+ }
+ });
+
+ }
+
+ /**
+ * @param shell shell that will appear
+ */
+ private static void makeShellAppears(final Shell shell) {
+ if (shell == null || shell.isDisposed()) {
+ return;
+ }
+
+ final Rectangle clientArea = Display.getDefault().getActiveShell().getMonitor().getClientArea();
+ final int startX = clientArea.x + clientArea.width - shell.getSize().x;
+
+ final int stepForPosition = MAX_DURATION_FOR_OPENING / shell.getSize().y * STEP;
+ final int stepForAlpha = STEP * 255 / shell.getSize().y;
+
+ final int lastPosition = clientArea.y + clientArea.height - shell.getSize().y;
+
+ shell.setAlpha(0);
+ shell.setLocation(startX, clientArea.y + clientArea.height);
+ shell.open();
+
+ shell.getDisplay().timerExec(stepForPosition, new Runnable() {
+
+ @Override
+ public void run() {
+
+ if (shell == null || shell.isDisposed()) {
+ return;
+ }
+
+ shell.setLocation(startX, shell.getLocation().y - STEP);
+ shell.setAlpha(shell.getAlpha() + stepForAlpha);
+ if (shell.getLocation().y >= lastPosition) {
+ shell.getDisplay().timerExec(stepForPosition, this);
+ } else {
+ shell.setAlpha(255);
+ Display.getDefault().timerExec(DISPLAY_TIME, fadeOut(shell, false));
+ }
+ }
+ });
+
+ }
+
+ /**
+ * @param shell shell that will disappear
+ * @param fast if true, the fading is much faster
+ * @return a runnable
+ */
+ private static Runnable fadeOut(final Shell shell, final boolean fast) {
+ return new Runnable() {
+
+ @Override
+ public void run() {
+ if (shell == null || shell.isDisposed()) {
+ return;
+ }
+
+ int currentAlpha = shell.getAlpha();
+ currentAlpha -= FADE_OUT_STEP * (fast ? 8 : 1);
+
+ if (currentAlpha <= 0) {
+ shell.setAlpha(0);
+ shell.dispose();
+ return;
+ }
+
+ shell.setAlpha(currentAlpha);
+
+ Display.getDefault().timerExec(FADE_TIMER, this);
+
+ }
+
+ };
+ }
+
+ /**
+ * Add a listener to the shell in order to handle the clicks on the close
+ * button
+ *
+ * @param shell associated shell
+ */
+ private static void createCloseAction(final Shell shell) {
+ shell.addListener(SWT.MouseUp, new Listener() {
+
+ @Override
+ public void handleEvent(final Event event) {
+ final Rectangle rect = shell.getClientArea();
+ final int xUpperLeftCorner = rect.width - 21;
+ final int yUpperLeftCorner = 13;
+
+ if (event.x >= xUpperLeftCorner && event.x <= xUpperLeftCorner + 8 && event.y >= yUpperLeftCorner && event.y <= yUpperLeftCorner + 8) {
+ Display.getDefault().timerExec(0, fadeOut(shell, true));
+ }
+
+ }
+ });
+
+ }
+
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/notify/NotifierColors.java b/org.tizen.common.externals/src/org/mihalis/opal/notify/NotifierColors.java
new file mode 100644
index 000000000..ddde66343
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/notify/NotifierColors.java
@@ -0,0 +1,34 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON
+ * 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:
+ * Laurent CARON (laurent.caron at gmail dot com) - initial API and implementation
+ *******************************************************************************/
+package org.mihalis.opal.notify;
+
+import org.eclipse.swt.graphics.Color;
+import org.mihalis.opal.utils.SWTGraphicUtil;
+
+/**
+ * This class is a simple POJO that holds colors used by the Notifier widget
+ *
+ */
+class NotifierColors {
+ Color titleColor;
+ Color textColor;
+ Color borderColor;
+ Color leftColor;
+ Color rightColor;
+
+ void dispose() {
+ SWTGraphicUtil.dispose(this.titleColor);
+ SWTGraphicUtil.dispose(this.borderColor);
+ SWTGraphicUtil.dispose(this.leftColor);
+ SWTGraphicUtil.dispose(this.rightColor);
+ SWTGraphicUtil.dispose(this.textColor);
+ }
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/notify/NotifierColorsFactory.java b/org.tizen.common.externals/src/org/mihalis/opal/notify/NotifierColorsFactory.java
new file mode 100644
index 000000000..18390636b
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/notify/NotifierColorsFactory.java
@@ -0,0 +1,66 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON 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: Laurent CARON (laurent.caron at gmail dot com) - initial API
+ * and implementation
+ *******************************************************************************/
+
+package org.mihalis.opal.notify;
+
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.graphics.Color;
+import org.eclipse.swt.widgets.Display;
+
+/**
+ * This class creates the colors associated to a given theme
+ *
+ */
+public class NotifierColorsFactory {
+
+ public enum NotifierTheme {
+ YELLOW_THEME, GRAY_THEME, BLUE_THEME
+ };
+
+ /**
+ * Constructor
+ */
+ private NotifierColorsFactory() {
+
+ }
+
+ /**
+ * @param theme a theme for the notifier widget
+ * @return the color set for the given theme
+ */
+ static NotifierColors getColorsForTheme(final NotifierTheme theme) {
+ final NotifierColors colors = new NotifierColors();
+ switch (theme) {
+ case BLUE_THEME:
+ colors.textColor = new Color(Display.getDefault(), 4, 64, 140);
+ colors.titleColor = Display.getDefault().getSystemColor(SWT.COLOR_BLACK);
+ colors.borderColor = new Color(Display.getDefault(), 153, 188, 232);
+ colors.leftColor = new Color(Display.getDefault(), 210, 225, 244);
+ colors.rightColor = new Color(Display.getDefault(), 182, 207, 238);
+ break;
+ case GRAY_THEME:
+ colors.textColor = Display.getDefault().getSystemColor(SWT.COLOR_BLACK);
+ colors.titleColor = Display.getDefault().getSystemColor(SWT.COLOR_DARK_RED);
+ colors.borderColor = new Color(Display.getDefault(), 208, 208, 208);
+ colors.leftColor = new Color(Display.getDefault(), 255, 255, 255);
+ colors.rightColor = new Color(Display.getDefault(), 208, 208, 208);
+ break;
+ default:
+ colors.textColor = Display.getDefault().getSystemColor(SWT.COLOR_BLACK);
+ colors.titleColor = Display.getDefault().getSystemColor(SWT.COLOR_BLACK);
+ colors.borderColor = new Color(Display.getDefault(), 218, 178, 85);
+ colors.leftColor = new Color(Display.getDefault(), 220, 220, 160);
+ colors.rightColor = new Color(Display.getDefault(), 255, 255, 191);
+ break;
+ }
+ return colors;
+ }
+
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/opalDialog/ChoiceItem.java b/org.tizen.common.externals/src/org/mihalis/opal/opalDialog/ChoiceItem.java
new file mode 100644
index 000000000..cff7959c1
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/opalDialog/ChoiceItem.java
@@ -0,0 +1,56 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON
+ * 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:
+ * Laurent CARON (laurent.caron at gmail dot com) - Initial implementation and API
+ * Eugene Ryzhikov - Author of the Oxbow Project (http://code.google.com/p/oxbow/) - Inspiration
+ *******************************************************************************/
+package org.mihalis.opal.opalDialog;
+
+/**
+ * Instances of this class are choice items used by the choice widget
+ */
+public class ChoiceItem {
+
+ private final String instruction;
+ private final String text;
+
+ /**
+ * Constructor
+ *
+ * @param instruction instruction of the choice
+ * @param text text displayed under the instruction
+ */
+ public ChoiceItem(final String instruction, final String text) {
+ this.instruction = instruction;
+ this.text = text;
+ }
+
+ /**
+ * Constructor
+ *
+ * @param instruction instruction
+ */
+ public ChoiceItem(final String instruction) {
+ this(instruction, null);
+ }
+
+ /**
+ * @return the instruction
+ */
+ public String getInstruction() {
+ return this.instruction;
+ }
+
+ /**
+ * @return the text
+ */
+ public String getText() {
+ return this.text;
+ };
+
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/opalDialog/ChoiceWidget.java b/org.tizen.common.externals/src/org/mihalis/opal/opalDialog/ChoiceWidget.java
new file mode 100644
index 000000000..24bcf992c
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/opalDialog/ChoiceWidget.java
@@ -0,0 +1,301 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON
+ * 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:
+ * Laurent CARON (laurent.caron at gmail dot com) - Initial implementation and API
+ * Eugene Ryzhikov - Author of the Oxbow Project (http://code.google.com/p/oxbow/) - Inspiration
+ *******************************************************************************/
+package org.mihalis.opal.opalDialog;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.SWTException;
+import org.eclipse.swt.events.DisposeEvent;
+import org.eclipse.swt.events.DisposeListener;
+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.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.Label;
+import org.eclipse.swt.widgets.Listener;
+import org.eclipse.swt.widgets.Widget;
+import org.mihalis.opal.utils.SWTGraphicUtil;
+
+/**
+ * Instance of this class are composite that represents a choice like in Windows
+ * Vista and Seven. It is composed of a green arrow, instruction and text
+ */
+public class ChoiceWidget extends Composite {
+ private Image oldImage;
+
+ private ChoiceItem choiceItem;
+
+ private Label image;
+ private Label instruction;
+ private Label text;
+
+ private final List<SelectionListener> selectionListeners;
+
+ private boolean selection;
+ private boolean insideComposite;
+ private boolean insideImage;
+ private boolean insideText;
+ private boolean insideInstruction;
+
+ /**
+ * Constructs a new instance of this class given its parent and a style
+ * value describing its behavior and appearance.
+ * <p>
+ * The style value is either one of the style constants defined in class
+ * <code>SWT</code> which is applicable to instances of this class, or must
+ * be built by <em>bitwise OR</em>'ing together (that is, using the
+ * <code>int</code> "|" operator) two or more of those <code>SWT</code>
+ * style constants. The class description lists the style constants that are
+ * applicable to the class. Style bits are also inherited from superclasses.
+ * </p>
+ *
+ * @param parent a widget which will be the parent of the new instance
+ * (cannot be null)
+ * @param style the style of widget to construct
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the parent is null</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the parent</li>
+ * </ul>
+ *
+ * @see Composite#Composite(Composite, int)
+ * @see SWT#NO_BACKGROUND
+ * @see SWT#NO_FOCUS
+ * @see SWT#NO_MERGE_PAINTS
+ * @see SWT#NO_REDRAW_RESIZE
+ * @see SWT#NO_RADIO_GROUP
+ * @see SWT#EMBEDDED
+ * @see SWT#DOUBLE_BUFFERED
+ * @see Widget#getStyle
+ */
+ public ChoiceWidget(final Composite parent, final int style) {
+ super(parent, style);
+
+ this.setBackgroundMode(SWT.INHERIT_DEFAULT);
+ this.setLayout(new GridLayout(2, false));
+
+ buildGreenArrow();
+ buildInstruction();
+ buildText();
+ addMouseListeners();
+
+ this.selectionListeners = new ArrayList<SelectionListener>();
+ this.addListener(SWT.Resize, new Listener() {
+ @Override
+ public void handleEvent(final Event event) {
+ drawComposite();
+ }
+ });
+
+ }
+
+ /**
+ * Build the green arrow
+ */
+ private void buildGreenArrow() {
+ this.image = new Label(this, SWT.NONE);
+ this.image.setImage(SWTGraphicUtil.createImage("images/arrowGreenRight.png"));
+ this.image.setBackground(getDisplay().getSystemColor(SWT.COLOR_WHITE));
+ this.image.setLayoutData(new GridData(GridData.CENTER, GridData.BEGINNING, false, false, 1, 2));
+ }
+
+ /**
+ * Build the instruction
+ */
+ private void buildInstruction() {
+ final Color color = new Color(Display.getCurrent(), 35, 107, 178);
+ addDisposeListener(new DisposeListener() {
+
+ @Override
+ public void widgetDisposed(final DisposeEvent e) {
+ SWTGraphicUtil.dispose(color);
+ }
+ });
+ this.instruction = new Label(this, SWT.NONE);
+ this.instruction.setForeground(color);
+ this.instruction.setLayoutData(new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false));
+ }
+
+ /**
+ * Build the panel
+ */
+ private void buildText() {
+ this.text = new Label(this, SWT.NONE);
+ this.text.setForeground(getDisplay().getSystemColor(SWT.COLOR_BLACK));
+ this.text.setLayoutData(new GridData(GridData.BEGINNING, GridData.BEGINNING, false, true));
+ }
+
+ /**
+ * Add mouse listeners
+ */
+ private void addMouseListeners() {
+ final Listener mouseEnterListener = new Listener() {
+
+ @Override
+ public void handleEvent(final Event event) {
+
+ if (event.widget.equals(ChoiceWidget.this)) {
+ ChoiceWidget.this.insideComposite = true;
+ }
+
+ if (event.widget.equals(ChoiceWidget.this.image)) {
+ ChoiceWidget.this.insideImage = true;
+ }
+ if (event.widget.equals(ChoiceWidget.this.text)) {
+ ChoiceWidget.this.insideText = true;
+ }
+ if (event.widget.equals(ChoiceWidget.this.instruction)) {
+ ChoiceWidget.this.insideInstruction = true;
+ }
+
+ drawComposite();
+ }
+ };
+
+ final Listener mouseExitListener = new Listener() {
+
+ @Override
+ public void handleEvent(final Event event) {
+ if (event.widget.equals(ChoiceWidget.this)) {
+ ChoiceWidget.this.insideComposite = false;
+ }
+
+ if (event.widget.equals(ChoiceWidget.this.image)) {
+ ChoiceWidget.this.insideImage = false;
+ }
+ if (event.widget.equals(ChoiceWidget.this.text)) {
+ ChoiceWidget.this.insideText = false;
+ }
+ if (event.widget.equals(ChoiceWidget.this.instruction)) {
+ ChoiceWidget.this.insideInstruction = false;
+ }
+ drawComposite();
+ }
+ };
+
+ final Listener mouseClickListener = new Listener() {
+
+ @Override
+ public void handleEvent(final Event event) {
+ for (final SelectionListener selectionListener : ChoiceWidget.this.selectionListeners) {
+ selectionListener.widgetSelected(null);
+ }
+ }
+ };
+
+ addListener(SWT.MouseEnter, mouseEnterListener);
+ this.image.addListener(SWT.MouseEnter, mouseEnterListener);
+ this.text.addListener(SWT.MouseEnter, mouseEnterListener);
+ this.instruction.addListener(SWT.MouseEnter, mouseEnterListener);
+
+ addListener(SWT.MouseExit, mouseExitListener);
+ this.image.addListener(SWT.MouseExit, mouseExitListener);
+ this.text.addListener(SWT.MouseExit, mouseExitListener);
+ this.instruction.addListener(SWT.MouseExit, mouseExitListener);
+
+ addListener(SWT.MouseUp, mouseClickListener);
+ this.image.addListener(SWT.MouseUp, mouseClickListener);
+ this.text.addListener(SWT.MouseUp, mouseClickListener);
+ this.instruction.addListener(SWT.MouseUp, mouseClickListener);
+ }
+
+ /**
+ * Draw the composite
+ */
+ private void drawComposite() {
+
+ final Rectangle rect = this.getClientArea();
+ final Image newImage = new Image(getDisplay(), Math.max(1, rect.width), Math.max(1, rect.height));
+
+ final GC gc = new GC(newImage);
+
+ final boolean inside = this.insideComposite || this.insideImage || this.insideInstruction || this.insideText;
+
+ if (!inside && !this.selection) {
+ gc.setBackground(getDisplay().getSystemColor(SWT.COLOR_WHITE));
+ gc.setForeground(getDisplay().getSystemColor(SWT.COLOR_WHITE));
+ gc.drawRectangle(rect.x, rect.y, rect.width, rect.height);
+ } else {
+ // The mouse is over OR the item is selected
+ final Color gradientColor = inside ? new Color(getDisplay(), 220, 231, 243) : new Color(getDisplay(), 241, 241, 241);
+ final Color borderColor = inside ? new Color(getDisplay(), 35, 107, 178) : new Color(getDisplay(), 192, 192, 192);
+
+ gc.setForeground(getDisplay().getSystemColor(SWT.COLOR_WHITE));
+ gc.setBackground(gradientColor);
+ gc.fillGradientRectangle(rect.x, rect.y, rect.width, rect.height, true);
+
+ gc.setForeground(borderColor);
+ gc.drawRoundRectangle(rect.x, rect.y, rect.width - 1, rect.height - 1, 2, 2);
+
+ gradientColor.dispose();
+ borderColor.dispose();
+ }
+ gc.dispose();
+
+ this.setBackgroundImage(newImage);
+ if (this.oldImage != null) {
+ this.oldImage.dispose();
+ }
+ this.oldImage = newImage;
+
+ }
+
+ /**
+ * @return the current choice item
+ */
+ public ChoiceItem getChoiceItem() {
+ return this.choiceItem;
+ }
+
+ /**
+ * @param choiceItem the choiceItem to set
+ */
+ public void setChoiceItem(final ChoiceItem choiceItem) {
+ this.choiceItem = choiceItem;
+ this.instruction.setText(choiceItem.getInstruction());
+ this.text.setText(choiceItem.getText());
+ }
+
+ /**
+ * Add a selection listener to this widget
+ *
+ * @param listener listener to add
+ */
+ public void addSelectionListener(final SelectionListener listener) {
+ this.selectionListeners.add(listener);
+ }
+
+ /**
+ * Remove a selection listener
+ *
+ * @param listener listener to remove
+ */
+ public void removeSelectionListener(final SelectionListener listener) {
+ this.selectionListeners.remove(listener);
+ }
+
+ public void setSelection(final boolean selection) {
+ this.selection = selection;
+ }
+
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/opalDialog/Dialog.java b/org.tizen.common.externals/src/org/mihalis/opal/opalDialog/Dialog.java
new file mode 100644
index 000000000..914ab1258
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/opalDialog/Dialog.java
@@ -0,0 +1,480 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON
+ * 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:
+ * Laurent CARON (laurent.caron at gmail dot com) - Initial implementation and API
+ * Eugene Ryzhikov - Author of the Oxbow Project (http://code.google.com/p/oxbow/) - Inspiration
+ *******************************************************************************/
+package org.mihalis.opal.opalDialog;
+
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.graphics.Point;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.Shell;
+import org.mihalis.opal.utils.ResourceManager;
+
+/**
+ * Instances of this class are dialog box
+ */
+public class Dialog {
+
+ /**
+ * Types of opal dialog
+ */
+ public enum OpalDialogType {
+ CLOSE, YES_NO, OK, OK_CANCEL, SELECT_CANCEL, NO_BUTTON, OTHER, NONE
+ }
+
+ private String title;
+ OpalDialogType buttonType;
+ private final MessageArea messageArea;
+ private final FooterArea footerArea;
+ final Shell shell;
+
+ private int minimumWidth = 300;
+ private int minimumHeight = 150;
+
+ /**
+ * Constructor
+ */
+ public Dialog() {
+ this(null);
+ }
+
+ /**
+ * Constructor
+ *
+ * @param parent parent shell
+ */
+ public Dialog(final Shell parent) {
+ if (parent == null) {
+ this.shell = new Shell(Display.getCurrent(), SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL);
+ } else {
+ this.shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL);
+ }
+ this.messageArea = new MessageArea(this);
+ this.footerArea = new FooterArea(this);
+ }
+
+ /**
+ * Show the dialog box
+ *
+ * @return the index of the selected button
+ */
+ public int show() {
+ final GridLayout gd = new GridLayout(1, true);
+ gd.horizontalSpacing = 0;
+ gd.verticalSpacing = 0;
+ gd.marginHeight = gd.marginWidth = 0;
+ this.shell.setLayout(gd);
+
+ this.messageArea.render();
+ this.footerArea.render();
+ if (this.title != null) {
+ this.shell.setText(this.title);
+ }
+ pack();
+ this.shell.open();
+
+ final Display display = this.shell.getDisplay();
+ while (!this.shell.isDisposed()) {
+ if (!display.readAndDispatch()) {
+ display.sleep();
+ }
+ }
+
+ return this.footerArea.getSelectedButton();
+ }
+
+ /**
+ * Close the dialog box
+ */
+ public void close() {
+ this.shell.dispose();
+
+ }
+
+ /**
+ * Compute the size of the shell
+ */
+ void pack() {
+
+ final Point preferredSize = this.shell.computeSize(SWT.DEFAULT, SWT.DEFAULT);
+
+ if (preferredSize.x < this.minimumWidth) {
+
+ preferredSize.x = this.minimumWidth;
+ }
+ if (preferredSize.y < this.minimumHeight) {
+ preferredSize.y = this.minimumHeight;
+ }
+
+ final Point displaySize = new Point(this.shell.getDisplay().getBounds().width, this.shell.getDisplay().getBounds().height);
+
+ final int centerX = (displaySize.x - preferredSize.x) / 2;
+ final int centerY = (displaySize.y - preferredSize.y) / 2;
+
+ this.shell.setBounds(centerX, centerY, preferredSize.x, preferredSize.y);
+ }
+
+ // ------------------------------------------- Convenient methods
+
+ /**
+ * Create a dialog box that asks a question
+ *
+ * @param title title of the dialog box
+ * @param text text of the question
+ * @param defaultValue default value of the input
+ * @return the value typed by the user
+ */
+ public static String ask(final String title, final String text, final String defaultValue) {
+ return ask(null, title, text, defaultValue);
+ }
+
+ /**
+ * Create a dialog box that asks a question
+ *
+ * @shell parent shell
+ * @param title title of the dialog box
+ * @param text text of the question
+ * @param defaultValue default value of the input
+ * @return the value typed by the user
+ */
+ public static String ask(final Shell shell, final String title, final String text, final String defaultValue) {
+ final Dialog dialog = new Dialog(shell);
+ dialog.setTitle(ResourceManager.getLabel(ResourceManager.INPUT));
+ dialog.getMessageArea().setTitle(title).setText(text).setIcon(Display.getCurrent().getSystemImage(SWT.ICON_INFORMATION)).addTextBox(defaultValue);
+ dialog.setButtonType(OpalDialogType.OK_CANCEL);
+ if (dialog.show() == 0) {
+ return dialog.getMessageArea().getTextBoxValue();
+ } else {
+ return null;
+ }
+ }
+
+ /**
+ * Create a dialog box that displays an error message
+ *
+ * @param title title of the dialog box
+ * @param errorMessage Error message
+ */
+ public static void error(final String title, final String errorMessage) {
+ error(null, title, errorMessage);
+ }
+
+ /**
+ * Create a dialog box that displays an error message
+ *
+ * @param shell parent shell
+ * @param title title of the dialog box
+ * @param errorMessage Error message
+ */
+ public static void error(final Shell shell, final String title, final String errorMessage) {
+ final Dialog dialog = new Dialog(shell);
+ dialog.setTitle(ResourceManager.getLabel(ResourceManager.APPLICATION_ERROR));
+ dialog.getMessageArea().setTitle(title).//
+ setText(errorMessage).//
+ setIcon(Display.getCurrent().getSystemImage(SWT.ICON_ERROR));
+ dialog.setButtonType(OpalDialogType.OK);
+ dialog.show();
+ }
+
+ /**
+ * Create a dialog box that inform the user
+ *
+ * @param title title of the dialog box
+ * @param text text to display
+ */
+ public static void inform(final String title, final String text) {
+ inform(null, title, text);
+ }
+
+ /**
+ * Create a dialog box that inform the user
+ *
+ * @param shell parent shell
+ * @param title title of the dialog box
+ * @param text text to display
+ */
+ public static void inform(final Shell shell, final String title, final String text) {
+ final Dialog dialog = new Dialog(shell);
+ dialog.setTitle(ResourceManager.getLabel(ResourceManager.INFORMATION));
+ dialog.getMessageArea().setTitle(title).setText(text).setIcon(Display.getCurrent().getSystemImage(SWT.ICON_INFORMATION));
+ dialog.setButtonType(OpalDialogType.CLOSE);
+ dialog.show();
+
+ }
+
+ /**
+ * Create a dialog box that asks the user a confirmation
+ *
+ * @param title title of the dialog box
+ * @param text text to display
+ * @return <code>true</code> if the user confirmed, <code>false</code>
+ * otherwise
+ */
+ public static boolean isConfirmed(final String title, final String text) {
+ return isConfirmed(null, title, text, -1);
+ }
+
+ /**
+ * Create a dialog box that asks the user a confirmation
+ *
+ * @param shell parent shell
+ * @param title title of the dialog box
+ * @param text text to display
+ * @return <code>true</code> if the user confirmed, <code>false</code>
+ * otherwise
+ */
+ public static boolean isConfirmed(final Shell shell, final String title, final String text) {
+ return isConfirmed(shell, title, text, -1);
+ }
+
+ /**
+ * Create a dialog box that asks the user a confirmation. The button "yes"
+ * is not enabled before timer seconds
+ *
+ * @param title title of the dialog box
+ * @param text text to display
+ * @param timer number of seconds before enabling the yes button
+ * @return <code>true</code> if the user confirmed, <code>false</code>
+ * otherwise
+ */
+ public static boolean isConfirmed(final String title, final String text, final int timer) {
+ return isConfirmed(null, title, text, timer);
+ }
+
+ /**
+ * Create a dialog box that asks the user a confirmation. The button "yes"
+ * is not enabled before timer seconds
+ *
+ * @param shell parent shell
+ * @param title title of the dialog box
+ * @param text text to display
+ * @param timer number of seconds before enabling the yes button
+ * @return <code>true</code> if the user confirmed, <code>false</code>
+ * otherwise
+ */
+ public static boolean isConfirmed(final Shell shell, final String title, final String text, final int timer) {
+ final Dialog dialog = new Dialog(shell);
+ dialog.setTitle(ResourceManager.getLabel(ResourceManager.WARNING));
+ dialog.getMessageArea().setTitle(title).setText(text).setIcon(Display.getCurrent().getSystemImage(SWT.ICON_WARNING));
+
+ dialog.getFooterArea().setTimer(timer).setTimerIndexButton(0);
+ dialog.setButtonType(OpalDialogType.YES_NO);
+ return dialog.show() == 0;
+ }
+
+ /**
+ * Create a dialog box with a radio choice
+ *
+ * @param title title of the dialog box
+ * @param text text to display
+ * @param defaultSelection index of the default selection
+ * @param values values to display
+ * @return the index of the selection
+ */
+ public static int radioChoice(final String title, final String text, final int defaultSelection, final String... values) {
+ return radioChoice(null, title, text, defaultSelection, values);
+ }
+
+ /**
+ * Create a dialog box with a radio choice
+ *
+ * @param shell parent shell
+ * @param title title of the dialog box
+ * @param text text to display
+ * @param defaultSelection index of the default selection
+ * @param values values to display
+ * @return the index of the selection
+ */
+ public static int radioChoice(final Shell shell, final String title, final String text, final int defaultSelection, final String... values) {
+ final Dialog dialog = new Dialog(shell);
+ dialog.setTitle(ResourceManager.getLabel(ResourceManager.CHOICE));
+ dialog.getMessageArea().setTitle(title).setText(text).setIcon(Display.getCurrent().getSystemImage(SWT.ICON_QUESTION)).addRadioButtons(defaultSelection, values);
+ dialog.setButtonType(OpalDialogType.SELECT_CANCEL);
+ if (dialog.show() == 0) {
+ return dialog.getMessageArea().getRadioChoice();
+ } else {
+ return -1;
+ }
+ }
+
+ /**
+ * Display a dialog box with an exception
+ *
+ * @param exception exception to display
+ */
+ public static void showException(final Throwable exception) {
+ final Dialog dialog = new Dialog();
+ dialog.setTitle(ResourceManager.getLabel(ResourceManager.EXCEPTION));
+
+ final String msg = exception.getMessage();
+ final String className = exception.getClass().getName();
+ final boolean noMessage = msg == null || msg.trim().length() == 0;
+
+ dialog.getMessageArea().setTitle(noMessage ? className : msg).//
+ setText(noMessage ? "" : className).//
+ setIcon(Display.getCurrent().getSystemImage(SWT.ICON_ERROR)).//
+ setException(exception);
+
+ dialog.getFooterArea().setExpanded(true);
+
+ dialog.setButtonType(OpalDialogType.CLOSE);
+ dialog.show();
+ }
+
+ /**
+ * Create a dialog box with a choice
+ *
+ * @param title title of the dialog box
+ * @param text text to display
+ * @param defaultSelection index of the default selection
+ * @param items items to display
+ * @return the index of the selected value
+ */
+ public static int choice(final String title, final String text, final int defaultSelection, final ChoiceItem... items) {
+ return choice(null, title, text, defaultSelection, items);
+ }
+
+ /**
+ * Create a dialog box with a choice
+ *
+ * @param shell parent shell
+ * @param title title of the dialog box
+ * @param text text to display
+ * @param defaultSelection index of the default selection
+ * @param items items to display
+ * @return the index of the selected value
+ */
+ public static int choice(final Shell shell, final String title, final String text, final int defaultSelection, final ChoiceItem... items) {
+ final Dialog dialog = new Dialog(shell);
+ dialog.setTitle(ResourceManager.getLabel(ResourceManager.CHOICE));
+ dialog.getMessageArea().setTitle(title).setText(text).setIcon(Display.getCurrent().getSystemImage(SWT.ICON_QUESTION)).addChoice(defaultSelection, items);
+ dialog.setButtonType(OpalDialogType.NONE);
+ dialog.show();
+ return dialog.getMessageArea().getChoice();
+ }
+
+ // ------------------------------------------- Getters & Setters
+
+ /**
+ * @return the title
+ */
+ public String getTitle() {
+ return this.title;
+ }
+
+ /**
+ * @param title the title to set
+ */
+ public void setTitle(final String title) {
+ this.title = title;
+ }
+
+ /**
+ * @return the buttonType
+ */
+ public OpalDialogType getButtonType() {
+ return this.buttonType;
+ }
+
+ /**
+ * @param buttonType the buttonType to set
+ */
+ public void setButtonType(final OpalDialogType buttonType) {
+ this.buttonType = buttonType;
+
+ switch (buttonType) {
+ case CLOSE:
+ this.footerArea.setButtonLabels(ResourceManager.getLabel(ResourceManager.CLOSE)).setDefaultButtonIndex(0);
+ break;
+ case NO_BUTTON:
+ break;
+ case OK:
+ this.footerArea.setButtonLabels(ResourceManager.getLabel(ResourceManager.OK)).setDefaultButtonIndex(0);
+ break;
+ case OK_CANCEL:
+ this.footerArea.setButtonLabels(ResourceManager.getLabel(ResourceManager.OK), ResourceManager.getLabel(ResourceManager.CANCEL)).setDefaultButtonIndex(-1);
+ break;
+ case SELECT_CANCEL:
+ this.footerArea.setButtonLabels(ResourceManager.getLabel(ResourceManager.SELECT), ResourceManager.getLabel(ResourceManager.CANCEL)).setDefaultButtonIndex(-1);
+ break;
+ case YES_NO:
+ this.footerArea.setButtonLabels(ResourceManager.getLabel(ResourceManager.YES), ResourceManager.getLabel(ResourceManager.NO)).setDefaultButtonIndex(0);
+ break;
+ default:
+ break;
+ }
+
+ }
+
+ /**
+ * @return the messageArea
+ */
+ public MessageArea getMessageArea() {
+ return this.messageArea;
+ }
+
+ /**
+ * @return the footerArea
+ */
+ public FooterArea getFooterArea() {
+ return this.footerArea;
+ }
+
+ /**
+ * @return the shell
+ */
+ public Shell getShell() {
+ return this.shell;
+ }
+
+ /**
+ * @return the index of the selected button
+ */
+ public int getSelectedButton() {
+ return getFooterArea().getSelectedButton();
+ }
+
+ /**
+ * @return the selection state of the checkbox
+ */
+ public boolean getCheckboxValue() {
+ return this.footerArea.getCheckBoxValue();
+ }
+
+ /**
+ * @return the minimum width of the dialog box
+ */
+ public int getMinimumWidth() {
+ return this.minimumWidth;
+ }
+
+ /**
+ * @param minimumWidth the minimum width of the dialog box to set
+ */
+ public void setMinimumWidth(final int minimumWidth) {
+ this.minimumWidth = minimumWidth;
+ }
+
+ /**
+ * @return the minimum height of the dialog box
+ */
+ public int getMinimumHeight() {
+ return this.minimumHeight;
+ }
+
+ /**
+ * @param minimumHeight the minimum height of the dialog box to set
+ */
+ public void setMinimumHeight(final int minimumHeight) {
+ this.minimumHeight = minimumHeight;
+ }
+
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/opalDialog/DialogArea.java b/org.tizen.common.externals/src/org/mihalis/opal/opalDialog/DialogArea.java
new file mode 100644
index 000000000..3e476930f
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/opalDialog/DialogArea.java
@@ -0,0 +1,154 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON
+ * 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:
+ * Laurent CARON (laurent.caron at gmail dot com) - Initial implementation and API
+ * Eugene Ryzhikov - Author of the Oxbow Project (http://code.google.com/p/oxbow/) - Inspiration
+ *******************************************************************************/
+package org.mihalis.opal.opalDialog;
+
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.DisposeEvent;
+import org.eclipse.swt.events.DisposeListener;
+import org.eclipse.swt.graphics.Color;
+import org.eclipse.swt.graphics.Font;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.widgets.Display;
+import org.mihalis.opal.utils.SWTGraphicUtil;
+
+/**
+ * This abstract class if the mother of MessageArea and FooterArea classes
+ */
+abstract class DialogArea {
+ protected final Dialog parent;
+ private boolean initialised;
+
+ /**
+ * Constructor
+ *
+ * @param parent parent dialog
+ */
+ public DialogArea(final Dialog parent) {
+ this.parent = parent;
+ }
+
+ /**
+ * Render the content of an area
+ */
+ abstract void render();
+
+ /**
+ * @return the initialised field
+ */
+ boolean isInitialised() {
+ return this.initialised;
+ }
+
+ /**
+ * @param initialised the initialised value to set
+ */
+ void setInitialised(final boolean initialised) {
+ this.initialised = initialised;
+ }
+
+ /**
+ * @return the normal font used by the dialog box
+ */
+ protected Font getNormalFont() {
+ return getFont("Segoe UI", 9, SWT.NONE);
+ }
+
+ /**
+ * @return the bigger font used by the dialog box
+ */
+ protected Font getBiggerFont() {
+ return getFont("Segoe UI", 11, SWT.NONE);
+ }
+
+ /**
+ * Build a font
+ *
+ * @param name name of the font
+ * @param size size of the font
+ * @param style style of the font
+ * @return the font
+ */
+ private Font getFont(final String name, final int size, final int style) {
+ final Font font = new Font(Display.getCurrent(), name, size, style);
+ this.parent.shell.addDisposeListener(new DisposeListener() {
+
+ @Override
+ public void widgetDisposed(final DisposeEvent e) {
+ SWTGraphicUtil.dispose(font);
+ }
+ });
+ return font;
+ }
+
+ /**
+ * @return the title's color (blue)
+ */
+ protected Color getTitleColor() {
+ final Color color = new Color(Display.getCurrent(), 35, 107, 178);
+ this.parent.shell.addDisposeListener(new DisposeListener() {
+
+ @Override
+ public void widgetDisposed(final DisposeEvent e) {
+ SWTGraphicUtil.dispose(color);
+ }
+ });
+ return color;
+ }
+
+ /**
+ * @return the grey color
+ */
+ protected Color getGreyColor() {
+ final Color color = new Color(Display.getCurrent(), 240, 240, 240);
+ this.parent.shell.addDisposeListener(new DisposeListener() {
+
+ @Override
+ public void widgetDisposed(final DisposeEvent e) {
+ SWTGraphicUtil.dispose(color);
+ }
+ });
+ return color;
+ }
+
+ /**
+ * @return the image "fewer details"
+ */
+ protected Image getFewerDetailsImage() {
+ return loadImage("images/fewerDetails.png");
+ }
+
+ /**
+ * @return the image "more details"
+ */
+ protected Image getMoreDetailsImage() {
+ return loadImage("images/moreDetails.png");
+ }
+
+ /**
+ * Loads an image
+ *
+ * @param fileName file name of the image
+ * @return the image
+ */
+ private Image loadImage(final String fileName) {
+ final Image image = SWTGraphicUtil.createImage(fileName);
+ this.parent.shell.addDisposeListener(new DisposeListener() {
+
+ @Override
+ public void widgetDisposed(final DisposeEvent e) {
+ SWTGraphicUtil.dispose(image);
+ }
+ });
+ return image;
+ }
+
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/opalDialog/FooterArea.java b/org.tizen.common.externals/src/org/mihalis/opal/opalDialog/FooterArea.java
new file mode 100644
index 000000000..66c7ecad2
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/opalDialog/FooterArea.java
@@ -0,0 +1,531 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON
+ * 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:
+ * Laurent CARON (laurent.caron at gmail dot com) - Initial implementation and API
+ * Eugene Ryzhikov - Author of the Oxbow Project (http://code.google.com/p/oxbow/) - Inspiration
+ *******************************************************************************/
+package org.mihalis.opal.opalDialog;
+
+import java.util.Arrays;
+import java.util.List;
+
+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.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.Display;
+import org.eclipse.swt.widgets.Event;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Listener;
+import org.mihalis.opal.utils.ResourceManager;
+
+/**
+ * Instances of this class are message areas
+ */
+public class FooterArea extends DialogArea {
+ private Image icon;
+ private String footerText;
+
+ private List<String> buttonLabels;
+ private int defaultButtonIndex;
+
+ private int timer;
+ private int timerIndexButton;
+
+ private int selectedButtonIndex;
+
+ private String collapsedLabelText;
+ private String expandedLabelText;
+ private boolean expanded;
+ private String detailText;
+ private boolean details;
+ private Button disabledButton;
+
+ private String checkBoxLabel;
+ private boolean checkBoxValue;
+
+ private Label expandedPanel;
+ private Composite composite;
+
+ /**
+ * Constructor
+ *
+ * @param parent dialog that is composed of this footer area
+ */
+ public FooterArea(final Dialog parent) {
+ super(parent);
+ this.selectedButtonIndex = -1;
+ this.expandedLabelText = ResourceManager.getLabel(ResourceManager.FEWER_DETAILS);
+ this.collapsedLabelText = ResourceManager.getLabel(ResourceManager.MORE_DETAILS);
+ this.timer = -1;
+ this.timerIndexButton = -1;
+ }
+
+ /**
+ * Add a check box
+ *
+ * @param label label to display
+ * @param selection default value of the check box
+ * @return this footer area
+ */
+ public FooterArea addCheckBox(final String label, final boolean selection) {
+ this.checkBoxLabel = label;
+ this.checkBoxValue = selection;
+ this.setInitialised(true);
+ return this;
+ }
+
+ /**
+ * @see org.mihalis.opal.OpalDialog.DialogArea#render()
+ */
+ @Override
+ void render() {
+ if (!this.isInitialised()) {
+ return;
+ }
+
+ this.createSeparator();
+
+ this.composite = new Composite(this.parent.shell, SWT.NONE);
+ this.composite.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, false));
+ this.composite.setBackground(this.getGreyColor());
+
+ int numberOfColumns = this.buttonLabels == null ? 0 : this.buttonLabels.size();
+ if (this.details) {
+ numberOfColumns += 2;
+ }
+
+ final GridLayout gridLayout = new GridLayout(numberOfColumns, false);
+ gridLayout.marginHeight = gridLayout.marginWidth = 10;
+ this.composite.setLayout(gridLayout);
+
+ if (this.details) {
+ this.createDetails(numberOfColumns);
+ }
+
+ if (this.buttonLabels != null) {
+ this.createButtons();
+ }
+
+ if (this.details && this.parent.getMessageArea().getException() == null && this.expanded) {
+ this.createExpandedPanel(numberOfColumns);
+ }
+
+ if (this.checkBoxLabel != null) {
+ this.createCheckBox(numberOfColumns);
+ }
+
+ if (this.footerText != null) {
+ this.createFooter();
+
+ }
+
+ }
+
+ /**
+ * Create the buttons
+ */
+ private void createButtons() {
+ Button defaultButton = null;
+ for (int i = 0; i < this.buttonLabels.size(); i++) {
+ final Button button = new Button(this.composite, SWT.PUSH);
+ button.setText(this.buttonLabels.get(i));
+
+ final GridData gd = new GridData(GridData.END, GridData.CENTER, i == 0, false);
+ gd.minimumWidth = 70;
+ gd.widthHint = 70;
+ button.setLayoutData(gd);
+
+ if (i == this.defaultButtonIndex) {
+ defaultButton = button;
+ }
+
+ final Integer integer = new Integer(i);
+ button.addSelectionListener(new SelectionAdapter() {
+
+ /**
+ * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
+ */
+ @Override
+ public void widgetSelected(final SelectionEvent e) {
+ FooterArea.this.parent.shell.dispose();
+ FooterArea.this.selectedButtonIndex = integer.intValue();
+ }
+
+ });
+
+ if (i == this.timerIndexButton && this.timer != -1) {
+ this.disabledButton = button;
+ button.setData(button.getText());
+ button.setText(button.getText() + " (" + this.timer + ")");
+ button.setEnabled(false);
+ }
+
+ }
+
+ if (this.timerIndexButton != -1 && this.timer != -1) {
+ Display.getCurrent().timerExec(1000, new Runnable() {
+
+ @Override
+ public void run() {
+ FooterArea.this.timer--;
+ if (FooterArea.this.disabledButton.isDisposed()) {
+ return;
+ }
+
+ if (FooterArea.this.timer == 0) {
+ FooterArea.this.disabledButton.setText((String) FooterArea.this.disabledButton.getData());
+ FooterArea.this.disabledButton.setEnabled(true);
+ } else {
+ FooterArea.this.disabledButton.setText(FooterArea.this.disabledButton.getData() + " (" + FooterArea.this.timer + ")");
+ Display.getCurrent().timerExec(1000, this);
+ }
+
+ }
+ });
+ }
+
+ this.parent.shell.setDefaultButton(defaultButton);
+ }
+
+ /**
+ * Create the details section
+ *
+ * @param numberOfColumns
+ */
+ private void createDetails(final int numberOfColumns) {
+ final Label icon = new Label(this.composite, SWT.NONE);
+ icon.setBackground(this.getGreyColor());
+ icon.setImage(this.isExpanded() ? this.getFewerDetailsImage() : this.getMoreDetailsImage());
+ icon.setLayoutData(new GridData(GridData.CENTER, GridData.CENTER, false, false));
+
+ final Label label = new Label(this.composite, SWT.NONE);
+ label.setBackground(this.getGreyColor());
+ label.setText(this.isExpanded() ? this.expandedLabelText : this.collapsedLabelText);
+ label.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, false, false));
+
+ final int numberOfColumnsParam = numberOfColumns;
+
+ final Listener listener = new Listener() {
+ @Override
+ public void handleEvent(final Event event) {
+ if (FooterArea.this.parent.getMessageArea().getException() != null) {
+ if (label.getText().equals(FooterArea.this.expandedLabelText)) {
+ label.setText(FooterArea.this.collapsedLabelText);
+ icon.setImage(FooterArea.this.getMoreDetailsImage());
+ FooterArea.this.parent.getMessageArea().hideException();
+ } else {
+ label.setText(FooterArea.this.expandedLabelText);
+ icon.setImage(FooterArea.this.getFewerDetailsImage());
+ FooterArea.this.parent.getMessageArea().showException();
+ }
+
+ } else {
+ if (label.getText().equals(FooterArea.this.expandedLabelText)) {
+ label.setText(FooterArea.this.collapsedLabelText);
+ icon.setImage(FooterArea.this.getMoreDetailsImage());
+ FooterArea.this.expandedPanel.dispose();
+ FooterArea.this.parent.pack();
+ } else {
+ label.setText(FooterArea.this.expandedLabelText);
+ icon.setImage(FooterArea.this.getFewerDetailsImage());
+ FooterArea.this.createExpandedPanel(numberOfColumnsParam);
+ FooterArea.this.parent.pack();
+ }
+ }
+ }
+ };
+
+ label.addListener(SWT.MouseUp, listener);
+ icon.addListener(SWT.MouseUp, listener);
+ }
+
+ /**
+ * Create a check box
+ *
+ * @param numberOfColumns
+ */
+ private void createCheckBox(final int numberOfColumns) {
+ final Button button = new Button(this.composite, SWT.CHECK);
+ button.setText(this.checkBoxLabel);
+ button.setSelection(this.checkBoxValue);
+ button.setBackground(this.getGreyColor());
+ button.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, true, false, numberOfColumns, 1));
+ button.addSelectionListener(new SelectionAdapter() {
+
+ /**
+ * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
+ */
+ @Override
+ public void widgetSelected(final SelectionEvent e) {
+ FooterArea.this.checkBoxValue = button.getSelection();
+ }
+
+ });
+ }
+
+ /**
+ * Create footer section
+ */
+ private void createFooter() {
+ this.createSeparator();
+
+ final Composite informationComposite = new Composite(this.parent.shell, SWT.NONE);
+ informationComposite.setLayoutData(new GridData(GridData.FILL, GridData.FILL, false, false));
+ informationComposite.setBackground(this.getGreyColor());
+
+ informationComposite.setLayout(new GridLayout(this.icon == null ? 1 : 2, false));
+
+ if (this.icon != null) {
+ final Label labelIcon = new Label(informationComposite, SWT.NONE);
+ labelIcon.setBackground(this.getGreyColor());
+ labelIcon.setImage(this.icon);
+ labelIcon.setLayoutData(new GridData(GridData.CENTER, GridData.CENTER, false, false));
+ }
+ final Label labelText = new Label(informationComposite, SWT.NONE);
+ labelText.setBackground(this.getGreyColor());
+ labelText.setText(this.footerText);
+ labelText.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false));
+ }
+
+ /**
+ * Create the expanded panel
+ *
+ * @param numberOfColumns
+ */
+ private void createExpandedPanel(final int numberOfColumns) {
+ this.expandedPanel = new Label(this.composite, SWT.BORDER);
+ this.expandedPanel.setText(this.detailText);
+ this.expandedPanel.setBackground(this.getGreyColor());
+ final GridData gd = new GridData(GridData.FILL, GridData.FILL, false, false, numberOfColumns, 1);
+ gd.minimumHeight = gd.heightHint = 150;
+ this.expandedPanel.setLayoutData(gd);
+ }
+
+ /**
+ * Create a separator
+ */
+ private void createSeparator() {
+ final Composite c = new Composite(this.parent.shell, SWT.NONE);
+ c.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, false));
+ c.setBackground(this.getGreyColor());
+
+ final GridLayout gridLayout = new GridLayout(1, false);
+ gridLayout.marginHeight = gridLayout.marginWidth = 0;
+ c.setLayout(gridLayout);
+
+ final Label separator = new Label(c, SWT.SEPARATOR | SWT.HORIZONTAL);
+ separator.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, false));
+
+ }
+
+ // ------------------------------------------- Getters & Setters
+
+ /**
+ * @return the icon
+ */
+ public Image getIcon() {
+ return this.icon;
+ }
+
+ /**
+ * @param icon the icon to set
+ * @return this footer area
+ */
+ public FooterArea setIcon(final Image icon) {
+ this.icon = icon;
+ this.setInitialised(true);
+ return this;
+ }
+
+ /**
+ * @return the text
+ */
+ public String getFooterText() {
+ return this.footerText;
+ }
+
+ /**
+ * @param text the text to set
+ * @return this footer area
+ */
+ public FooterArea setFooterText(final String text) {
+ this.footerText = text;
+ this.setInitialised(true);
+ return this;
+ }
+
+ /**
+ * @return the button labels
+ */
+ public List<String> getButtonLabels() {
+ return this.buttonLabels;
+ }
+
+ /**
+ * @param buttonLabels the button labels to set
+ * @return this footer area
+ */
+ public FooterArea setButtonLabels(final List<String> buttonLabels) {
+ this.buttonLabels = buttonLabels;
+ this.setInitialised(true);
+ return this;
+ }
+
+ /**
+ * @param buttonLabels the button labels to set
+ * @return this footer area
+ */
+ public FooterArea setButtonLabels(final String... buttonLabels) {
+ this.buttonLabels = Arrays.asList(buttonLabels);
+ this.setInitialised(true);
+ return this;
+ }
+
+ /**
+ * @return the default button index
+ */
+ public int getDefaultButtonIndex() {
+ return this.defaultButtonIndex;
+ }
+
+ /**
+ * @param defaultButtonIndex the default button index to set
+ * @return this footer area
+ */
+ public FooterArea setDefaultButtonIndex(final int defaultButtonIndex) {
+ this.defaultButtonIndex = defaultButtonIndex;
+ this.setInitialised(true);
+ return this;
+ }
+
+ /**
+ * @return the timer value
+ */
+ public int getTimer() {
+ return this.timer;
+ }
+
+ /**
+ * @param timer the timer value to set
+ * @return this footer area
+ */
+ public FooterArea setTimer(final int timer) {
+ this.timer = timer;
+ this.setInitialised(true);
+ return this;
+ }
+
+ /**
+ * @return the timer index button
+ */
+ public int getTimerIndexButton() {
+ return this.timerIndexButton;
+ }
+
+ /**
+ * @param timerIndexButton the timer index button to set
+ * @return this footer area
+ */
+ public FooterArea setTimerIndexButton(final int timerIndexButton) {
+ this.timerIndexButton = timerIndexButton;
+ this.setInitialised(true);
+ return this;
+ }
+
+ /**
+ * @return the selected button
+ */
+ int getSelectedButton() {
+ return this.selectedButtonIndex;
+ }
+
+ /**
+ * @return the collapsed label text
+ */
+ public String getCollapsedLabelText() {
+ return this.collapsedLabelText;
+ }
+
+ /**
+ * @param collapsedLabelText the collapsed label text to set
+ * @return this footer area
+ */
+ public FooterArea setCollapsedLabelText(final String collapsedLabelText) {
+ this.details = true;
+ this.collapsedLabelText = collapsedLabelText;
+ this.setInitialised(true);
+ return this;
+ }
+
+ /**
+ * @return the expanded label text
+ */
+ public String getExpandedLabelText() {
+ return this.expandedLabelText;
+ }
+
+ /**
+ * @param expandedLabelText the expanded label text to set
+ * @return this footer area
+ */
+ public FooterArea setExpandedLabelText(final String expandedLabelText) {
+ this.details = true;
+ this.expandedLabelText = expandedLabelText;
+ this.setInitialised(true);
+ return this;
+ }
+
+ /**
+ * @return the expanded flag
+ */
+ public boolean isExpanded() {
+ return this.expanded;
+ }
+
+ /**
+ * @param expanded the expanded flag to set
+ * @return this footer area
+ */
+ public FooterArea setExpanded(final boolean expanded) {
+ this.details = true;
+ this.expanded = expanded;
+ this.setInitialised(true);
+ return this;
+ }
+
+ /**
+ * @return the detail text
+ */
+ public String getDetailText() {
+ return this.detailText;
+ }
+
+ /**
+ * @param detailText the detail text to set
+ * @return this footer area
+ */
+ public FooterArea setDetailText(final String detailText) {
+ this.details = true;
+ this.detailText = detailText;
+ this.setInitialised(true);
+ return this;
+ }
+
+ /**
+ * @return the check box vqlue
+ */
+ public boolean getCheckBoxValue() {
+ return this.checkBoxValue;
+ }
+
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/opalDialog/MessageArea.java b/org.tizen.common.externals/src/org/mihalis/opal/opalDialog/MessageArea.java
new file mode 100644
index 000000000..55cc9e82c
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/opalDialog/MessageArea.java
@@ -0,0 +1,541 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON
+ * 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:
+ * Laurent CARON (laurent.caron at gmail dot com) - Initial implementation and API
+ * Eugene Ryzhikov - Author of the Oxbow Project (http://code.google.com/p/oxbow/) - Inspiration
+ *******************************************************************************/
+package org.mihalis.opal.opalDialog;
+
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.custom.StyledText;
+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.Display;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.ProgressBar;
+import org.eclipse.swt.widgets.Text;
+import org.mihalis.opal.utils.SWTGraphicUtil;
+import org.mihalis.opal.utils.StringUtil;
+
+/**
+ * Instances of this class are message areas
+ */
+public class MessageArea extends DialogArea {
+ // Main composite
+ private Composite composite;
+
+ // Informations for a simple dialog box
+ private String title;
+ private Image icon;
+ private String text;
+
+ // Informations for a radio choice dialog box
+ private int radioChoice;
+ private int radioDefaultSelection;
+ private String[] radioValues;
+
+ // Informations for a exception viewer dialog box
+ private Throwable exception;
+ private Text textException;
+
+ // Informations for an input dialog box
+ private String textBoxValue;
+
+ // Informations for a choice dialog box
+ private int choice;
+ private int choiceDefaultSelection;
+ private ChoiceItem[] choiceValues;
+
+ // Informations for a progress bar displayed in a dialog box
+ private ProgressBar progressBar;
+ private int progressBarMinimumValue;
+ private int progressBarMaximumValue;
+ private int progressBarValue;
+
+ /**
+ * Constructor
+ *
+ * @param parent dialog that is composed of this message area
+ */
+ public MessageArea(final Dialog parent) {
+ super(parent);
+ this.radioChoice = -1;
+ this.choice = -1;
+ this.progressBarValue = -1;
+ }
+
+ /**
+ * Add a choice
+ *
+ * @param defaultSelection default selection
+ * @param items a list of the choice item
+ * @return the current message area
+ */
+ public MessageArea addChoice(final int defaultSelection, final ChoiceItem... items) {
+ setInitialised(true);
+ this.choiceDefaultSelection = defaultSelection;
+ this.choiceValues = items;
+ return this;
+ }
+
+ /**
+ * Add a choice composed of radio buttons
+ *
+ * @param defaultSelection default selection
+ * @param values values
+ * @return the current message area
+ */
+ public MessageArea addRadioButtons(final int defaultSelection, final String... values) {
+ setInitialised(true);
+ this.radioDefaultSelection = defaultSelection;
+ this.radioValues = values;
+ return this;
+ }
+
+ /**
+ * Add a text box for input
+ *
+ * @param value defaut value of the textbox
+ * @return the current message area
+ */
+ public MessageArea addTextBox(final String value) {
+ setInitialised(true);
+ this.textBoxValue = value;
+ return this;
+ }
+
+ /**
+ * Add a progress bar
+ *
+ * @param mininum minimum value
+ * @param maximum maximum value
+ * @param value default value
+ * @return the current message area
+ */
+ public MessageArea addProgressBar(final int mininum, final int maximum, final int value) {
+ setInitialised(true);
+ this.progressBarMinimumValue = mininum;
+ this.progressBarMaximumValue = maximum;
+ this.progressBarValue = value;
+ return this;
+ }
+
+ /**
+ * @see org.mihalis.opal.OpalDialog.DialogArea#render()
+ */
+ @Override
+ public void render() {
+ if (!isInitialised()) {
+ return;
+ }
+
+ this.composite = new Composite(this.parent.shell, SWT.NONE);
+ this.composite.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, true));
+ this.composite.setBackground(this.composite.getDisplay().getSystemColor(SWT.COLOR_WHITE));
+
+ final boolean hasIcon = this.icon != null;
+ final boolean hasTitle = !StringUtil.isEmpty(this.title);
+ final boolean hasText = !StringUtil.isEmpty(this.text);
+ final boolean hasRadio = this.radioValues != null;
+ final boolean hasException = this.exception != null;
+ final boolean hasTextbox = this.textBoxValue != null;
+ final boolean hasChoice = this.choiceValues != null;
+ final boolean hasProgressBar = this.progressBarValue != -1;
+
+ final int numberOfColumns = hasIcon ? 2 : 1;
+ int numberOfRows = hasTitle && hasText ? 2 : 1;
+
+ if (hasRadio) {
+ numberOfRows += this.radioValues.length;
+ }
+
+ if (hasChoice) {
+ numberOfRows += this.choiceValues.length;
+ }
+
+ if (hasException || hasTextbox) {
+ numberOfRows++;
+ }
+
+ if (hasProgressBar) {
+ numberOfRows++;
+ }
+
+ final GridLayout gridLayout = new GridLayout(numberOfColumns, false);
+ gridLayout.marginHeight = gridLayout.marginWidth = 0;
+ gridLayout.marginRight = 10;
+ gridLayout.marginLeft = 10;
+ gridLayout.marginTop = 10;
+ gridLayout.marginBottom = 10;
+ this.composite.setLayout(gridLayout);
+
+ if (hasIcon) {
+ createIcon(numberOfRows);
+ }
+
+ if (hasTitle) {
+ createTitle(hasIcon);
+ }
+
+ if (hasText) {
+ createText(hasIcon, hasTitle);
+ }
+
+ if (hasRadio) {
+ createRadioButtons();
+ }
+
+ if (hasException) {
+ createTextException();
+ }
+
+ if (hasTextbox) {
+ createTextBox();
+ }
+
+ if (hasChoice) {
+ createChoice();
+ }
+
+ if (hasProgressBar) {
+ createProgressBar();
+ }
+
+ }
+
+ /**
+ * Create the icon
+ *
+ * @param numberOfRows number of rows displayed
+ */
+ private void createIcon(final int numberOfRows) {
+ final Label label = new Label(this.composite, SWT.NONE);
+ label.setImage(this.icon);
+ label.setBackground(this.composite.getDisplay().getSystemColor(SWT.COLOR_WHITE));
+ label.setLayoutData(new GridData(GridData.CENTER, GridData.BEGINNING, false, false, 1, numberOfRows));
+ }
+
+ /**
+ * Create the title
+ *
+ * @param hasIcon if <code>true</code> an icon is displayed
+ */
+ private void createTitle(final boolean hasIcon) {
+ final Label label = new Label(this.composite, SWT.NONE);
+ label.setText(this.title);
+ label.setFont(getBiggerFont());
+ label.setForeground(getTitleColor());
+ label.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE));
+ final GridData gd = new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false, 1, 1);
+
+ if (hasIcon) {
+ gd.horizontalIndent = 8;
+ } else {
+ gd.horizontalIndent = 10;
+ gd.verticalIndent = 10;
+ }
+
+ label.setLayoutData(gd);
+ }
+
+ /**
+ * Create the text
+ *
+ * @param hasIcon if <code>true</code> an icon is displayed
+ * @param hasTitle if <code>true</code> a title is displayed
+ */
+ private void createText(final boolean hasIcon, final boolean hasTitle) {
+ final StyledText label = new StyledText(this.composite, SWT.NONE);
+ label.setText("<html><body>" + this.text + "</body></html>");
+ SWTGraphicUtil.applyHTMLFormating(label);
+ label.setEnabled(false);
+ label.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE));
+ final GridData gd = new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false, 1, 1);
+
+ if (hasIcon) {
+ gd.horizontalIndent = 8;
+ } else {
+ gd.horizontalIndent = 20;
+ if (hasTitle) {
+ gd.verticalIndent = 8;
+ } else {
+ gd.verticalIndent = 20;
+ }
+ }
+
+ label.setLayoutData(gd);
+ }
+
+ /**
+ * Create radio buttons
+ */
+ private void createRadioButtons() {
+ for (int i = 0; i < this.radioValues.length; i++) {
+ final Button button = new Button(this.composite, SWT.RADIO);
+ button.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE));
+ button.setText(this.radioValues[i]);
+
+ final Integer index = new Integer(i);
+ button.addSelectionListener(new SelectionAdapter() {
+
+ /**
+ * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
+ */
+ @Override
+ public void widgetSelected(final SelectionEvent e) {
+ if (button.getSelection()) {
+ MessageArea.this.radioChoice = index.intValue();
+ }
+ }
+
+ });
+
+ button.setSelection(i == this.radioDefaultSelection);
+ final GridData gd = new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false, 1, 1);
+ gd.horizontalIndent = 10;
+ button.setLayoutData(gd);
+ }
+ }
+
+ /**
+ * Create the text that displays an exception
+ */
+ private void createTextException() {
+ this.textException = new Text(this.composite, SWT.MULTI | SWT.READ_ONLY | SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL);
+ this.textException.setText(StringUtil.stackStraceAsString(this.exception));
+ this.textException.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE));
+ final GridData gd = new GridData(GridData.FILL, GridData.FILL, false, false, 1, 1);
+ gd.minimumHeight = 300;
+ this.textException.setLayoutData(gd);
+ }
+
+ /**
+ * Create a text box
+ */
+ private void createTextBox() {
+ final Text textbox = new Text(this.composite, SWT.SINGLE | SWT.BORDER);
+ textbox.setText(this.textBoxValue);
+ textbox.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE));
+ final GridData gd = new GridData(GridData.FILL, GridData.FILL, true, false, 1, 1);
+ textbox.setLayoutData(gd);
+ textbox.addModifyListener(new ModifyListener() {
+
+ @Override
+ public void modifyText(final ModifyEvent e) {
+ MessageArea.this.textBoxValue = textbox.getText();
+ }
+ });
+ }
+
+ /**
+ * Create a choice selection
+ */
+ private void createChoice() {
+ for (int i = 0; i < this.choiceValues.length; i++) {
+ final ChoiceWidget choice = new ChoiceWidget(this.composite, SWT.RADIO);
+ choice.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE));
+ choice.setChoiceItem(this.choiceValues[i]);
+
+ final Integer index = new Integer(i);
+ choice.addSelectionListener(new SelectionAdapter() {
+
+ /**
+ * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
+ */
+ @Override
+ public void widgetSelected(final SelectionEvent e) {
+ MessageArea.this.choice = index.intValue();
+ MessageArea.this.parent.shell.dispose();
+ }
+
+ });
+
+ choice.setSelection(i == this.choiceDefaultSelection);
+ final GridData gd = new GridData(GridData.FILL, GridData.FILL, false, false, 1, 1);
+ choice.setLayoutData(gd);
+ }
+ }
+
+ /**
+ * Create a progress bar
+ */
+ private void createProgressBar() {
+ this.progressBar = new ProgressBar(this.composite, SWT.SMOOTH | SWT.HORIZONTAL);
+ this.progressBar.setMinimum(this.progressBarMinimumValue);
+ this.progressBar.setMaximum(this.progressBarMaximumValue);
+ this.progressBar.setSelection(this.progressBarValue);
+ this.progressBar.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE));
+ final GridData gd = new GridData(GridData.FILL, GridData.FILL, true, false, 1, 1);
+ this.progressBar.setLayoutData(gd);
+ }
+
+ /**
+ * Hide the exception panel
+ */
+ void hideException() {
+ this.textException.dispose();
+ this.parent.pack();
+
+ }
+
+ /**
+ * Show the exception panel
+ */
+ void showException() {
+ createTextException();
+ this.parent.pack();
+ }
+
+ // ------------------------------------------- Getters & Setters
+
+ /**
+ * @return the title
+ */
+ public String getTitle() {
+ return this.title;
+ }
+
+ /**
+ * @param title the title to set
+ * @return the current message area
+ */
+ public MessageArea setTitle(final String title) {
+ this.title = title;
+ setInitialised(true);
+ return this;
+ }
+
+ /**
+ * @return the icon
+ */
+ public Image getIcon() {
+ return this.icon;
+ }
+
+ /**
+ * @param icon the icon to set
+ */
+ public MessageArea setIcon(final Image icon) {
+ this.icon = icon;
+ setInitialised(true);
+ return this;
+ }
+
+ /**
+ * @return the text
+ */
+ public String getText() {
+ return this.text;
+ }
+
+ /**
+ * @param text the text to set
+ */
+ public MessageArea setText(final String text) {
+ this.text = text;
+ setInitialised(true);
+ return this;
+ }
+
+ /**
+ * @return the radio choice
+ */
+ public int getRadioChoice() {
+ return this.radioChoice;
+ }
+
+ /**
+ * @return the exception
+ */
+ public Throwable getException() {
+ return this.exception;
+ }
+
+ /**
+ * @param exception the exception to set
+ * @return
+ */
+ public MessageArea setException(final Throwable exception) {
+ this.exception = exception;
+ setInitialised(true);
+ return this;
+ }
+
+ /**
+ * @return the choice
+ */
+ public int getChoice() {
+ return this.choice;
+ }
+
+ /**
+ * @return the value stored in the text box
+ */
+ public String getTextBoxValue() {
+ return this.textBoxValue;
+ }
+
+ /**
+ * @return the progress bar minimum value
+ */
+ public int getProgressBarMinimumValue() {
+ return this.progressBarMinimumValue;
+ }
+
+ /**
+ * @param progressBarMinimumValue the progress bar minimum value to set
+ */
+ public void setProgressBarMinimumValue(final int progressBarMinimumValue) {
+ this.progressBarMinimumValue = progressBarMinimumValue;
+ if (this.progressBar != null && !this.progressBar.isDisposed()) {
+ this.progressBar.setMinimum(progressBarMinimumValue);
+ }
+ }
+
+ /**
+ * @return the progress bar maximum value
+ */
+ public int getProgressBarMaximumValue() {
+ return this.progressBarMaximumValue;
+ }
+
+ /**
+ * @param progressBarMaximumValue the progress bar minimum value to set
+ */
+ public void setProgressBarMaximumValue(final int progressBarMaximumValue) {
+ this.progressBarMaximumValue = progressBarMaximumValue;
+ if (this.progressBar != null && !this.progressBar.isDisposed()) {
+ this.progressBar.setMaximum(progressBarMaximumValue);
+ }
+ }
+
+ /**
+ * @return the progress bar value
+ */
+ public int getProgressBarValue() {
+ return this.progressBarValue;
+ }
+
+ /**
+ * @param progressBarValue the progress bar value to set
+ */
+ public void setProgressBarValue(final int progressBarValue) {
+ this.progressBarValue = progressBarValue;
+ if (this.progressBar != null && !this.progressBar.isDisposed()) {
+ this.progressBar.setSelection(progressBarValue);
+ }
+ }
+
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/panels/BlurredPanel.java b/org.tizen.common.externals/src/org/mihalis/opal/panels/BlurredPanel.java
new file mode 100644
index 000000000..4d2b79d73
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/panels/BlurredPanel.java
@@ -0,0 +1,151 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON
+ * 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:
+ * Laurent CARON (laurent.caron at gmail dot com) - initial API and implementation
+ *******************************************************************************/
+package org.mihalis.opal.panels;
+
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.SWTException;
+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.layout.FillLayout;
+import org.eclipse.swt.widgets.Canvas;
+import org.eclipse.swt.widgets.Event;
+import org.eclipse.swt.widgets.Listener;
+import org.eclipse.swt.widgets.Shell;
+import org.mihalis.opal.utils.SWTGraphicUtil;
+
+/**
+ * Instances of this class are controls located on the top of a shell. They
+ * display a blurred version of the content of the shell
+ */
+public class BlurredPanel {
+ private final Shell parent;
+ private static final String BLURED_PANEL_KEY = "org.mihalis.opal.Panels.DarkPanel";
+ private int radius;
+ private Shell panel;
+ private Canvas canvas;
+
+ /**
+ * Constructs a new instance of this class given its parent.
+ *
+ * @param shell a shell that will be the parent of the new instance (cannot
+ * be null)
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the parent is null</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the parent has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the parent</li>
+ * </ul>
+ */
+ public BlurredPanel(final Shell shell) {
+ if (shell == null) {
+ SWT.error(SWT.ERROR_NULL_ARGUMENT);
+ }
+
+ if (shell.isDisposed()) {
+ SWT.error(SWT.ERROR_INVALID_ARGUMENT);
+ }
+
+ this.parent = shell;
+ if (shell.getData(BLURED_PANEL_KEY) != null) {
+ throw new IllegalArgumentException("This shell has already an infinite panel attached on it !");
+ }
+ shell.setData(BLURED_PANEL_KEY, this);
+ this.radius = 2;
+ }
+
+ /**
+ * Show the blurred panel
+ */
+ public void show() {
+ if (this.parent.isDisposed()) {
+ SWT.error(SWT.ERROR_WIDGET_DISPOSED);
+ }
+
+ this.panel = new Shell(this.parent, SWT.APPLICATION_MODAL | SWT.NO_TRIM);
+ this.panel.setLayout(new FillLayout());
+
+ this.panel.addListener(SWT.KeyUp, new Listener() {
+
+ @Override
+ public void handleEvent(final Event event) {
+ event.doit = false;
+ }
+ });
+
+ this.canvas = new Canvas(this.panel, SWT.NO_BACKGROUND | SWT.DOUBLE_BUFFERED);
+ this.canvas.addPaintListener(new PaintListener() {
+
+ @Override
+ public void paintControl(final PaintEvent e) {
+ paintCanvas(e);
+ }
+ });
+
+ this.panel.setBounds(this.panel.getDisplay().map(this.parent, null, this.parent.getClientArea()));
+ this.panel.open();
+
+ }
+
+ /**
+ * Paint the canvas that holds the panel
+ *
+ * @param e {@link PaintEvent}
+ */
+ private void paintCanvas(final PaintEvent e) {
+ // Paint the panel
+ e.gc.drawImage(createBlurredImage(), 0, 0);
+ }
+
+ private Image createBlurredImage() {
+ final GC gc = new GC(this.parent);
+ final Image image = new Image(this.parent.getDisplay(), this.parent.getSize().x, this.parent.getSize().y);
+ gc.copyArea(image, 0, 0);
+ gc.dispose();
+
+ return new Image(this.parent.getDisplay(), SWTGraphicUtil.blur(image.getImageData(), this.radius));
+
+ }
+
+ /**
+ * Hide the panel
+ */
+ public void hide() {
+ if (this.parent.isDisposed()) {
+ SWT.error(SWT.ERROR_WIDGET_DISPOSED);
+ }
+
+ if (this.panel == null || this.panel.isDisposed()) {
+ return;
+ }
+
+ this.panel.dispose();
+ }
+
+ /**
+ * @return the radius of the blur effect
+ */
+ public int getRadius() {
+ return this.radius;
+ }
+
+ /**
+ * @param radius the radius to set
+ */
+ public void setRadius(final int radius) {
+ this.radius = radius;
+ }
+
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/panels/DarkPanel.java b/org.tizen.common.externals/src/org/mihalis/opal/panels/DarkPanel.java
new file mode 100644
index 000000000..ca681be14
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/panels/DarkPanel.java
@@ -0,0 +1,144 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON
+ * 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:
+ * Laurent CARON (laurent.caron at gmail dot com) - initial API and implementation
+ *******************************************************************************/
+package org.mihalis.opal.panels;
+
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.SWTException;
+import org.eclipse.swt.events.PaintEvent;
+import org.eclipse.swt.events.PaintListener;
+import org.eclipse.swt.graphics.GC;
+import org.eclipse.swt.graphics.Rectangle;
+import org.eclipse.swt.layout.FillLayout;
+import org.eclipse.swt.widgets.Canvas;
+import org.eclipse.swt.widgets.Event;
+import org.eclipse.swt.widgets.Listener;
+import org.eclipse.swt.widgets.Shell;
+
+/**
+ * Instances of this class are controls located on the top of a shell. They
+ * display a dark panel on this shell
+ */
+public class DarkPanel {
+ private final Shell parent;
+ private static final String DARK_PANEL_KEY = "org.mihalis.opal.BluredPanel.DarkPanel";
+ private int alpha;
+ private Shell panel;
+ private Canvas canvas;
+
+ /**
+ * Constructs a new instance of this class given its parent.
+ *
+ * @param shell a shell that will be the parent of the new instance (cannot
+ * be null)
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the parent is null</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the parent has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the parent</li>
+ * </ul>
+ */
+ public DarkPanel(final Shell shell) {
+ if (shell == null) {
+ SWT.error(SWT.ERROR_NULL_ARGUMENT);
+ }
+
+ if (shell.isDisposed()) {
+ SWT.error(SWT.ERROR_INVALID_ARGUMENT);
+ }
+
+ this.parent = shell;
+ if (shell.getData(DARK_PANEL_KEY) != null) {
+ throw new IllegalArgumentException("This shell has already an infinite panel attached on it !");
+ }
+ shell.setData(DARK_PANEL_KEY, this);
+ this.alpha = 100;
+ }
+
+ /**
+ * Show the dark panel
+ */
+ public void show() {
+ if (this.parent.isDisposed()) {
+ SWT.error(SWT.ERROR_WIDGET_DISPOSED);
+ }
+
+ this.panel = new Shell(this.parent, SWT.APPLICATION_MODAL | SWT.NO_TRIM);
+ this.panel.setLayout(new FillLayout());
+ this.panel.setAlpha(this.alpha);
+
+ this.panel.addListener(SWT.KeyUp, new Listener() {
+
+ @Override
+ public void handleEvent(final Event event) {
+ event.doit = false;
+ }
+ });
+
+ this.canvas = new Canvas(this.panel, SWT.NO_BACKGROUND | SWT.DOUBLE_BUFFERED);
+ this.canvas.addPaintListener(new PaintListener() {
+
+ @Override
+ public void paintControl(final PaintEvent e) {
+ paintCanvas(e);
+ }
+ });
+
+ this.panel.setBounds(this.panel.getDisplay().map(this.parent, null, this.parent.getClientArea()));
+ this.panel.open();
+
+ }
+
+ /**
+ * Paint the canvas that holds the panel
+ *
+ * @param e {@link PaintEvent}
+ */
+ private void paintCanvas(final PaintEvent e) {
+ // Paint the panel
+ final Rectangle clientArea = ((Canvas) e.widget).getClientArea();
+ final GC gc = e.gc;
+ gc.setBackground(this.panel.getDisplay().getSystemColor(SWT.COLOR_BLACK));
+ gc.fillRectangle(clientArea);
+ }
+
+ /**
+ * Hide the dark panel
+ */
+ public void hide() {
+ if (this.parent.isDisposed()) {
+ SWT.error(SWT.ERROR_WIDGET_DISPOSED);
+ }
+
+ if (this.panel == null || this.panel.isDisposed()) {
+ return;
+ }
+
+ this.panel.dispose();
+ }
+
+ /**
+ * @return the alpha value
+ */
+ public int getAlpha() {
+ return this.alpha;
+ }
+
+ /**
+ * @param alpha the alpha to set
+ */
+ public void setAlpha(final int alpha) {
+ this.alpha = alpha;
+ }
+
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/PWContainer.java b/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/PWContainer.java
new file mode 100644
index 000000000..17784f6ff
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/PWContainer.java
@@ -0,0 +1,45 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON
+ * 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:
+ * Laurent CARON (laurent.caron at gmail dot com) - Initial implementation and API
+ *******************************************************************************/
+package org.mihalis.opal.preferenceWindow;
+
+import org.eclipse.swt.widgets.Composite;
+import org.mihalis.opal.preferenceWindow.widgets.PWWidget;
+
+/**
+ * Abstract class for "Containers" (row, group and tab)
+ *
+ */
+public abstract class PWContainer {
+
+ /**
+ * Add a container to the current element
+ *
+ * @param element element to add
+ * @return the container
+ */
+ public abstract PWContainer add(final PWContainer element);
+
+ /**
+ * Add a widget to the current element
+ *
+ * @param widget widget to add
+ * @return the container
+ */
+ public abstract PWContainer add(final PWWidget widget);
+
+ /**
+ * Build the content of the container
+ *
+ * @param parent parent composite
+ */
+ public abstract void build(final Composite parent);
+
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/PWGroup.java b/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/PWGroup.java
new file mode 100644
index 000000000..ac0efb4aa
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/PWGroup.java
@@ -0,0 +1,169 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON
+ * 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:
+ * Laurent CARON (laurent.caron at gmail dot com) - Initial implementation and API
+ *******************************************************************************/
+package org.mihalis.opal.preferenceWindow;
+
+import java.util.ArrayList;
+import java.util.List;
+
+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.Group;
+import org.mihalis.opal.preferenceWindow.widgets.PWWidget;
+
+/**
+ * Instances of this class are groups
+ */
+public class PWGroup extends PWRowGroup {
+
+ private final String label;
+ private final boolean hasBorder;
+ private final List<PWRow> children;
+
+ /**
+ * Constructor
+ *
+ * @param hasBorder if <code>true</code>, the group has a border
+ */
+ public PWGroup(final boolean hasBorder) {
+ this(null, hasBorder);
+ }
+
+ /**
+ * Constructor
+ *
+ * @param label label associated to the group
+ */
+ public PWGroup(final String label) {
+ this(label, true);
+ }
+
+ /**
+ * Constructor
+ *
+ * @param label label associated to the group
+ * @param hasBorder if <code>true</code>, the group has a border
+ */
+ public PWGroup(final String label, final boolean hasBorder) {
+ this.label = label;
+ this.hasBorder = hasBorder;
+ this.children = new ArrayList<PWRow>();
+ }
+
+ /**
+ * @see org.mihalis.opal.preferenceWindow.PWContainer#add(org.mihalis.opal.preferenceWindow.PWContainer)
+ */
+ @Override
+ public PWContainer add(final PWContainer element) {
+ if (!(element instanceof PWRow)) {
+ throw new UnsupportedOperationException("Can only add a PWRow.");
+ }
+ this.children.add((PWRow) element);
+ return this;
+ }
+
+ /**
+ * @see org.mihalis.opal.preferenceWindow.PWContainer#add(org.mihalis.opal.preferenceWindow.widgets.PWWidget)
+ */
+ @Override
+ public PWContainer add(final PWWidget widget) {
+ final PWRow row = new PWRow();
+ row.add(widget);
+ this.children.add(row);
+ return this;
+ }
+
+ /**
+ * @see org.mihalis.opal.preferenceWindow.PWContainer#build(org.eclipse.swt.widgets.Composite)
+ */
+ @Override
+ public void build(final Composite parent) {
+ final Composite composite;
+ if (this.hasBorder) {
+ composite = new Group(parent, SWT.NONE);
+ if (this.label != null && !this.label.trim().equals("")) {
+ ((Group) composite).setText(this.label);
+ }
+ } else {
+ composite = new Composite(parent, SWT.BORDER);
+ }
+
+ final int numCol = computeNumberOfColumns();
+
+ composite.setLayout(new GridLayout(numCol, false));
+ composite.setLayoutData(new GridData(GridData.BEGINNING, GridData.FILL, false, false, this.parentNumberOfColums, 1));
+
+ for (final PWRow row : this.children) {
+ row.setParentNumberOfColumns(numCol);
+ row.build(composite);
+ }
+
+ }
+
+ /**
+ * @return
+ */
+ private int computeNumberOfColumns() {
+ int numberOfColumns = 1;
+ for (final PWRow row : this.children) {
+ numberOfColumns = Math.max(numberOfColumns, row.getNumberOfColums());
+ }
+ return numberOfColumns;
+ }
+
+ /**
+ * @see org.mihalis.opal.preferenceWindow.PWRowGroup#checkParent(org.mihalis.opal.preferenceWindow.PWContainer)
+ */
+ @Override
+ protected void checkParent(final PWContainer parent) {
+ if (parent instanceof PWTab) {
+ return;
+ }
+ throw new UnsupportedOperationException("Bad parent, should be only PWTab ");
+ }
+
+ /**
+ * @see org.mihalis.opal.preferenceWindow.PWRowGroup#enableOrDisable()
+ */
+ @Override
+ public void enableOrDisable() {
+ if (this.enabler == null) {
+ return;
+ }
+
+ final boolean enabled = this.enabler.isEnabled();
+ for (final PWRow row : this.children) {
+ enableOrDisable(row, enabled);
+ }
+ }
+
+ /**
+ * Enable or disable a row
+ *
+ * @param row row to enable or disable
+ * @param enabled enable flag
+ */
+ private void enableOrDisable(final PWRow row, final boolean enabled) {
+ for (final PWWidget widget : row.widgets) {
+ final boolean widgetEnable = widget.enableOrDisable();
+
+ for (final Control c : widget.getControls()) {
+ if (!c.isDisposed()) {
+ c.setEnabled(enabled && widgetEnable);
+ }
+ }
+ }
+
+ }
+
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/PWRow.java b/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/PWRow.java
new file mode 100644
index 000000000..e38abdc0e
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/PWRow.java
@@ -0,0 +1,142 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON
+ * 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:
+ * Laurent CARON (laurent.caron at gmail dot com) - Initial implementation and API
+ *******************************************************************************/
+package org.mihalis.opal.preferenceWindow;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.mihalis.opal.preferenceWindow.widgets.PWButton;
+import org.mihalis.opal.preferenceWindow.widgets.PWLabel;
+import org.mihalis.opal.preferenceWindow.widgets.PWWidget;
+
+/**
+ * Instances of this class are rows
+ */
+public class PWRow extends PWRowGroup {
+ protected final List<PWWidget> widgets;
+
+ /**
+ * Constructor
+ */
+ public PWRow() {
+ this.widgets = new ArrayList<PWWidget>();
+ }
+
+ /**
+ * @see org.mihalis.opal.preferenceWindow.PWContainer#add(org.mihalis.opal.preferenceWindow.widgets.PWWidget)
+ */
+ @Override
+ public PWContainer add(final PWWidget widget) {
+ this.widgets.add(widget);
+ addColumn(widget.getNumberOfColumns());
+ return this;
+ }
+
+ /**
+ * @see org.mihalis.opal.preferenceWindow.PWContainer#add(org.mihalis.opal.preferenceWindow.PWContainer)
+ */
+ @Override
+ public PWContainer add(final PWContainer element) {
+ if (element instanceof PWRow || element instanceof PWGroup) {
+ return this.parent.add(element);
+ } else {
+ throw new UnsupportedOperationException("Can only add a PWGroup or a PWRow.");
+ }
+ }
+
+ /**
+ * @see org.mihalis.opal.preferenceWindow.PWContainer#build(org.eclipse.swt.widgets.Composite)
+ */
+ @Override
+ public void build(final Composite parent) {
+ final int size = this.widgets.size();
+ int columIndex = 0;
+ for (int i = 0; i < size; i++) {
+ final PWWidget widget = this.widgets.get(i);
+ final Control control = widget.checkAndBuild(parent);
+ if (control != null && control.getLayoutData() == null) {
+ final int colSpan;
+ final boolean grabExcessSpace;
+ final int alignment;
+ if (size == 1) {
+ if (widget.isSingleWidget()) {
+ colSpan = this.parentNumberOfColums;
+ } else {
+ colSpan = this.parentNumberOfColums - widget.getNumberOfColumns() + 1;
+ }
+ grabExcessSpace = true;
+ } else {
+ if (i == size - 1) {
+ colSpan = this.parentNumberOfColums - columIndex;
+ grabExcessSpace = widget.isGrabExcessSpace();
+ } else {
+ colSpan = 1;
+ grabExcessSpace = widget instanceof PWButton && i == 0 ? true : widget.isGrabExcessSpace();
+ }
+ }
+ columIndex += widget.getNumberOfColumns();
+
+ if (i == 0 && grabExcessSpace && size > 1) {
+ if (widget instanceof PWLabel || widget instanceof PWButton) {
+ alignment = GridData.END;
+ } else {
+ alignment = GridData.BEGINNING;
+ }
+ } else {
+ alignment = widget.getAlignment();
+ }
+
+ final GridData gd = new GridData(alignment, GridData.BEGINNING, grabExcessSpace, false, colSpan, 1);
+ gd.horizontalIndent = widget.getIndent();
+ gd.widthHint = widget.getWidth();
+ if (widget.getHeight() != -1) {
+ gd.heightHint = widget.getHeight();
+ }
+ control.setLayoutData(gd);
+ }
+ }
+ }
+
+ /**
+ * @see org.mihalis.opal.preferenceWindow.PWRowGroup#checkParent(org.mihalis.opal.preferenceWindow.PWContainer)
+ */
+ @Override
+ protected void checkParent(final PWContainer parent) {
+ if (parent instanceof PWTab || parent instanceof PWGroup) {
+ return;
+ }
+ throw new UnsupportedOperationException("Bad parent, should be only PWTab or PWGroup");
+ }
+
+ /**
+ * @see org.mihalis.opal.preferenceWindow.PWRowGroup#enableOrDisable()
+ */
+ @Override
+ public void enableOrDisable() {
+ if (this.enabler == null) {
+ return;
+ }
+
+ final boolean enabled = this.enabler.isEnabled();
+ for (final PWWidget widget : this.widgets) {
+ final boolean widgetEnable = widget.enableOrDisable();
+ for (final Control c : widget.getControls()) {
+ if (!c.isDisposed()) {
+ c.setEnabled(enabled && widgetEnable);
+ }
+ }
+ }
+ }
+
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/PWRowGroup.java b/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/PWRowGroup.java
new file mode 100644
index 000000000..63674bc29
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/PWRowGroup.java
@@ -0,0 +1,79 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON
+ * 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:
+ * Laurent CARON (laurent.caron at gmail dot com) - Initial implementation and API
+ *******************************************************************************/
+package org.mihalis.opal.preferenceWindow;
+
+import org.mihalis.opal.preferenceWindow.enabler.Enabler;
+
+/**
+ * Abstract class for both row and groups
+ */
+public abstract class PWRowGroup extends PWContainer {
+
+ protected int numberOfColumns;
+ protected int parentNumberOfColums;
+ protected PWContainer parent;
+ protected Enabler enabler;
+
+ /**
+ * Check if the parent is compatible with the object
+ *
+ * @param parent parent to check
+ * @throws UnsupportedOperationException if the parent is not compatible
+ * with the object
+ */
+ protected abstract void checkParent(PWContainer parent);
+
+ /**
+ * Enables or disables all elements stored in this group or row
+ */
+ public abstract void enableOrDisable();
+
+ /**
+ * Add a column to the current element
+ *
+ * @param number number of column to add
+ */
+ public void addColumn(final int number) {
+ this.numberOfColumns += number;
+ }
+
+ /**
+ * @return the number of columns of this group or row
+ */
+ public int getNumberOfColums() {
+ return this.numberOfColumns;
+ }
+
+ /**
+ * @param enabler the enabler to set
+ */
+ public PWRowGroup setEnabler(final Enabler enabler) {
+ this.enabler = enabler;
+ this.enabler.injectRowGroup(this);
+ return this;
+ }
+
+ /**
+ * @param parent the parent to set
+ */
+ public void setParent(final PWContainer parent) {
+ checkParent(parent);
+ this.parent = parent;
+ }
+
+ /**
+ * @param numberOfColumns the number of columns of the parent
+ */
+ public void setParentNumberOfColumns(final int numberOfColumns) {
+ this.parentNumberOfColums = numberOfColumns;
+ }
+
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/PWTab.java b/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/PWTab.java
new file mode 100644
index 000000000..03fc554be
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/PWTab.java
@@ -0,0 +1,111 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON
+ * 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:
+ * Laurent CARON (laurent.caron at gmail dot com) - Initial implementation and API
+ *******************************************************************************/
+package org.mihalis.opal.preferenceWindow;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Composite;
+import org.mihalis.opal.preferenceWindow.widgets.PWWidget;
+
+/**
+ * Instance of this class are tabs
+ *
+ */
+public class PWTab extends PWContainer {
+ private final Image image;
+ private final String text;
+ private final List<PWRowGroup> children;
+
+ /**
+ * Constructor
+ *
+ * @param image image associated to the tab
+ * @param text text associated to the tab
+ */
+ PWTab(final Image image, final String text) {
+ this.image = image;
+ this.text = text;
+ this.children = new ArrayList<PWRowGroup>();
+ }
+
+ /**
+ * @see org.mihalis.opal.preferenceWindow.PWContainer#add(org.mihalis.opal.preferenceWindow.PWContainer)
+ */
+ @Override
+ public PWContainer add(final PWContainer element) {
+ if (!(element instanceof PWGroup) && !(element instanceof PWRow)) {
+ throw new UnsupportedOperationException("Can only add a PWGroup or a PWRow.");
+ }
+ ((PWRowGroup) element).setParent(this);
+ this.children.add((PWRowGroup) element);
+ return this;
+ }
+
+ /**
+ * @see org.mihalis.opal.preferenceWindow.PWContainer#add(org.mihalis.opal.preferenceWindow.widgets.PWWidget)
+ */
+ @Override
+ public PWContainer add(final PWWidget widget) {
+ final PWRow row = new PWRow();
+ row.setParent(this);
+ row.add(widget);
+ this.children.add(row);
+ return this;
+ }
+
+ /**
+ * @see org.mihalis.opal.preferenceWindow.PWContainer#build(org.eclipse.swt.widgets.Composite)
+ */
+ @Override
+ public void build(final Composite parent) {
+ final int numberOfColumns = computeNumberOfColums();
+ parent.setLayout(new GridLayout(numberOfColumns, false));
+
+ for (final PWRowGroup rowGroup : this.children) {
+ rowGroup.setParentNumberOfColumns(numberOfColumns);
+ rowGroup.build(parent);
+ }
+
+ PreferenceWindow.getInstance().fireEnablers();
+
+ }
+
+ /**
+ * @return the total number of columns in this tab
+ */
+ private int computeNumberOfColums() {
+ int numberOfColumns = 1;
+ for (final PWRowGroup rowGroup : this.children) {
+ if (rowGroup instanceof PWRow) {
+ numberOfColumns = Math.max(numberOfColumns, rowGroup.getNumberOfColums());
+ }
+ }
+ return numberOfColumns;
+ }
+
+ /**
+ * @return the image associate to this tab
+ */
+ public Image getImage() {
+ return this.image;
+ }
+
+ /**
+ * @return the text associated to this tab
+ */
+ public String getText() {
+ return this.text;
+ }
+
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/PWTabContainer.java b/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/PWTabContainer.java
new file mode 100644
index 000000000..8bfe14c5f
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/PWTabContainer.java
@@ -0,0 +1,228 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON
+ * 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:
+ * Laurent CARON (laurent.caron at gmail dot com) - Initial implementation and API
+ *******************************************************************************/
+package org.mihalis.opal.preferenceWindow;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.eclipse.swt.SWT;
+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.Rectangle;
+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.Event;
+import org.eclipse.swt.widgets.Listener;
+import org.mihalis.opal.flatButton.FlatButton;
+import org.mihalis.opal.utils.SWTGraphicUtil;
+
+/**
+ * Instances of this class are a container that allows the user to select a tab
+ */
+class PWTabContainer extends Composite {
+
+ private final List<PWTab> tabs;
+ private Composite container;
+ private Image oldButtonContainerImage;
+ private final List<FlatButton> buttons;
+ private Composite buttonContainer;
+
+ /**
+ * Constructor
+ *
+ * @param parent parent composite
+ * @param style style (not used)
+ * @param tabs list of tabs
+ */
+ PWTabContainer(final Composite parent, final int style, final List<PWTab> tabs) {
+ super(parent, style);
+ this.tabs = new ArrayList<PWTab>();
+ this.tabs.addAll(tabs);
+
+ this.buttons = new ArrayList<FlatButton>();
+
+ final GridLayout gridLayout = new GridLayout(2, false);
+ gridLayout.marginWidth = gridLayout.marginHeight = 0;
+ gridLayout.horizontalSpacing = gridLayout.verticalSpacing = 0;
+ setLayout(gridLayout);
+
+ }
+
+ /**
+ * Build the container
+ */
+ void build() {
+ build(null);
+ }
+
+ void build(Color selectedTabColor) {
+
+ createButtonsContainer();
+ createButtons(selectedTabColor);
+ createContentContainer();
+
+ select(0);
+ }
+
+ /**
+ * Create the buttons container
+ */
+ private void createButtonsContainer() {
+ createContainer();
+ createButtonsContainerBackground();
+
+ }
+
+ /**
+ * Create the container
+ */
+ private void createContainer() {
+ this.buttonContainer = new Composite(this, SWT.NONE);
+ final GridData buttonContainerGridData = new GridData(GridData.FILL, GridData.FILL, true, false, 2, 1);
+ //buttonContainerGridData.heightHint = 63; // Original size (32x32)
+ //buttonContainerGridData.heightHint = 79; // Tizen fit size (48x48)
+ this.buttonContainer.setLayoutData(buttonContainerGridData);
+
+ this.buttonContainer.setBackground(getDisplay().getSystemColor(SWT.COLOR_WHITE));
+
+ final GridLayout gridLayout = new GridLayout(this.tabs.size(), false);
+ gridLayout.marginWidth = gridLayout.marginHeight = 0;
+ gridLayout.horizontalSpacing = gridLayout.verticalSpacing = 0;
+ gridLayout.marginBottom = 2;
+ this.buttonContainer.setLayout(gridLayout);
+ }
+
+ /**
+ * Create the background of the container
+ */
+ private void createButtonsContainerBackground() {
+ this.buttonContainer.addListener(SWT.Resize, new Listener() {
+
+ @Override
+ public void handleEvent(final Event event) {
+ final Rectangle rect = PWTabContainer.this.buttonContainer.getClientArea();
+ final Image image = new Image(getDisplay(), Math.max(1, rect.width), Math.max(1, rect.height));
+ final GC gc = new GC(image);
+ final Color grey = new Color(getDisplay(), 204, 204, 204);
+ gc.setForeground(grey);
+ gc.drawLine(0, rect.height - 1, rect.width, rect.height - 1);
+ grey.dispose();
+ gc.dispose();
+ PWTabContainer.this.buttonContainer.setBackgroundImage(image);
+ if (PWTabContainer.this.oldButtonContainerImage != null) {
+ PWTabContainer.this.oldButtonContainerImage.dispose();
+ }
+ PWTabContainer.this.oldButtonContainerImage = image;
+
+ }
+ });
+ SWTGraphicUtil.dispose(this.buttonContainer, this.oldButtonContainerImage);
+ }
+
+// /**
+// * Create the buttons
+// */
+// private void createButtons() {
+// createButtons(null);
+// }
+
+ private void createButtons(Color selectedTabColor) {
+ for (int i = 0; i < this.tabs.size(); i++) {
+ final PWTab tab = this.tabs.get(i);
+ final FlatButton button = new FlatButton(this.buttonContainer, SWT.NONE);
+ button.setText(tab.getText());
+ button.setImage(tab.getImage());
+
+ if(selectedTabColor != null) {
+ button.setSelectedColor(selectedTabColor);
+ }
+ SWTGraphicUtil.dispose(button, tab.getImage());
+
+ final GridData gd;
+ if (i == this.tabs.size() - 1) {
+ gd = new GridData(GridData.BEGINNING, GridData.BEGINNING, true, false);
+ } else {
+ gd = new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false);
+ }
+ if (i == 0) {
+ gd.horizontalIndent = 5;
+ }
+ gd.widthHint = 75;
+ button.setLayoutData(gd);
+
+ final int index = i;
+ button.addSelectionListener(new SelectionAdapter() {
+
+ /**
+ * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
+ */
+ @Override
+ public void widgetSelected(final SelectionEvent e) {
+ select(index);
+ }
+
+ });
+
+ this.buttons.add(button);
+
+ }
+ }
+
+ /**
+ * Select a given button
+ *
+ * @param index index of the selected button
+ */
+ private void select(final int index) {
+ for (final Control c : this.container.getChildren()) {
+ c.dispose();
+ }
+
+ this.tabs.get(index).build(this.container);
+ this.container.layout();
+
+ for (int i = 0; i < this.buttons.size(); i++) {
+ this.buttons.get(i).setSelection(i == index);
+ }
+ }
+
+ /**
+ * Create the content container, ie the composite that will contain all
+ * widgets
+ */
+ private void createContentContainer() {
+ this.container = new Composite(this, SWT.NONE);
+ final GridData tempContainer = new GridData(GridData.FILL, GridData.FILL, true, true, 2, 1);
+
+ int defaultSize = 350;
+ int notebookSize = 280;
+
+ //tempContainer.widthHint = 700;
+ tempContainer.heightHint = defaultSize;
+
+ Rectangle bounds = Display.getCurrent().getBounds();
+ if (bounds.height <= (768 + defaultSize - notebookSize)) {
+ tempContainer.heightHint = notebookSize; // 280px is fitted on 768px display
+ }
+
+ this.container.setLayoutData(tempContainer);
+ }
+
+ public Composite getContainer() {
+ return this.container;
+ }
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/PreferenceWindow.java b/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/PreferenceWindow.java
new file mode 100644
index 000000000..01de51e67
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/PreferenceWindow.java
@@ -0,0 +1,306 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON
+ * 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:
+ * Laurent CARON (laurent.caron at gmail dot com) - Initial implementation and API
+ *******************************************************************************/
+package org.mihalis.opal.preferenceWindow;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.SelectionAdapter;
+import org.eclipse.swt.events.SelectionEvent;
+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.Button;
+import org.eclipse.swt.widgets.Composite;
+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.mihalis.opal.preferenceWindow.widgets.PWWidget;
+import org.mihalis.opal.utils.ResourceManager;
+import org.mihalis.opal.utils.SWTGraphicUtil;
+
+/**
+ * This class is a preference window
+ *
+ */
+public class PreferenceWindow {
+ private final Map<String, ValueAndAssociatedWidgets> values;
+ private final List<PWTab> tabs;
+ private final Shell parentShell;
+ private boolean returnedValue;
+ private Shell shell;
+ private static PreferenceWindow instance;
+
+
+ /**
+ * Constructor
+ *
+ * @param parent parent shell (may be null)
+ * @param values a map that contains all values that will be displayed in
+ * widgets
+ */
+ private PreferenceWindow(final Shell parent, final Map<String, Object> values) {
+ this.parentShell = parent;
+ this.values = new HashMap<String, ValueAndAssociatedWidgets>(values.size());
+
+ for (final String key : values.keySet()) {
+ this.values.put(key, new ValueAndAssociatedWidgets(values.get(key)));
+ }
+
+ this.tabs = new ArrayList<PWTab>();
+ }
+
+ /**
+ * Create a preference window (a singleton)
+ *
+ * @param parent parent shell (may be null)
+ * @param values a map that contains all values that will be displayed in
+ * widgets
+ * @return
+ */
+ public static PreferenceWindow create(final Shell parent, final Map<String, Object> values) {
+ instance = new PreferenceWindow(parent, values);
+ return instance;
+ }
+
+ /**
+ * Create a preference window (a singleton)
+ *
+ * @param values a map that contains all values that will be displayed in
+ * widgets
+ * @return
+ */
+ public static PreferenceWindow create(final Map<String, Object> values) {
+ instance = new PreferenceWindow(null, values);
+ return instance;
+ }
+
+ /**
+ * @return an instance of the preference window
+ */
+ public static PreferenceWindow getInstance() {
+ if (instance == null) {
+ throw new NullPointerException("The instance of PreferenceWindow has not yet been created or has been destroyed.");
+ }
+ return instance;
+ }
+
+ /**
+ * Add a tab to the preference window
+ *
+ * @param image image associated to the tab
+ * @param text text associated to the image
+ * @return the
+ */
+ public PWTab addTab(final Image image, final String text) {
+ final PWTab tab = new PWTab(image, text);
+ this.tabs.add(tab);
+ return tab;
+ }
+
+ /**
+ * Add a widget that is linked to a given property
+ *
+ * @param propertyKey the property
+ * @param widget the widget
+ */
+ public void addWidgetLinkedTo(final String propertyKey, final PWWidget widget) {
+ if (!this.values.containsKey(propertyKey)) {
+ this.values.put(propertyKey, new ValueAndAssociatedWidgets(null));
+ }
+ this.values.get(propertyKey).addWidget(widget);
+ }
+
+ /**
+ * Add a row group that is linked to a given property
+ *
+ * @param propertyKey the property
+ * @param rowGroup the widget
+ */
+ public void addRowGroupLinkedTo(final String propertyKey, final PWRowGroup rowGroup) {
+ if (!this.values.containsKey(propertyKey)) {
+ this.values.put(propertyKey, new ValueAndAssociatedWidgets(null));
+ }
+ this.values.get(propertyKey).addRowGroup(rowGroup);
+ }
+
+ /**
+ * Open the preference window
+ *
+ * @return <code>true</code> if the user pressed on the Ok button,
+ * <code>false</code> if the user pressed on the Cancel button
+ */
+ public boolean open() {
+ if (this.parentShell == null) {
+ this.shell = new Shell(SWT.SHELL_TRIM);
+ } else {
+ this.shell = new Shell(instance.parentShell, SWT.SHELL_TRIM);
+ }
+
+ this.shell.addListener(SWT.Dispose, new Listener() {
+
+ @Override
+ public void handleEvent(final Event event) {
+ instance = null;
+ }
+ });
+
+ buildShell();
+ openShell();
+
+ return this.returnedValue;
+ }
+
+ /**
+ * Builds the shell
+ */
+ private void buildShell() {
+ this.shell.setText(ResourceManager.getLabel(ResourceManager.PREFERENCES));
+ final GridLayout gridLayout = new GridLayout(2, false);
+ gridLayout.marginWidth = gridLayout.marginHeight = 0;
+ gridLayout.horizontalSpacing = gridLayout.verticalSpacing = 0;
+ this.shell.setLayout(gridLayout);
+ final PWTabContainer container = new PWTabContainer(this.shell, SWT.NONE, this.tabs);
+ container.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, true, 2, 1));
+ container.build();
+
+ final Label sep = new Label(this.shell, SWT.SEPARATOR | SWT.HORIZONTAL);
+ sep.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, true, 2, 1));
+
+ buildButtons();
+
+ }
+
+ /**
+ * Builds the Tabs for inner composite
+ *
+ * @author Jihoon Song {@literal <jihoon80.song@samsung.com>} (S-Core)
+ */
+ public void buildTabs(Composite parent) {
+ buildTabs(parent, null);
+ }
+
+ public void buildTabs(Composite parent, Color selectedTabColor) {
+ final PWTabContainer container = new PWTabContainer(parent, SWT.BORDER, this.tabs);
+ container.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, true, 2, 1));
+ container.build(selectedTabColor);
+ }
+
+ /**
+ * Builds the buttons
+ */
+ private void buildButtons() {
+ final Button buttonOK = new Button(this.shell, SWT.PUSH);
+ buttonOK.setText(ResourceManager.getLabel(ResourceManager.OK));
+ final GridData gridDataOk = new GridData(GridData.END, GridData.END, true, false);
+ gridDataOk.widthHint = 100;
+ buttonOK.setLayoutData(gridDataOk);
+ buttonOK.addSelectionListener(new SelectionAdapter() {
+
+ /**
+ * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
+ */
+ @Override
+ public void widgetSelected(final SelectionEvent e) {
+ PreferenceWindow.this.returnedValue = true;
+ PreferenceWindow.this.shell.dispose();
+ }
+
+ });
+ this.shell.setDefaultButton(buttonOK);
+
+ final Button buttonCancel = new Button(this.shell, SWT.PUSH);
+ buttonCancel.setText(ResourceManager.getLabel(ResourceManager.CANCEL));
+ final GridData gridDataCancel = new GridData(GridData.BEGINNING, GridData.END, false, false);
+ gridDataCancel.widthHint = 100;
+ buttonCancel.setLayoutData(gridDataCancel);
+ buttonCancel.addSelectionListener(new SelectionAdapter() {
+
+ /**
+ * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
+ */
+ @Override
+ public void widgetSelected(final SelectionEvent e) {
+ PreferenceWindow.this.returnedValue = false;
+ PreferenceWindow.this.shell.dispose();
+ }
+
+ });
+ }
+
+ /**
+ * Open the shell
+ */
+ private void openShell() {
+ this.shell.pack();
+ this.shell.open();
+ SWTGraphicUtil.centerShell(this.shell);
+
+ while (!this.shell.isDisposed()) {
+ if (!this.shell.getDisplay().readAndDispatch()) {
+ this.shell.getDisplay().sleep();
+ }
+ }
+
+ }
+
+ /**
+ * Fire all enablers
+ */
+ public void fireEnablers() {
+ for (final String key : this.values.keySet()) {
+ this.values.get(key).fireValueChanged();
+ }
+ }
+
+ /**
+ * @param key
+ * @return the value associated to the <i>key</i>
+ */
+ public Object getValueFor(final String key) {
+ if (this.values.containsKey(key)) {
+ return this.values.get(key).getValue();
+ }
+ return null;
+ }
+
+ /**
+ * @return the list of all values
+ */
+ public Map<String, Object> getValues() {
+ final Map<String, Object> returnedValues = new HashMap<String, Object>();
+ for (final String key : this.values.keySet()) {
+ returnedValues.put(key, this.values.get(key).getValue());
+ }
+ return returnedValues;
+ }
+
+ /**
+ * Store a value associated to the key
+ *
+ * @param key
+ * @param value
+ */
+ public void setValue(final String key, final Object value) {
+ if (this.values.containsKey(key)) {
+ this.values.get(key).setValue(value);
+ } else {
+ this.values.put(key, new ValueAndAssociatedWidgets(value));
+ }
+
+ }
+
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/ValueAndAssociatedWidgets.java b/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/ValueAndAssociatedWidgets.java
new file mode 100644
index 000000000..5d13736fd
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/ValueAndAssociatedWidgets.java
@@ -0,0 +1,79 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON
+ * 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:
+ * Laurent CARON (laurent.caron at gmail dot com) - Initial implementation and API
+ *******************************************************************************/
+package org.mihalis.opal.preferenceWindow;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.mihalis.opal.preferenceWindow.widgets.PWWidget;
+
+/**
+ * This POJO contains a value a list of widgets that depends on a given property
+ *
+ */
+class ValueAndAssociatedWidgets {
+ private Object value;
+ private final List<PWWidget> widgets;
+ private final List<PWRowGroup> rowGroups;
+
+ /**
+ * Constructor
+ *
+ * @param value associated value
+ */
+ ValueAndAssociatedWidgets(final Object value) {
+ this.value = value;
+ this.widgets = new ArrayList<PWWidget>();
+ this.rowGroups = new ArrayList<PWRowGroup>();
+ }
+
+ /**
+ * @param widget dependant widget
+ */
+ void addWidget(final PWWidget widget) {
+ this.widgets.add(widget);
+ }
+
+ /**
+ * @param rowGroup dependant row or group
+ */
+ void addRowGroup(final PWRowGroup rowGroup) {
+ this.rowGroups.add(rowGroup);
+ }
+
+ /**
+ * @return the value stored in the instance
+ */
+ Object getValue() {
+ return this.value;
+ }
+
+ /**
+ * @param value new value stored in this instance
+ */
+ void setValue(final Object value) {
+ this.value = value;
+ fireValueChanged();
+ }
+
+ /**
+ * Fire events when the value has changed
+ */
+ void fireValueChanged() {
+ for (final PWRowGroup rowGroup : this.rowGroups) {
+ rowGroup.enableOrDisable();
+ }
+
+ for (final PWWidget widget : this.widgets) {
+ widget.enableOrDisable();
+ }
+ }
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/enabler/EnabledIfEquals.java b/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/enabler/EnabledIfEquals.java
new file mode 100644
index 000000000..b29db9dce
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/enabler/EnabledIfEquals.java
@@ -0,0 +1,44 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON
+ * 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:
+ * Laurent CARON (laurent.caron at gmail dot com) - Initial implementation and API
+ *******************************************************************************/
+package org.mihalis.opal.preferenceWindow.enabler;
+
+import org.mihalis.opal.preferenceWindow.PreferenceWindow;
+
+/**
+ * This enabler is used to enable a widget if a property is equal to a given
+ * value
+ */
+public class EnabledIfEquals extends Enabler {
+ private final Object value;
+
+ /**
+ * Constructor
+ *
+ * @param prop property to evaluate
+ * @param value condition value
+ */
+ public EnabledIfEquals(final String prop, final Object value) {
+ super(prop);
+ this.value = value;
+ }
+
+ /**
+ * @see org.mihalis.opal.preferenceWindow.enabler.Enabler#isEnabled()
+ */
+ @Override
+ public boolean isEnabled() {
+ final Object propValue = PreferenceWindow.getInstance().getValueFor(this.prop);
+ if (this.value == null) {
+ return propValue == null;
+ }
+ return this.value.equals(propValue);
+ }
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/enabler/EnabledIfNotEquals.java b/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/enabler/EnabledIfNotEquals.java
new file mode 100644
index 000000000..7f4e9c130
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/enabler/EnabledIfNotEquals.java
@@ -0,0 +1,44 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON
+ * 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:
+ * Laurent CARON (laurent.caron at gmail dot com) - Initial implementation and API
+ *******************************************************************************/
+package org.mihalis.opal.preferenceWindow.enabler;
+
+import org.mihalis.opal.preferenceWindow.PreferenceWindow;
+
+/**
+ * This enabler is used to enable a widget if a property is not equal to a given
+ * value
+ */
+public class EnabledIfNotEquals extends Enabler {
+ private final Object value;
+
+ /**
+ * Constructor
+ *
+ * @param prop property to evaluate
+ * @param value condition value
+ */
+ public EnabledIfNotEquals(final String prop, final Object value) {
+ super(prop);
+ this.value = value;
+ }
+
+ /**
+ * @see org.mihalis.opal.preferenceWindow.enabler.Enabler#isEnabled()
+ */
+ @Override
+ public boolean isEnabled() {
+ final Object propValue = PreferenceWindow.getInstance().getValueFor(this.prop);
+ if (this.value == null) {
+ return propValue == null;
+ }
+ return !this.value.equals(propValue);
+ }
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/enabler/EnabledIfTrue.java b/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/enabler/EnabledIfTrue.java
new file mode 100644
index 000000000..969e2c58a
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/enabler/EnabledIfTrue.java
@@ -0,0 +1,46 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON
+ * 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:
+ * Laurent CARON (laurent.caron at gmail dot com) - Initial implementation and API
+ *******************************************************************************/
+package org.mihalis.opal.preferenceWindow.enabler;
+
+import org.mihalis.opal.preferenceWindow.PreferenceWindow;
+
+/**
+ * This enabler is used to enable a widget if a boolean property is true
+ */
+public class EnabledIfTrue extends Enabler {
+
+ /**
+ * Constructor
+ *
+ * @param prop boolean property
+ */
+ public EnabledIfTrue(final String prop) {
+ super(prop);
+ }
+
+ /**
+ * @see org.mihalis.opal.preferenceWindow.enabler.Enabler#isEnabled()
+ */
+ @Override
+ public boolean isEnabled() {
+ final Object value = PreferenceWindow.getInstance().getValueFor(this.prop);
+
+ if (value != null && !(value instanceof Boolean)) {
+ throw new UnsupportedOperationException("Impossible to evaluate [" + this.prop + "] because it is not a Boolean !");
+ }
+
+ if (value == null) {
+ return true;
+ }
+
+ return ((Boolean) value).booleanValue();
+ }
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/enabler/Enabler.java b/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/enabler/Enabler.java
new file mode 100644
index 000000000..3b0e04afd
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/enabler/Enabler.java
@@ -0,0 +1,57 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON
+ * 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:
+ * Laurent CARON (laurent.caron at gmail dot com) - Initial implementation and API
+ *******************************************************************************/
+package org.mihalis.opal.preferenceWindow.enabler;
+
+import org.mihalis.opal.preferenceWindow.PWRowGroup;
+import org.mihalis.opal.preferenceWindow.PreferenceWindow;
+import org.mihalis.opal.preferenceWindow.widgets.PWWidget;
+
+/**
+ * This is the abstract class of all Enablers. An enabler is an object used to
+ * enable or disable a widget depending on a value of a stored property.
+ */
+public abstract class Enabler {
+
+ protected String prop;
+
+ /**
+ * Constructor
+ *
+ * @param prop property linked to the enabler.
+ */
+ public Enabler(final String prop) {
+ this.prop = prop;
+ }
+
+ /**
+ * @return the evaluation condition
+ */
+ public abstract boolean isEnabled();
+
+ /**
+ * Link a widget to the enabler
+ *
+ * @param widget widget to link
+ */
+ public void injectWidget(final PWWidget widget) {
+ PreferenceWindow.getInstance().addWidgetLinkedTo(this.prop, widget);
+ }
+
+ /**
+ * Link a row or a group to the enabler
+ *
+ * @param rowGroup RowGroup to link
+ */
+ public void injectRowGroup(final PWRowGroup rowGroup) {
+ PreferenceWindow.getInstance().addRowGroupLinkedTo(this.prop, rowGroup);
+ }
+
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWButton.java b/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWButton.java
new file mode 100644
index 000000000..4762b8050
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWButton.java
@@ -0,0 +1,63 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON
+ * 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:
+ * Laurent CARON (laurent.caron at gmail dot com) - Initial implementation and API
+ *******************************************************************************/
+package org.mihalis.opal.preferenceWindow.widgets;
+
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.SelectionListener;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+
+/**
+ * Instances of this class are buttons
+ *
+ */
+public class PWButton extends PWWidget {
+ private final SelectionListener listener;
+
+ /**
+ * Constructor
+ *
+ * @param label associated label
+ * @param listener selection listener
+ */
+ public PWButton(final String label, final SelectionListener listener) {
+ super(label, null, 1, true);
+ this.listener = listener;
+ }
+
+ /**
+ * @see org.mihalis.opal.preferenceWindow.widgets.PWWidget#build(org.eclipse.swt.widgets.Composite)
+ */
+ @Override
+ public Control build(final Composite parent) {
+ final Button button = new Button(parent, SWT.PUSH);
+ addControl(button);
+ if (getLabel() == null) {
+ throw new UnsupportedOperationException("You need to set a label for a button");
+ } else {
+ button.setText(getLabel());
+ }
+ if (this.listener != null) {
+ button.addSelectionListener(this.listener);
+ }
+
+ return button;
+
+ }
+
+ /**
+ * @see org.mihalis.opal.preferenceWindow.widgets.PWWidget#check()
+ */
+ @Override
+ public void check() {
+ }
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWCheckbox.java b/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWCheckbox.java
new file mode 100644
index 000000000..8dc7f367e
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWCheckbox.java
@@ -0,0 +1,76 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON
+ * 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:
+ * Laurent CARON (laurent.caron at gmail dot com) - Initial implementation and API
+ *******************************************************************************/
+package org.mihalis.opal.preferenceWindow.widgets;
+
+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.swt.widgets.Control;
+import org.mihalis.opal.preferenceWindow.PreferenceWindow;
+
+/**
+ * Instances of this class are checkboxes
+ */
+public class PWCheckbox extends PWWidget {
+
+ /**
+ * Constructor
+ *
+ * @param label associated label
+ * @param propertyKey associated key
+ */
+ public PWCheckbox(final String label, final String propertyKey) {
+ super(label, propertyKey, 1, true);
+ }
+
+ /**
+ * @see org.mihalis.opal.preferenceWindow.widgets.PWWidget#build(org.eclipse.swt.widgets.Composite)
+ */
+ @Override
+ public Control build(final Composite parent) {
+ if (getLabel() == null) {
+ throw new UnsupportedOperationException("Please specify a label for a checkbox");
+ }
+ final Button button = new Button(parent, SWT.CHECK);
+ addControl(button);
+ button.setText(getLabel());
+ final boolean originalSelection = (Boolean) PreferenceWindow.getInstance().getValueFor(getPropertyKey());
+ button.setSelection(originalSelection);
+
+ button.addSelectionListener(new SelectionAdapter() {
+ /**
+ * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
+ */
+ @Override
+ public void widgetSelected(final SelectionEvent e) {
+ PreferenceWindow.getInstance().setValue(getPropertyKey(), button.getSelection());
+ }
+ });
+ return button;
+ }
+
+ /**
+ * @see org.mihalis.opal.preferenceWindow.widgets.PWWidget#check()
+ */
+ @Override
+ public void check() {
+ final Object value = PreferenceWindow.getInstance().getValueFor(getPropertyKey());
+ if (value == null) {
+ PreferenceWindow.getInstance().setValue(getPropertyKey(), new Boolean(false));
+ } else {
+ if (!(value instanceof Boolean)) {
+ throw new UnsupportedOperationException("The property '" + getPropertyKey() + "' has to be a Boolean because it is associated to a checkbox");
+ }
+ }
+ }
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWChooser.java b/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWChooser.java
new file mode 100644
index 000000000..318215a50
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWChooser.java
@@ -0,0 +1,82 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON
+ * 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:
+ * Laurent CARON (laurent.caron at gmail dot com) - Initial implementation and API
+ *******************************************************************************/
+package org.mihalis.opal.preferenceWindow.widgets;
+
+import org.eclipse.swt.SWT;
+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.Text;
+import org.mihalis.opal.utils.ResourceManager;
+
+/**
+ * Abstract class for chooser widgets
+ *
+ */
+public abstract class PWChooser extends PWWidget {
+
+ /**
+ * Constructor
+ *
+ * @param label associated label
+ * @param propertyKey associated key
+ */
+ public PWChooser(final String label, final String propertyKey) {
+ super(label, propertyKey, 3, false);
+ setGrabExcessSpace(false);
+ }
+
+ /**
+ * @see org.mihalis.opal.preferenceWindow.widgets.PWWidget#build(org.eclipse.swt.widgets.Composite)
+ */
+ @Override
+ public Control build(final Composite parent) {
+ final Label label = new Label(parent, SWT.NONE);
+
+ if (getLabel() == null) {
+ throw new UnsupportedOperationException("You need to set a label for a directory or a dialog chooser");
+ } else {
+ label.setText(getLabel());
+ }
+ addControl(label);
+ final GridData labelGridData = new GridData(GridData.END, GridData.BEGINNING, false, false);
+ labelGridData.horizontalIndent = getIndent();
+ label.setLayoutData(labelGridData);
+
+ final Text text = new Text(parent, SWT.BORDER | SWT.READ_ONLY);
+ addControl(text);
+ final GridData textGridData = new GridData(GridData.FILL, GridData.BEGINNING, true, false);
+ text.setLayoutData(textGridData);
+
+ final Button button = new Button(parent, SWT.PUSH);
+ addControl(button);
+ final GridData buttonGridData = new GridData(GridData.FILL, GridData.BEGINNING, false, false);
+ buttonGridData.widthHint = 150;
+ button.setText(ResourceManager.getLabel(ResourceManager.CHOOSE) + "...");
+ button.setLayoutData(buttonGridData);
+
+ setButtonAction(text, button);
+
+ return button;
+
+ }
+
+ /**
+ * Code executed when the user presses the button
+ *
+ * @param text text box
+ * @param button associated button
+ */
+ protected abstract void setButtonAction(Text text, Button button);
+
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWColorChooser.java b/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWColorChooser.java
new file mode 100644
index 000000000..0d3b1b327
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWColorChooser.java
@@ -0,0 +1,133 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON
+ * 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:
+ * Laurent CARON (laurent.caron at gmail dot com) - Initial implementation and API
+ *******************************************************************************/
+package org.mihalis.opal.preferenceWindow.widgets;
+
+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.RGB;
+import org.eclipse.swt.layout.GridData;
+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.Event;
+import org.eclipse.swt.widgets.Listener;
+import org.mihalis.opal.preferenceWindow.PreferenceWindow;
+import org.mihalis.opal.utils.SWTGraphicUtil;
+
+/**
+ * Instances of this class are used to select a color
+ *
+ */
+public class PWColorChooser extends PWWidget {
+
+ private Color color;
+
+ /**
+ * Constructor
+ *
+ * @param label associated label
+ * @param propertyKey associated key
+ */
+ public PWColorChooser(final String label, final String propertyKey) {
+ super(label, propertyKey, label == null ? 1 : 2, false);
+ }
+
+ /**
+ * @see org.mihalis.opal.preferenceWindow.widgets.PWWidget#build(org.eclipse.swt.widgets.Composite)
+ */
+ @Override
+ public Control build(final Composite parent) {
+ final RGB rgb = (RGB) PreferenceWindow.getInstance().getValueFor(getPropertyKey());
+
+ if (rgb == null) {
+ this.color = Display.getDefault().getSystemColor(SWT.COLOR_WHITE);
+ } else {
+ this.color = new Color(Display.getDefault(), rgb);
+ }
+
+ buildLabel(parent, GridData.CENTER);
+ final Button button = new Button(parent, SWT.PUSH);
+ addControl(button);
+
+ button.addListener(SWT.Resize, new Listener() {
+ @Override
+ public void handleEvent(final Event event) {
+ drawButton(button);
+ }
+ });
+
+ button.addListener(SWT.Selection, new Listener() {
+
+ @Override
+ public void handleEvent(final Event event) {
+ final ColorDialog dialog = new ColorDialog(button.getShell());
+ final RGB result = dialog.open();
+ if (result != null) {
+ SWTGraphicUtil.dispose(PWColorChooser.this.color);
+ PWColorChooser.this.color = new Color(button.getDisplay(), result);
+ drawButton(button);
+ PreferenceWindow.getInstance().setValue(getPropertyKey(), result);
+ }
+ }
+ });
+
+ button.addListener(SWT.Dispose, new Listener() {
+
+ @Override
+ public void handleEvent(final Event event) {
+ SWTGraphicUtil.dispose(PWColorChooser.this.color);
+ }
+ });
+
+ return button;
+ }
+
+ /**
+ * @param button button on which we draw the rectangle
+ */
+ protected void drawButton(final Button button) {
+ final int height = (int) button.getFont().getFontData()[0].height;
+ final int width = button.getBounds().width - 16;
+
+ final Image newImage = new Image(button.getDisplay(), Math.max(1, width), Math.max(1, height));
+
+ final GC gc = new GC(newImage);
+ gc.setBackground(PWColorChooser.this.color);
+ gc.fillRectangle(0, 0, width, height);
+
+ gc.setForeground(button.getDisplay().getSystemColor(SWT.COLOR_BLACK));
+ gc.drawRectangle(0, 0, width - 1, height - 1);
+
+ gc.dispose();
+
+ button.setImage(newImage);
+ }
+
+ /**
+ * @see org.mihalis.opal.preferenceWindow.widgets.PWWidget#check()
+ */
+ @Override
+ public void check() {
+ final Object value = PreferenceWindow.getInstance().getValueFor(getPropertyKey());
+ if (value == null) {
+ PreferenceWindow.getInstance().setValue(getPropertyKey(), null);
+ } else {
+ if (!(value instanceof RGB)) {
+ throw new UnsupportedOperationException("The property '" + getPropertyKey() + "' has to be a RGB because it is associated to a color chooser");
+ }
+ }
+ }
+
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWCombo.java b/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWCombo.java
new file mode 100644
index 000000000..1960011bc
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWCombo.java
@@ -0,0 +1,107 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON
+ * 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:
+ * Laurent CARON (laurent.caron at gmail dot com) - Initial implementation and API
+ *******************************************************************************/
+package org.mihalis.opal.preferenceWindow.widgets;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.widgets.Combo;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Event;
+import org.eclipse.swt.widgets.Listener;
+import org.mihalis.opal.preferenceWindow.PreferenceWindow;
+
+/**
+ * Instances of this class are Combo
+ *
+ */
+public class PWCombo extends PWWidget {
+
+ private final List<Object> data;
+ private final boolean editable;
+
+ /**
+ * Constructor
+ *
+ * @param label associated label
+ * @param propertyKey associated key
+ */
+ public PWCombo(final String label, final String propertyKey, final Object... values) {
+ this(label, propertyKey, false, values);
+ }
+
+ /**
+ * Constructor
+ *
+ * @param label associated label
+ * @param propertyKey associated key
+ */
+ public PWCombo(final String label, final String propertyKey, final boolean editable, final Object... values) {
+ super(label, propertyKey, label == null ? 1 : 2, false);
+ this.data = new ArrayList<Object>(Arrays.asList(values));
+ this.editable = editable;
+ }
+
+ /**
+ * @see org.mihalis.opal.preferenceWindow.widgets.PWWidget#build(org.eclipse.swt.widgets.Composite)
+ */
+ @Override
+ public Control build(final Composite parent) {
+ buildLabel(parent, GridData.CENTER);
+
+ final Combo combo = new Combo(parent, SWT.BORDER | (this.editable ? SWT.NONE : SWT.READ_ONLY));
+ addControl(combo);
+
+ for (int i = 0; i < this.data.size(); i++) {
+ final Object datum = this.data.get(i);
+ combo.add(datum.toString());
+ if (datum.equals(PreferenceWindow.getInstance().getValueFor(getPropertyKey()))) {
+ combo.select(i);
+ }
+ }
+
+ combo.addListener(SWT.Modify, new Listener() {
+
+ @Override
+ public void handleEvent(final Event event) {
+ PreferenceWindow.getInstance().setValue(getPropertyKey(), PWCombo.this.data.get(combo.getSelectionIndex()));
+ }
+ });
+
+ return combo;
+ }
+
+ /**
+ * @see org.mihalis.opal.preferenceWindow.widgets.PWWidget#check()
+ */
+ @Override
+ public void check() {
+ final Object value = PreferenceWindow.getInstance().getValueFor(getPropertyKey());
+ if (value == null) {
+ PreferenceWindow.getInstance().setValue(getPropertyKey(), null);
+ } else {
+ if (this.editable && !(value instanceof String)) {
+ throw new UnsupportedOperationException("The property '" + getPropertyKey() + "' has to be a String because it is associated to an editable combo");
+ }
+
+ if (!this.data.isEmpty()) {
+ if (!value.getClass().equals(this.data.get(0).getClass())) {
+ throw new UnsupportedOperationException("The property '" + getPropertyKey() + "' has to be a " + this.data.get(0).getClass() + " because it is associated to a combo");
+ }
+ }
+
+ }
+ }
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWDirectoryChooser.java b/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWDirectoryChooser.java
new file mode 100644
index 000000000..db0cd9b13
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWDirectoryChooser.java
@@ -0,0 +1,78 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON
+ * 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:
+ * Laurent CARON (laurent.caron at gmail dot com) - Initial implementation and API
+ *******************************************************************************/
+package org.mihalis.opal.preferenceWindow.widgets;
+
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.DirectoryDialog;
+import org.eclipse.swt.widgets.Event;
+import org.eclipse.swt.widgets.Listener;
+import org.eclipse.swt.widgets.Text;
+import org.mihalis.opal.preferenceWindow.PreferenceWindow;
+import org.mihalis.opal.utils.ResourceManager;
+
+/**
+ * Instances of this class are used to select a directory
+ */
+public class PWDirectoryChooser extends PWChooser {
+
+ /**
+ * Constructor
+ *
+ * @param label associated label
+ * @param propertyKey associated key
+ */
+ public PWDirectoryChooser(final String label, final String propertyKey) {
+ super(label, propertyKey);
+ }
+
+ /**
+ * @see org.mihalis.opal.preferenceWindow.widgets.PWChooser#setButtonAction(org.eclipse.swt.widgets.Text,
+ * org.eclipse.swt.widgets.Button)
+ */
+ @Override
+ protected void setButtonAction(final Text text, final Button button) {
+
+ final String originalDirectory = (String) PreferenceWindow.getInstance().getValueFor(getPropertyKey());
+ text.setText(originalDirectory);
+
+ button.addListener(SWT.Selection, new Listener() {
+
+ @Override
+ public void handleEvent(final Event event) {
+ final DirectoryDialog dialog = new DirectoryDialog(text.getShell());
+ dialog.setMessage(ResourceManager.getLabel(ResourceManager.CHOOSE_DIRECTORY));
+ final String result = dialog.open();
+ if (result != null) {
+ text.setText(result);
+ PreferenceWindow.getInstance().setValue(getPropertyKey(), result);
+ }
+
+ }
+ });
+ }
+
+ /**
+ * @see org.mihalis.opal.preferenceWindow.widgets.PWWidget#check()
+ */
+ @Override
+ public void check() {
+ final Object value = PreferenceWindow.getInstance().getValueFor(getPropertyKey());
+ if (value == null) {
+ PreferenceWindow.getInstance().setValue(getPropertyKey(), "");
+ } else {
+ if (!(value instanceof String)) {
+ throw new UnsupportedOperationException("The property '" + getPropertyKey() + "' has to be a String because it is associated to a directory chooser");
+ }
+ }
+ }
+
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWFileChooser.java b/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWFileChooser.java
new file mode 100644
index 000000000..421aa0e76
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWFileChooser.java
@@ -0,0 +1,75 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON
+ * 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:
+ * Laurent CARON (laurent.caron at gmail dot com) - Initial implementation and API
+ *******************************************************************************/
+package org.mihalis.opal.preferenceWindow.widgets;
+
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Event;
+import org.eclipse.swt.widgets.FileDialog;
+import org.eclipse.swt.widgets.Listener;
+import org.eclipse.swt.widgets.Text;
+import org.mihalis.opal.preferenceWindow.PreferenceWindow;
+
+/**
+ * Instances of this class are used to select a file
+ */
+public class PWFileChooser extends PWChooser {
+
+ /**
+ * Constructor
+ *
+ * @param label associated label
+ * @param propertyKey associated key
+ */
+ public PWFileChooser(final String label, final String propertyKey) {
+ super(label, propertyKey);
+ }
+
+ /**
+ * @see org.mihalis.opal.preferenceWindow.widgets.PWChooser#setButtonAction(org.eclipse.swt.widgets.Text,
+ * org.eclipse.swt.widgets.Button)
+ */
+ @Override
+ protected void setButtonAction(final Text text, final Button button) {
+ final String originalFile = (String) PreferenceWindow.getInstance().getValueFor(getPropertyKey());
+ text.setText(originalFile);
+
+ button.addListener(SWT.Selection, new Listener() {
+ @Override
+ public void handleEvent(final Event event) {
+ final FileDialog dialog = new FileDialog(text.getShell(), SWT.OPEN);
+ final String result = dialog.open();
+ if (result != null) {
+ text.setText(result);
+ PreferenceWindow.getInstance().setValue(getPropertyKey(), result);
+ }
+
+ }
+ });
+
+ }
+
+ /**
+ * @see org.mihalis.opal.preferenceWindow.widgets.PWWidget#check()
+ */
+ @Override
+ public void check() {
+ final Object value = PreferenceWindow.getInstance().getValueFor(getPropertyKey());
+ if (value == null) {
+ PreferenceWindow.getInstance().setValue(getPropertyKey(), "");
+ } else {
+ if (!(value instanceof String)) {
+ throw new UnsupportedOperationException("The property '" + getPropertyKey() + "' has to be a String because it is associated to a file chooser");
+ }
+ }
+ }
+
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWFloatText.java b/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWFloatText.java
new file mode 100644
index 000000000..db6446816
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWFloatText.java
@@ -0,0 +1,114 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON
+ * 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:
+ * Laurent CARON (laurent.caron at gmail dot com) - Initial implementation and API
+ *******************************************************************************/
+package org.mihalis.opal.preferenceWindow.widgets;
+
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.VerifyEvent;
+import org.eclipse.swt.events.VerifyListener;
+import org.mihalis.opal.preferenceWindow.PreferenceWindow;
+import org.mihalis.opal.utils.StringUtil;
+
+/**
+ * Instances of this class are text box to type floats
+ */
+public class PWFloatText extends PWText {
+
+ /**
+ * Constructor
+ *
+ * @param label associated label
+ * @param propertyKey associated key
+ */
+ public PWFloatText(final String label, final String propertyKey) {
+ super(label, propertyKey);
+ }
+
+ /**
+ * @see org.mihalis.opal.preferenceWindow.widgets.PWText#addVerifyListeners()
+ */
+ @Override
+ public void addVerifyListeners() {
+ this.text.addVerifyListener(new VerifyListener() {
+
+ @Override
+ public void verifyText(final VerifyEvent e) {
+ if (e.character != 0 && !Character.isDigit(e.character) && e.keyCode != SWT.BS && e.keyCode != SWT.DEL && e.character != '.' && e.character != ',') {
+ e.doit = false;
+ return;
+ }
+
+ e.doit = verifyEntry(e.text, e.keyCode);
+
+ }
+ });
+
+ }
+
+ /**
+ * Check if an entry is a float
+ *
+ * @param entry text typed by the user
+ * @param keyCode key code
+ * @return true if the user typed a float value, false otherwise
+ */
+ private boolean verifyEntry(final String entry, final int keyCode) {
+ final String work;
+ if (keyCode == SWT.DEL) {
+ work = StringUtil.removeCharAt(this.text.getText(), this.text.getCaretPosition());
+ } else if (keyCode == SWT.BS && this.text.getCaretPosition() == 0) {
+ work = StringUtil.removeCharAt(this.text.getText(), this.text.getCaretPosition() - 1);
+ } else if (keyCode == 0) {
+ work = entry;
+ } else {
+ work = StringUtil.insertString(this.text.getText(), entry, this.text.getCaretPosition());
+ }
+
+ try {
+ Double.parseDouble(work.replace(',', '.'));
+ } catch (final NumberFormatException nfe) {
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ * @see org.mihalis.opal.preferenceWindow.widgets.PWWidget#check()
+ */
+ @Override
+ public void check() {
+ final Object value = PreferenceWindow.getInstance().getValueFor(getPropertyKey());
+ if (value == null) {
+ PreferenceWindow.getInstance().setValue(getPropertyKey(), new Float(0));
+ } else {
+ if (!(value instanceof Float)) {
+ throw new UnsupportedOperationException("The property '" + getPropertyKey() + "' has to be a Float because it is associated to a float text widget");
+ }
+ }
+ }
+
+ /**
+ * @see org.mihalis.opal.preferenceWindow.widgets.PWText#convertValue()
+ */
+ @Override
+ public Object convertValue() {
+ return Float.parseFloat(this.text.getText());
+ }
+
+ /**
+ * @see org.mihalis.opal.preferenceWindow.widgets.PWText#getStyle()
+ */
+ @Override
+ public int getStyle() {
+ return SWT.NONE;
+ }
+
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWFontChooser.java b/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWFontChooser.java
new file mode 100644
index 000000000..5637fe2ea
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWFontChooser.java
@@ -0,0 +1,95 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON
+ * 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:
+ * Laurent CARON (laurent.caron at gmail dot com) - Initial implementation and API
+ *******************************************************************************/
+package org.mihalis.opal.preferenceWindow.widgets;
+
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.graphics.FontData;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Event;
+import org.eclipse.swt.widgets.FontDialog;
+import org.eclipse.swt.widgets.Listener;
+import org.eclipse.swt.widgets.Text;
+import org.mihalis.opal.preferenceWindow.PreferenceWindow;
+import org.mihalis.opal.utils.ResourceManager;
+
+/**
+ * Instances of this class are used to select a font
+ */
+public class PWFontChooser extends PWChooser {
+ private FontData fontData;
+
+ /**
+ * Constructor
+ *
+ * @param label associated label
+ * @param propertyKey associated key
+ */
+ public PWFontChooser(final String label, final String propertyKey) {
+ super(label, propertyKey);
+ }
+
+ /**
+ * @see org.mihalis.opal.preferenceWindow.widgets.PWWidget#check()
+ */
+ @Override
+ public void check() {
+ final Object value = PreferenceWindow.getInstance().getValueFor(getPropertyKey());
+ if (value == null) {
+ PreferenceWindow.getInstance().setValue(getPropertyKey(), null);
+ } else {
+ if (!(value instanceof FontData)) {
+ throw new UnsupportedOperationException("The property '" + getPropertyKey() + "' has to be a FontData because it is associated to a font chooser");
+ }
+ }
+ }
+
+ /**
+ * @see org.mihalis.opal.preferenceWindow.widgets.PWChooser#setButtonAction(org.eclipse.swt.widgets.Text,
+ * org.eclipse.swt.widgets.Button)
+ */
+ @Override
+ protected void setButtonAction(final Text text, final Button button) {
+ this.fontData = (FontData) PreferenceWindow.getInstance().getValueFor(getPropertyKey());
+
+ button.addListener(SWT.Selection, new Listener() {
+
+ @Override
+ public void handleEvent(final Event event) {
+ final FontDialog dialog = new FontDialog(text.getShell());
+ final FontData result = dialog.open();
+ if (result != null && result.getName() != null && !"".equals(result.getName().trim())) {
+ PWFontChooser.this.fontData = result;
+ PreferenceWindow.getInstance().setValue(getPropertyKey(), result);
+ text.setText(buildFontInformation());
+ }
+
+ }
+ });
+
+ }
+
+ /**
+ * @return a string that contains data about the choosen font
+ */
+ protected String buildFontInformation() {
+ final StringBuilder sb = new StringBuilder();
+ if (this.fontData != null) {
+ sb.append(this.fontData.getName()).append(",").append(this.fontData.getHeight()).append(" pt");
+ if ((this.fontData.getStyle() & SWT.BOLD) == SWT.BOLD) {
+ sb.append(", ").append(ResourceManager.getLabel(ResourceManager.BOLD));
+ }
+ if ((this.fontData.getStyle() & SWT.ITALIC) == SWT.ITALIC) {
+ sb.append(", ").append(ResourceManager.getLabel(ResourceManager.ITALIC));
+ }
+ }
+ return sb.toString();
+ }
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWIntegerText.java b/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWIntegerText.java
new file mode 100644
index 000000000..8e681df17
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWIntegerText.java
@@ -0,0 +1,84 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON
+ * 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:
+ * Laurent CARON (laurent.caron at gmail dot com) - Initial implementation and API
+ *******************************************************************************/
+package org.mihalis.opal.preferenceWindow.widgets;
+
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.widgets.Event;
+import org.eclipse.swt.widgets.Listener;
+import org.mihalis.opal.preferenceWindow.PreferenceWindow;
+
+/**
+ * Instances of this class are text box to type Integers
+ */
+public class PWIntegerText extends PWText {
+
+ /**
+ * Constructor
+ *
+ * @param label associated label
+ * @param propertyKey associated key
+ */
+ public PWIntegerText(final String label, final String propertyKey) {
+ super(label, propertyKey);
+ }
+
+ /**
+ * @see org.mihalis.opal.preferenceWindow.widgets.PWText#addVerifyListeners()
+ */
+ @Override
+ public void addVerifyListeners() {
+ this.text.addListener(SWT.Verify, new Listener() {
+ @Override
+ public void handleEvent(final Event e) {
+ final String string = e.text;
+ final char[] chars = new char[string.length()];
+ string.getChars(0, chars.length, chars, 0);
+ for (int i = 0; i < chars.length; i++) {
+ if (!('0' <= chars[i] && chars[i] <= '9') && e.keyCode != SWT.BS && e.keyCode != SWT.DEL) {
+ e.doit = false;
+ return;
+ }
+ }
+ }
+ });
+ }
+
+ /**
+ * @see org.mihalis.opal.preferenceWindow.widgets.PWWidget#check()
+ */
+ @Override
+ public void check() {
+ final Object value = PreferenceWindow.getInstance().getValueFor(getPropertyKey());
+ if (value == null) {
+ PreferenceWindow.getInstance().setValue(getPropertyKey(), new Integer(0));
+ } else {
+ if (!(value instanceof Integer)) {
+ throw new UnsupportedOperationException("The property '" + getPropertyKey() + "' has to be an Integer because it is associated to a integer text widget");
+ }
+ }
+ }
+
+ /**
+ * @see org.mihalis.opal.preferenceWindow.widgets.PWText#convertValue()
+ */
+ @Override
+ public Object convertValue() {
+ return Integer.parseInt(this.text.getText());
+ }
+
+ /**
+ * @see org.mihalis.opal.preferenceWindow.widgets.PWText#getStyle()
+ */
+ @Override
+ public int getStyle() {
+ return SWT.NONE;
+ }
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWLabel.java b/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWLabel.java
new file mode 100644
index 000000000..bcffef7b8
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWLabel.java
@@ -0,0 +1,81 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON
+ * 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:
+ * Laurent CARON (laurent.caron at gmail dot com) - Initial implementation and API
+ *******************************************************************************/
+package org.mihalis.opal.preferenceWindow.widgets;
+
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.custom.StyledText;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.mihalis.opal.utils.SWTGraphicUtil;
+
+/**
+ * Instances of this class are labels, that could contain some HTML tags (B,I,U)
+ */
+public class PWLabel extends PWWidget {
+
+ private StyledText labelWidget;
+
+ /**
+ * Constructor
+ *
+ * @param label associated label
+ */
+ public PWLabel(final String label) {
+ super(label, null, 1, true);
+ setAlignment(GridData.FILL);
+ setGrabExcessSpace(true);
+ }
+
+ /**
+ * @see org.mihalis.opal.preferenceWindow.widgets.PWWidget#build(org.eclipse.swt.widgets.Composite)
+ */
+ @Override
+ public Control build(final Composite parent) {
+ if (getLabel() == null) {
+ throw new UnsupportedOperationException("You need to set a description for a PWLabel object");
+ }
+ this.labelWidget = new StyledText(parent, SWT.WRAP | SWT.READ_ONLY);
+ this.labelWidget.setEnabled(false);
+ this.labelWidget.setBackground(parent.getBackground());
+ this.labelWidget.setText("<html><body>" + getLabel() + "</body></html>");
+ SWTGraphicUtil.applyHTMLFormating(this.labelWidget);
+ return this.labelWidget;
+ }
+
+ /**
+ * @see org.mihalis.opal.preferenceWindow.widgets.PWWidget#check()
+ */
+ @Override
+ public void check() {
+ }
+
+ /**
+ * @see org.mihalis.opal.preferenceWindow.widgets.PWWidget#enableOrDisable()
+ */
+ @Override
+ public boolean enableOrDisable() {
+ if (this.enabler == null) {
+ return true;
+ }
+
+ final boolean enabled = this.enabler.isEnabled();
+ if (!this.labelWidget.isDisposed()) {
+ if (enabled) {
+ this.labelWidget.setForeground(this.labelWidget.getDisplay().getSystemColor(SWT.COLOR_BLACK));
+ } else {
+ this.labelWidget.setForeground(this.labelWidget.getDisplay().getSystemColor(SWT.COLOR_DARK_GRAY));
+ }
+ }
+ return enabled;
+ }
+
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWPasswordText.java b/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWPasswordText.java
new file mode 100644
index 000000000..843b2882b
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWPasswordText.java
@@ -0,0 +1,69 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON
+ * 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:
+ * Laurent CARON (laurent.caron at gmail dot com) - Initial implementation and API
+ *******************************************************************************/
+package org.mihalis.opal.preferenceWindow.widgets;
+
+import org.eclipse.swt.SWT;
+import org.mihalis.opal.preferenceWindow.PreferenceWindow;
+
+/**
+ * Instances of this class are text box to type password
+ */
+public class PWPasswordText extends PWText {
+
+ /**
+ * Constructor
+ *
+ * @param label associated label
+ * @param propertyKey associated key
+ */
+ public PWPasswordText(final String label, final String propertyKey) {
+ super(label, propertyKey);
+ }
+
+ /**
+ * @see org.mihalis.opal.preferenceWindow.widgets.PWText#addVerifyListeners()
+ */
+ @Override
+ public void addVerifyListeners() {
+ }
+
+ /**
+ * @see org.mihalis.opal.preferenceWindow.widgets.PWWidget#check()
+ */
+ @Override
+ public void check() {
+ final Object value = PreferenceWindow.getInstance().getValueFor(getPropertyKey());
+ if (value == null) {
+ PreferenceWindow.getInstance().setValue(getPropertyKey(), "");
+ } else {
+ if (!(value instanceof String)) {
+ throw new UnsupportedOperationException("The property '" + getPropertyKey() + "' has to be a String because it is associated to a password text box");
+ }
+ }
+
+ }
+
+ /**
+ * @see org.mihalis.opal.preferenceWindow.widgets.PWText#convertValue()
+ */
+ @Override
+ public Object convertValue() {
+ return this.text.getText();
+ }
+
+ /**
+ * @see org.mihalis.opal.preferenceWindow.widgets.PWText#getStyle()
+ */
+ @Override
+ public int getStyle() {
+ return SWT.PASSWORD;
+ }
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWRadio.java b/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWRadio.java
new file mode 100644
index 000000000..3dfee00df
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWRadio.java
@@ -0,0 +1,98 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON
+ * 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:
+ * Laurent CARON (laurent.caron at gmail dot com) - Initial implementation and API
+ *******************************************************************************/
+package org.mihalis.opal.preferenceWindow.widgets;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+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.Listener;
+import org.mihalis.opal.preferenceWindow.PreferenceWindow;
+
+/**
+ * Instances of this class are a group of radio buttons
+ *
+ */
+public class PWRadio extends PWWidget {
+
+ private final List<Object> data;
+ private final List<Button> buttons;
+
+ /**
+ * Constructor
+ *
+ * @param label associated label
+ * @param propertyKey associated key
+ */
+ public PWRadio(final String label, final String prop, final Object... values) {
+ super(null, prop, label == null ? 1 : 2, false);
+ this.data = new ArrayList<Object>(Arrays.asList(values));
+ this.buttons = new ArrayList<Button>();
+ }
+
+ /**
+ * @see org.mihalis.opal.preferenceWindow.widgets.PWWidget#build(org.eclipse.swt.widgets.Composite)
+ */
+ @Override
+ public Control build(final Composite parent) {
+ buildLabel(parent, GridData.BEGINNING);
+
+ final Composite composite = new Composite(parent, SWT.NONE);
+ final GridLayout gridLayout = new GridLayout();
+ gridLayout.marginHeight = gridLayout.marginWidth = 0;
+ composite.setLayout(gridLayout);
+
+ for (final Object datum : this.data) {
+ final Button button = new Button(composite, SWT.RADIO);
+ addControl(button);
+ button.setText(datum.toString());
+ button.setLayoutData(new GridData(GridData.FILL, GridData.BEGINNING, true, false));
+ button.setSelection(datum.equals(PreferenceWindow.getInstance().getValueFor(getPropertyKey())));
+ button.setData(datum);
+ button.addListener(SWT.Selection, new Listener() {
+ @Override
+ public void handleEvent(final Event event) {
+ if (button.getSelection()) {
+ PreferenceWindow.getInstance().setValue(getPropertyKey(), button.getData());
+ }
+ }
+ });
+
+ this.buttons.add(button);
+ }
+ return composite;
+ }
+
+ /**
+ * @see org.mihalis.opal.preferenceWindow.widgets.PWWidget#check()
+ */
+ @Override
+ public void check() {
+ final Object value = PreferenceWindow.getInstance().getValueFor(getPropertyKey());
+ if (value == null) {
+ PreferenceWindow.getInstance().setValue(getPropertyKey(), null);
+ } else {
+ if (!this.data.isEmpty()) {
+ if (!value.getClass().equals(this.data.get(0).getClass())) {
+ throw new UnsupportedOperationException("The property '" + getPropertyKey() + "' has to be a " + this.data.get(0).getClass() + " because it is associated to a combo");
+ }
+ }
+ }
+ }
+
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWScale.java b/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWScale.java
new file mode 100644
index 000000000..a6bb64837
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWScale.java
@@ -0,0 +1,91 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON
+ * 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:
+ * Laurent CARON (laurent.caron at gmail dot com) - Initial implementation and API
+ *******************************************************************************/
+package org.mihalis.opal.preferenceWindow.widgets;
+
+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.Event;
+import org.eclipse.swt.widgets.Listener;
+import org.eclipse.swt.widgets.Scale;
+import org.mihalis.opal.preferenceWindow.PreferenceWindow;
+
+/**
+ * Instances of this class are scales
+ */
+public class PWScale extends PWWidget {
+
+ private final int max;
+ private final int min;
+ private final int increment;
+
+ /**
+ * Constructor
+ *
+ * @param label associated label
+ * @param propertyKey associated key
+ * @param min minimum value
+ * @param max maximum value
+ * @param increment increment value
+ */
+ public PWScale(final String label, final String propertyKey, final int min, final int max, final int increment) {
+ super(label, propertyKey, label == null ? 1 : 2, false);
+ this.min = min;
+ this.max = max;
+ this.increment = increment;
+ }
+
+ /**
+ * @see org.mihalis.opal.preferenceWindow.widgets.PWWidget#build(org.eclipse.swt.widgets.Composite)
+ */
+ @Override
+ public Control build(final Composite parent) {
+ buildLabel(parent, GridData.CENTER);
+ final Scale scale = new Scale(parent, SWT.HORIZONTAL);
+ addControl(scale);
+ scale.setIncrement(this.increment);
+ scale.setMinimum(this.min);
+ scale.setMaximum(this.max);
+ final Integer originalValue = (Integer) PreferenceWindow.getInstance().getValueFor(getPropertyKey());
+ scale.setSelection(originalValue.intValue());
+
+ scale.addListener(SWT.Modify, new Listener() {
+ @Override
+ public void handleEvent(final Event event) {
+ PreferenceWindow.getInstance().setValue(getPropertyKey(), new Integer(scale.getSelection()));
+ }
+ });
+
+ return scale;
+ }
+
+ /**
+ * @see org.mihalis.opal.preferenceWindow.widgets.PWWidget#check()
+ */
+ @Override
+ public void check() {
+ final Object value = PreferenceWindow.getInstance().getValueFor(getPropertyKey());
+ if (value == null) {
+ PreferenceWindow.getInstance().setValue(getPropertyKey(), new Integer(this.min));
+ } else {
+ if (!(value instanceof Integer)) {
+ throw new UnsupportedOperationException("The property '" + getPropertyKey() + "' has to be an Integer because it is associated to a iscale");
+ }
+
+ final int valueAsInt = ((Integer) value).intValue();
+ if (valueAsInt < this.min || valueAsInt > this.max) {
+ throw new UnsupportedOperationException("The property '" + getPropertyKey() + "' is out of range (value is " + valueAsInt + ", range is " + this.min + "-" + this.max + ")");
+ }
+ }
+ }
+
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWSeparator.java b/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWSeparator.java
new file mode 100644
index 000000000..b24032ae4
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWSeparator.java
@@ -0,0 +1,78 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON
+ * 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:
+ * Laurent CARON (laurent.caron at gmail dot com) - Initial implementation and API
+ *******************************************************************************/
+package org.mihalis.opal.preferenceWindow.widgets;
+
+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.swt.widgets.Control;
+import org.mihalis.opal.titledSeparator.TitledSeparator;
+
+/**
+ * Instances of this class are separators
+ *
+ */
+public class PWSeparator extends PWWidget {
+
+ private final Image image;
+
+ /**
+ * Constructor
+ *
+ */
+ public PWSeparator() {
+ this(null, null);
+ }
+
+ /**
+ * Constructor
+ *
+ * @param label associated label
+ */
+ public PWSeparator(final String label) {
+ this(label, null);
+ }
+
+ /**
+ * Constructor
+ *
+ * @param label associated label
+ * @param image associated image
+ */
+ public PWSeparator(final String label, final Image image) {
+ super(label, null, 1, true);
+ this.image = image;
+ setAlignment(GridData.FILL);
+ setGrabExcessSpace(true);
+ setHeight(20);
+ }
+
+ /**
+ * @see org.mihalis.opal.preferenceWindow.widgets.PWWidget#build(org.eclipse.swt.widgets.Composite)
+ */
+ @Override
+ public Control build(final Composite parent) {
+ final TitledSeparator sep = new TitledSeparator(parent, SWT.NONE);
+ addControl(sep);
+ sep.setText(getLabel());
+ sep.setImage(this.image);
+ return sep;
+ }
+
+ /**
+ * @see org.mihalis.opal.preferenceWindow.widgets.PWWidget#check()
+ */
+ @Override
+ public void check() {
+ }
+
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWSpinner.java b/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWSpinner.java
new file mode 100644
index 000000000..9fe4875d3
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWSpinner.java
@@ -0,0 +1,86 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON
+ * 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:
+ * Laurent CARON (laurent.caron at gmail dot com) - Initial implementation and API
+ *******************************************************************************/
+package org.mihalis.opal.preferenceWindow.widgets;
+
+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.Event;
+import org.eclipse.swt.widgets.Listener;
+import org.eclipse.swt.widgets.Spinner;
+import org.mihalis.opal.preferenceWindow.PreferenceWindow;
+
+/**
+ * Instances of this class are spinners
+ */
+public class PWSpinner extends PWWidget {
+ private final int max;
+ private final int min;
+
+ /**
+ * Constructor
+ *
+ * @param label associated label
+ * @param propertyKey associated key
+ * @param min minimum value
+ * @param max maximum value
+ */
+ public PWSpinner(final String label, final String propertyKey, final int min, final int max) {
+ super(label, propertyKey, label == null ? 1 : 2, false);
+ this.min = min;
+ this.max = max;
+ }
+
+ /**
+ * @see org.mihalis.opal.preferenceWindow.widgets.PWWidget#build(org.eclipse.swt.widgets.Composite)
+ */
+ @Override
+ public Control build(final Composite parent) {
+ buildLabel(parent, GridData.CENTER);
+ final Spinner spinner = new Spinner(parent, SWT.HORIZONTAL | SWT.BORDER);
+ addControl(spinner);
+ spinner.setMinimum(this.min);
+ spinner.setMaximum(this.max);
+ final Integer originalValue = (Integer) PreferenceWindow.getInstance().getValueFor(getPropertyKey());
+ spinner.setSelection(originalValue.intValue());
+
+ spinner.addListener(SWT.Modify, new Listener() {
+ @Override
+ public void handleEvent(final Event event) {
+ PreferenceWindow.getInstance().setValue(getPropertyKey(), new Integer(spinner.getSelection()));
+ }
+ });
+
+ return spinner;
+ }
+
+ /**
+ * @see org.mihalis.opal.preferenceWindow.widgets.PWWidget#check()
+ */
+ @Override
+ public void check() {
+ final Object value = PreferenceWindow.getInstance().getValueFor(getPropertyKey());
+ if (value == null) {
+ PreferenceWindow.getInstance().setValue(getPropertyKey(), new Integer(this.min));
+ } else {
+ if (!(value instanceof Integer)) {
+ throw new UnsupportedOperationException("The property '" + getPropertyKey() + "' has to be an Integer because it is associated to a spinner");
+ }
+
+ final int valueAsInt = ((Integer) value).intValue();
+ if (valueAsInt < this.min || valueAsInt > this.max) {
+ throw new UnsupportedOperationException("The property '" + getPropertyKey() + "' is out of range (value is " + valueAsInt + ", range is " + this.min + "-" + this.max + ")");
+ }
+ }
+ }
+
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWStringText.java b/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWStringText.java
new file mode 100644
index 000000000..bc2301aa2
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWStringText.java
@@ -0,0 +1,68 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON
+ * 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:
+ * Laurent CARON (laurent.caron at gmail dot com) - Initial implementation and API
+ *******************************************************************************/
+package org.mihalis.opal.preferenceWindow.widgets;
+
+import org.eclipse.swt.SWT;
+import org.mihalis.opal.preferenceWindow.PreferenceWindow;
+
+/**
+ * Instances of this class are text box to type Strings
+ */
+public class PWStringText extends PWText {
+
+ /**
+ * Constructor
+ *
+ * @param label associated label
+ * @param propertyKey associated key
+ */
+ public PWStringText(final String label, final String propertyKey) {
+ super(label, propertyKey);
+ }
+
+ /**
+ * @see org.mihalis.opal.preferenceWindow.widgets.PWText#addVerifyListeners()
+ */
+ @Override
+ public void addVerifyListeners() {
+ }
+
+ /**
+ * @see org.mihalis.opal.preferenceWindow.widgets.PWWidget#check()
+ */
+ @Override
+ public void check() {
+ final Object value = PreferenceWindow.getInstance().getValueFor(getPropertyKey());
+ if (value == null) {
+ PreferenceWindow.getInstance().setValue(getPropertyKey(), "");
+ } else {
+ if (!(value instanceof String)) {
+ throw new UnsupportedOperationException("The property '" + getPropertyKey() + "' has to be a String because it is associated to a stringtext");
+ }
+ }
+ }
+
+ /**
+ * @see org.mihalis.opal.preferenceWindow.widgets.PWText#convertValue()
+ */
+ @Override
+ public Object convertValue() {
+ return this.text.getText();
+ }
+
+ /**
+ * @see org.mihalis.opal.preferenceWindow.widgets.PWText#getStyle()
+ */
+ @Override
+ public int getStyle() {
+ return SWT.NONE;
+ }
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWText.java b/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWText.java
new file mode 100644
index 000000000..3d37a8606
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWText.java
@@ -0,0 +1,74 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON
+ * 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:
+ * Laurent CARON (laurent.caron at gmail dot com) - Initial implementation and API
+ *******************************************************************************/
+package org.mihalis.opal.preferenceWindow.widgets;
+
+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.Event;
+import org.eclipse.swt.widgets.Listener;
+import org.eclipse.swt.widgets.Text;
+import org.mihalis.opal.preferenceWindow.PreferenceWindow;
+
+/**
+ * This is the abstract class for all text widgets (except textarea)
+ */
+public abstract class PWText extends PWWidget {
+
+ protected Text text;
+
+ /**
+ * Constructor
+ *
+ * @param label associated label
+ * @param propertyKey associated property key
+ */
+ public PWText(final String label, final String propertyKey) {
+ super(label, propertyKey, label == null ? 1 : 2, false);
+ setGrabExcessSpace(true);
+ }
+
+ /**
+ * @see org.mihalis.opal.preferenceWindow.widgets.PWWidget#build(org.eclipse.swt.widgets.Composite)
+ */
+ @Override
+ public Control build(final Composite parent) {
+ buildLabel(parent, GridData.CENTER);
+ this.text = new Text(parent, SWT.BORDER | getStyle());
+ addControl(this.text);
+ addVerifyListeners();
+ this.text.setText(PreferenceWindow.getInstance().getValueFor(getPropertyKey()).toString());
+ this.text.addListener(SWT.Modify, new Listener() {
+ @Override
+ public void handleEvent(final Event event) {
+ PreferenceWindow.getInstance().setValue(getPropertyKey(), convertValue());
+ }
+ });
+ return this.text;
+ }
+
+ /**
+ * Add the verify listeners
+ */
+ public abstract void addVerifyListeners();
+
+ /**
+ * @return the value of the data typed by the user in the correct format
+ */
+ public abstract Object convertValue();
+
+ /**
+ * @return the style (SWT.NONE or SWT.PASSWORD)
+ */
+ public abstract int getStyle();
+
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWTextarea.java b/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWTextarea.java
new file mode 100644
index 000000000..0521707b7
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWTextarea.java
@@ -0,0 +1,77 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON
+ * 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:
+ * Laurent CARON (laurent.caron at gmail dot com) - Initial implementation and API
+ *******************************************************************************/
+package org.mihalis.opal.preferenceWindow.widgets;
+
+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.Event;
+import org.eclipse.swt.widgets.Listener;
+import org.eclipse.swt.widgets.Text;
+import org.mihalis.opal.preferenceWindow.PreferenceWindow;
+
+/**
+ * Instances of this class are text areas
+ *
+ */
+public class PWTextarea extends PWWidget {
+
+ /**
+ * Constructor
+ *
+ * @param label associated label
+ * @param propertyKey associated key
+ */
+ public PWTextarea(final String label, final String propertyKey) {
+ super(label, propertyKey, label == null ? 1 : 2, false);
+ setGrabExcessSpace(true);
+ setHeight(50);
+ setWidth(350);
+ }
+
+ /**
+ * @see org.mihalis.opal.preferenceWindow.widgets.PWWidget#build(org.eclipse.swt.widgets.Composite)
+ */
+ @Override
+ public Control build(final Composite parent) {
+ buildLabel(parent, GridData.BEGINNING);
+
+ final Text text = new Text(parent, SWT.BORDER | SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
+ addControl(text);
+ text.setText(PreferenceWindow.getInstance().getValueFor(getPropertyKey()).toString());
+ text.addListener(SWT.FocusOut, new Listener() {
+
+ @Override
+ public void handleEvent(final Event event) {
+ PreferenceWindow.getInstance().setValue(getPropertyKey(), text.getText());
+ }
+ });
+
+ return text;
+ }
+
+ /**
+ * @see org.mihalis.opal.preferenceWindow.widgets.PWWidget#check()
+ */
+ @Override
+ public void check() {
+ final Object value = PreferenceWindow.getInstance().getValueFor(getPropertyKey());
+ if (value == null) {
+ PreferenceWindow.getInstance().setValue(getPropertyKey(), "");
+ } else {
+ if (!(value instanceof String)) {
+ throw new UnsupportedOperationException("The property '" + getPropertyKey() + "' has to be a String because it is associated to a textarea");
+ }
+ }
+ }
+
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWURLText.java b/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWURLText.java
new file mode 100644
index 000000000..ebb145afe
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWURLText.java
@@ -0,0 +1,98 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON
+ * 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:
+ * Laurent CARON (laurent.caron at gmail dot com) - Initial implementation and API
+ *******************************************************************************/
+package org.mihalis.opal.preferenceWindow.widgets;
+
+import java.net.MalformedURLException;
+import java.net.URL;
+
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.widgets.Event;
+import org.eclipse.swt.widgets.Listener;
+import org.mihalis.opal.opalDialog.Dialog;
+import org.mihalis.opal.preferenceWindow.PreferenceWindow;
+import org.mihalis.opal.utils.ResourceManager;
+
+/**
+ * Instances of this class are text box used to type URL
+ */
+public class PWURLText extends PWText {
+
+ /**
+ * Constructor
+ *
+ * @param label associated label
+ * @param propertyKey associated key
+ */
+ public PWURLText(final String label, final String propertyKey) {
+ super(label, propertyKey);
+ setWidth(200);
+ }
+
+ /**
+ * @see org.mihalis.opal.preferenceWindow.widgets.PWText#addVerifyListeners()
+ */
+ @Override
+ public void addVerifyListeners() {
+ this.text.addListener(SWT.FocusOut, new Listener() {
+
+ @Override
+ public void handleEvent(final Event event) {
+ try {
+ new URL(PWURLText.this.text.getText());
+ } catch (final MalformedURLException e) {
+ Dialog.error(ResourceManager.getLabel(ResourceManager.APPLICATION_ERROR), ResourceManager.getLabel(ResourceManager.VALID_URL));
+ event.doit = false;
+ PWURLText.this.text.forceFocus();
+ }
+
+ }
+ });
+
+ }
+
+ /**
+ * @see org.mihalis.opal.preferenceWindow.widgets.PWWidget#check()
+ */
+ @Override
+ public void check() {
+ final Object value = PreferenceWindow.getInstance().getValueFor(getPropertyKey());
+ if (value == null) {
+ PreferenceWindow.getInstance().setValue(getPropertyKey(), "");
+ } else {
+ if (!(value instanceof String)) {
+ throw new UnsupportedOperationException("The property '" + getPropertyKey() + "' has to be a String because it is associated to a URL text box");
+ }
+
+ try {
+ new URL((String) value);
+ } catch (final MalformedURLException e) {
+ throw new UnsupportedOperationException("The property '" + getPropertyKey() + "' has a value (" + value + ") that is not an URL");
+ }
+ }
+ }
+
+ /**
+ * @see org.mihalis.opal.preferenceWindow.widgets.PWText#convertValue()
+ */
+ @Override
+ public Object convertValue() {
+ return this.text.getText();
+ }
+
+ /**
+ * @see org.mihalis.opal.preferenceWindow.widgets.PWText#getStyle()
+ */
+ @Override
+ public int getStyle() {
+ return SWT.NONE;
+ }
+
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWWidget.java b/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWWidget.java
new file mode 100644
index 000000000..424cf0223
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/preferenceWindow/widgets/PWWidget.java
@@ -0,0 +1,264 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON
+ * 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:
+ * Laurent CARON (laurent.caron at gmail dot com) - Initial implementation and API
+ *******************************************************************************/
+package org.mihalis.opal.preferenceWindow.widgets;
+
+import java.util.ArrayList;
+import java.util.List;
+
+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.Label;
+import org.mihalis.opal.preferenceWindow.enabler.Enabler;
+
+/**
+ * This class is the root class for all widgets that take part of a preference
+ * window
+ *
+ */
+public abstract class PWWidget {
+ private final String propertyKey;
+ private final String label;
+ protected Enabler enabler;
+ private final List<Control> controls;
+
+ private int alignment = GridData.BEGINNING;
+ private int indent = 0;
+ private int width = 100;
+ private int height = -1;
+ protected int numberOfColumns = 1;
+ private boolean grabExcessSpace = false;
+
+ private boolean singleWidget = false;
+
+ /**
+ * Constructor
+ *
+ * @param label label associated to the widget
+ * @param propertyKey property key binded to the widget
+ * @param numberOfColumns number of columns taken by the widget
+ * @param singleWidget if true, the widget is supposed to be "alone" (used
+ * for placement)
+ */
+ protected PWWidget(final String label, final String propertyKey, final int numberOfColumns, final boolean singleWidget) {
+ this.label = label;
+ this.propertyKey = propertyKey;
+ this.numberOfColumns = numberOfColumns;
+ this.singleWidget = singleWidget;
+ this.controls = new ArrayList<Control>();
+ }
+
+ /**
+ * Build the widget
+ *
+ * @param parent parent composite
+ * @return the created control
+ */
+ protected abstract Control build(Composite parent);
+
+ /**
+ * Build the label associated to the widget
+ *
+ * @param parent parent composite
+ * @param verticalAlignment vertical alignment
+ */
+ protected void buildLabel(final Composite parent, final int verticalAlignment) {
+ if (getLabel() != null) {
+ final Label label = new Label(parent, SWT.NONE);
+ label.setText(getLabel());
+ final GridData labelGridData = new GridData(GridData.END, verticalAlignment, false, false);
+ labelGridData.horizontalIndent = getIndent();
+ label.setLayoutData(labelGridData);
+ addControl(label);
+ }
+ }
+
+ /**
+ * Check if the property can be binded to the widget
+ *
+ * @throws UnsupportedOperationException if the property could not be binded
+ * to the widget
+ */
+ protected abstract void check();
+
+ /**
+ * Check if the property can be binded to the widget, then build the widget
+ *
+ * @param parent parent composite
+ * @return the created control
+ */
+ public Control checkAndBuild(final Composite parent) {
+ check();
+ return build(parent);
+ }
+
+ /**
+ * Enable or disable the widget, depending on the associated enabler
+ */
+ public boolean enableOrDisable() {
+ if (this.enabler == null) {
+ return true;
+ }
+
+ final boolean enabled = this.enabler.isEnabled();
+ for (final Control c : this.controls) {
+ if (!c.isDisposed()) {
+ c.setEnabled(enabled);
+ }
+ }
+ return enabled;
+ }
+
+ // ------------------------------- getters & setters
+
+ /**
+ * @return the alignment (GridData.BEGINNING, GridData.CENTER, GridData.END,
+ * GridData.FILL)
+ */
+ public int getAlignment() {
+ return this.alignment;
+ }
+
+ /**
+ * @return the list of controls contained in the widget
+ */
+ public List<Control> getControls() {
+ return this.controls;
+ }
+
+ /**
+ * @return <code>true</code> if the widget should grab the excess space
+ */
+ public boolean isGrabExcessSpace() {
+ return this.grabExcessSpace;
+ }
+
+ /**
+ * @return the height of the widget
+ */
+ public int getHeight() {
+ return this.height;
+ }
+
+ /**
+ * @return the indentation space of the widget
+ */
+ public int getIndent() {
+ return this.indent;
+ }
+
+ /**
+ * @return the label associated to the widget (may be <code>null</code>)
+ */
+ public String getLabel() {
+ return this.label;
+ }
+
+ /**
+ * @return the number of columns associated to the widget
+ */
+ public int getNumberOfColumns() {
+ return this.numberOfColumns;
+ }
+
+ /**
+ * @return the propertyKey associated to the widget
+ */
+ String getPropertyKey() {
+ return this.propertyKey;
+ }
+
+ /**
+ * @return the width of the widget
+ */
+ public int getWidth() {
+ return this.width;
+ }
+
+ /**
+ * @return <code>true</code> if the widget is "alone"
+ */
+ public boolean isSingleWidget() {
+ return this.singleWidget;
+ }
+
+ /**
+ * Adds a control to the list of control contained in the widget
+ *
+ * @param control control to add
+ */
+ protected void addControl(final Control control) {
+ this.controls.add(control);
+ }
+
+ /**
+ * @param alignment the alignment to set (GridData.BEGINNING,
+ * GridData.CENTER, GridData.END, GridData.FILL)
+ * @return the widget
+ */
+ public PWWidget setAlignment(final int alignment) {
+ if (alignment != GridData.BEGINNING && alignment != GridData.CENTER && alignment != GridData.END && alignment != GridData.FILL) {
+ throw new UnsupportedOperationException("Value should be one of the following :GridData.BEGINNING, GridData.CENTER, GridData.END, GridData.FILL");
+ }
+ this.alignment = alignment;
+ return this;
+ }
+
+ /**
+ * @param enabler the enabler to set
+ * @return the widget
+ */
+ public PWWidget setEnabler(final Enabler enabler) {
+ this.enabler = enabler;
+ this.enabler.injectWidget(this);
+ return this;
+ }
+
+ /**
+ * @param grabExcessSpace true if you want the widget to grab the excess
+ * space
+ * @return the widget
+ */
+ public PWWidget setGrabExcessSpace(final boolean grabExcessSpace) {
+ this.grabExcessSpace = grabExcessSpace;
+ return this;
+ }
+
+ /**
+ * @param height the height to set
+ * @return the widget
+ */
+ public PWWidget setHeight(final int height) {
+ this.height = height;
+ return this;
+
+ }
+
+ /**
+ * @param indent the indentation space to set
+ * @return the widget
+ */
+ public PWWidget setIndent(final int indent) {
+ this.indent = indent;
+ return this;
+ }
+
+ /**
+ * @param width the width to set
+ * @return the widget
+ */
+ public PWWidget setWidth(final int width) {
+ this.width = width;
+ return this;
+ }
+
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/promptSupport/BaseFocusControlListener.java b/org.tizen.common.externals/src/org/mihalis/opal/promptSupport/BaseFocusControlListener.java
new file mode 100644
index 000000000..35c65bed0
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/promptSupport/BaseFocusControlListener.java
@@ -0,0 +1,169 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON.
+ * 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:
+ * Peter Weishapl - Inspiration
+ * Laurent CARON (laurent.caron@gmail.com) - initial API and implementation
+ *******************************************************************************/
+package org.mihalis.opal.promptSupport;
+
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.ControlEvent;
+import org.eclipse.swt.events.ControlListener;
+import org.eclipse.swt.events.FocusEvent;
+import org.eclipse.swt.events.FocusListener;
+import org.eclipse.swt.graphics.Color;
+import org.eclipse.swt.graphics.Font;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Event;
+import org.eclipse.swt.widgets.Listener;
+import org.mihalis.opal.promptSupport.PromptSupport.FocusBehavior;
+import org.mihalis.opal.utils.SWTGraphicUtil;
+
+/**
+ * Abstract class that contains code for the FocusLost, FocusGained and
+ * ControlResized events
+ *
+ */
+abstract class BaseFocusControlListener implements FocusListener, ControlListener {
+
+ protected Control control;
+ private boolean firstDraw;
+ private Font initialFont;
+ private Color initialBackgroundColor;
+ private Color initialForegroundColor;
+
+ /**
+ * Constructor
+ *
+ * @param control control on which this listener will be attached
+ */
+ BaseFocusControlListener(final Control control) {
+ this.control = control;
+ this.firstDraw = true;
+ }
+
+ /**
+ * @see org.eclipse.swt.events.FocusListener#focusGained(org.eclipse.swt.events.FocusEvent)
+ */
+ @Override
+ public void focusGained(final FocusEvent e) {
+ if (isFilled()) {
+ // Widget not empty
+ return;
+ }
+
+ applyInitialLook();
+ if (PromptSupport.getFocusBehavior(this.control) == FocusBehavior.HIDE_PROMPT) {
+ hidePrompt();
+ } else {
+ highLightPrompt();
+ }
+ }
+
+ /**
+ * Apply the initial look of the widget
+ */
+ private void applyInitialLook() {
+ this.control.setFont(this.initialFont);
+ this.control.setBackground(this.initialBackgroundColor);
+ this.control.setForeground(this.initialForegroundColor);
+ }
+
+ /**
+ * Code when the focus behiaviour is "Hide"
+ */
+ protected abstract void hidePrompt();
+
+ /**
+ * Code when the focus behiaviour is "Highlight"
+ */
+ protected abstract void highLightPrompt();
+
+ /**
+ * @see org.eclipse.swt.events.FocusListener#focusLost(org.eclipse.swt.events.FocusEvent)
+ */
+ @Override
+ public void focusLost(final FocusEvent e) {
+ if (isFilled()) {
+ return;
+ }
+
+ storeInitialLook();
+ applyForegroundColor();
+ applyBackgroundColor();
+ applyFontStyle();
+ fillPromptText();
+ }
+
+ /**
+ * @return <code>true</code> if the widget is filled, <code>false</code>
+ * otherwise
+ */
+ protected abstract boolean isFilled();
+
+ /**
+ * Apply the foreground color for the prompt
+ */
+ private void applyForegroundColor() {
+ this.control.setForeground(PromptSupport.getForeground(this.control));
+ }
+
+ /**
+ * Apply the background color for the prompt
+ */
+ private void applyBackgroundColor() {
+ this.control.setBackground(PromptSupport.getBackground(this.control));
+ }
+
+ /**
+ * Apply the font style to the prompt
+ */
+ private void applyFontStyle() {
+ final Font font = SWTGraphicUtil.buildFontFrom(this.control, PromptSupport.getFontStyle(this.control));
+ this.control.setFont(font);
+ this.control.addListener(SWT.Dispose, new Listener() {
+ @Override
+ public void handleEvent(final Event event) {
+ SWTGraphicUtil.dispose(font);
+ }
+ });
+ }
+
+ /**
+ * Fill the prompt text
+ */
+ protected abstract void fillPromptText();
+
+ /**
+ * @see org.eclipse.swt.events.ControlListener#controlMoved(org.eclipse.swt.events.ControlEvent)
+ */
+ @Override
+ public void controlMoved(final ControlEvent e) {
+ }
+
+ /**
+ * @see org.eclipse.swt.events.ControlListener#controlResized(org.eclipse.swt.events.ControlEvent)
+ */
+ @Override
+ public void controlResized(final ControlEvent e) {
+ if (this.firstDraw) {
+ storeInitialLook();
+ this.firstDraw = true;
+ focusLost(null);
+ }
+ }
+
+ /**
+ * Store the initial look of the widget
+ */
+ private void storeInitialLook() {
+ this.initialFont = this.control.getFont();
+ this.initialBackgroundColor = this.control.getBackground();
+ this.initialForegroundColor = this.control.getForeground();
+ }
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/promptSupport/CComboFocusControlListener.java b/org.tizen.common.externals/src/org/mihalis/opal/promptSupport/CComboFocusControlListener.java
new file mode 100644
index 000000000..5a2da0708
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/promptSupport/CComboFocusControlListener.java
@@ -0,0 +1,68 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON.
+ * 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:
+ * Peter Weishapl - Inspiration
+ * Laurent CARON (laurent.caron@gmail.com) - initial API and implementation
+ *******************************************************************************/
+package org.mihalis.opal.promptSupport;
+
+import org.eclipse.swt.custom.CCombo;
+
+/**
+ * Focus/Control listener for a CCombo widget
+ */
+class CComboFocusControlListener extends BaseFocusControlListener {
+
+ /**
+ * Constructor
+ *
+ * @param control control on which this listener will be attached
+ */
+ public CComboFocusControlListener(final CCombo control) {
+ super(control);
+ }
+
+ /**
+ * @see org.mihalis.opal.promptSupport.BaseFocusControlListener#hidePrompt()
+ */
+ @Override
+ protected void hidePrompt() {
+ ((CCombo) this.control).setText("");
+ }
+
+ /**
+ * @see org.mihalis.opal.promptSupport.BaseFocusControlListener#highLightPrompt()
+ */
+ @Override
+ protected void highLightPrompt() {
+ }
+
+ /**
+ * @see org.mihalis.opal.promptSupport.BaseFocusControlListener#fillPromptText()
+ */
+ @Override
+ protected void fillPromptText() {
+ final String promptText = PromptSupport.getPrompt(this.control);
+ if (promptText != null) {
+ ((CCombo) this.control).setText(promptText);
+ }
+ }
+
+ /**
+ * @see org.mihalis.opal.promptSupport.BaseFocusControlListener#isFilled()
+ */
+ @Override
+ protected boolean isFilled() {
+ final String promptText = PromptSupport.getPrompt(this.control);
+ if (promptText != null && promptText.equals(((CCombo) this.control).getText().trim())) {
+ return false;
+ }
+ return !"".equals(((CCombo) this.control).getText().trim());
+ }
+
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/promptSupport/ComboFocusControlListener.java b/org.tizen.common.externals/src/org/mihalis/opal/promptSupport/ComboFocusControlListener.java
new file mode 100644
index 000000000..8e330f928
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/promptSupport/ComboFocusControlListener.java
@@ -0,0 +1,73 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON.
+ * 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:
+ * Peter Weishapl - Inspiration
+ * Laurent CARON (laurent.caron@gmail.com) - initial API and implementation
+ *******************************************************************************/
+package org.mihalis.opal.promptSupport;
+
+import org.eclipse.swt.widgets.Combo;
+
+/**
+ * Focus/Control listener for a Combo widget
+ */
+class ComboFocusControlListener extends BaseFocusControlListener {
+
+ /**
+ * Constructor
+ *
+ * @param control control on which this listener will be attached
+ */
+ public ComboFocusControlListener(final Combo control) {
+ super(control);
+ }
+
+ /**
+ * @see org.mihalis.opal.promptSupport.BaseFocusControlListener#hidePrompt()
+ */
+ @Override
+ protected void hidePrompt() {
+ ((Combo) this.control).setText("");
+ }
+
+ /**
+ * @see org.mihalis.opal.promptSupport.BaseFocusControlListener#highLightPrompt()
+ */
+ @Override
+ protected void highLightPrompt() {
+ }
+
+ /**
+ * @see org.mihalis.opal.promptSupport.BaseFocusControlListener#fillPromptText()
+ */
+ @Override
+ protected void fillPromptText() {
+ final String promptText = PromptSupport.getPrompt(this.control);
+ if (promptText != null) {
+ this.control.getDisplay().asyncExec(new Runnable() {
+
+ @Override
+ public void run() {
+ ((Combo) ComboFocusControlListener.this.control).setText(promptText);
+ }
+ });
+ }
+ }
+
+ /**
+ * @see org.mihalis.opal.promptSupport.BaseFocusControlListener#isFilled()
+ */
+ @Override
+ protected boolean isFilled() {
+ final String promptText = PromptSupport.getPrompt(this.control);
+ if (promptText != null && promptText.equals(((Combo) this.control).getText().trim())) {
+ return false;
+ }
+ return !"".equals(((Combo) this.control).getText().trim());
+ }
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/promptSupport/FocusControlListenerFactory.java b/org.tizen.common.externals/src/org/mihalis/opal/promptSupport/FocusControlListenerFactory.java
new file mode 100644
index 000000000..82671dbe4
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/promptSupport/FocusControlListenerFactory.java
@@ -0,0 +1,49 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON.
+ * 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:
+ * Peter Weishapl - Inspiration
+ * Laurent CARON (laurent.caron@gmail.com) - initial API and implementation
+ *******************************************************************************/
+package org.mihalis.opal.promptSupport;
+
+import org.eclipse.swt.custom.CCombo;
+import org.eclipse.swt.custom.StyledText;
+import org.eclipse.swt.widgets.Combo;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Text;
+
+/**
+ * This is a factory of focus/control listeners
+ *
+ */
+class FocusControlListenerFactory {
+
+ /**
+ * @param control control on which the listener will be added
+ * @return a BaseControlFocus Listener that can be attached to the events
+ * focusLost, focusGained and controlResized
+ */
+ static BaseFocusControlListener getFocusControlListenerFor(final Control control) {
+ if (control instanceof Combo) {
+ return new ComboFocusControlListener((Combo) control);
+ }
+ if (control instanceof CCombo) {
+ return new CComboFocusControlListener((CCombo) control);
+ }
+
+ if (control instanceof Text) {
+ return new TextFocusControlListener((Text) control);
+ }
+
+ if (control instanceof StyledText) {
+ return new StyledTextFocusControlListener((StyledText) control);
+ }
+ throw new IllegalArgumentException("Control should be a Text, a Combo, a CCombo or a StyledText widget");
+ }
+
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/promptSupport/PromptSupport.java b/org.tizen.common.externals/src/org/mihalis/opal/promptSupport/PromptSupport.java
new file mode 100644
index 000000000..d04ade68d
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/promptSupport/PromptSupport.java
@@ -0,0 +1,230 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON.
+ * 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:
+ * Peter Weishapl - Inspiration
+ * Laurent CARON (laurent.caron@gmail.com) - initial API and implementation
+ *******************************************************************************/
+package org.mihalis.opal.promptSupport;
+
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.custom.CCombo;
+import org.eclipse.swt.custom.StyledText;
+import org.eclipse.swt.graphics.Color;
+import org.eclipse.swt.widgets.Combo;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Text;
+
+/**
+ * This utility class allows the user to add a prompt to a text or combo
+ * component (see http://designinginterfaces.com/Input_Prompt)
+ *
+ */
+public class PromptSupport {
+ public static enum FocusBehavior {
+ /**
+ * Highlight the prompt text as it would be selected.
+ */
+ HIGHLIGHT_PROMPT,
+ /**
+ * Hide the prompt text.
+ */
+ HIDE_PROMPT
+ };
+
+ private static final String KEY = "org.mihalis.opal.promptSupport.PromptSupport";
+ static final String BACKGROUND = KEY + ".background";
+ static final String FOREGROUND = KEY + ".foreground";
+ static final String STYLE = KEY + ".style";
+ static final String BEHAVIOR = KEY + ".behavior";
+ static final String PROMPT = KEY + ".prompt";
+ static final String SET = KEY + ".set";
+
+ /**
+ * <p>
+ * Convenience method to set the <code>promptText</code> and
+ * <code>promptTextColor</code> on a {@link Control}.
+ * </p>
+ *
+ * @param promptText Prompt Text
+ * @param promptForeground Foreground
+ * @param promptBackground Background
+ * @param control control
+ * @exception IllegalArgumentException if the control is not a Text Box, a
+ * Combo Box, a StyledText or a CCombo
+ */
+ public static void init(final String promptText, final Color promptForeground, final Color promptBackground, final Control control) {
+ if (promptText != null && promptText.length() > 0) {
+ setPrompt(promptText, control);
+ }
+ if (promptForeground != null) {
+ setForeground(promptForeground, control);
+ }
+ if (promptBackground != null) {
+ setBackground(promptBackground, control);
+ }
+ }
+
+ /**
+ * Get the background color of the <code>control</code>, when no text is
+ * present. If no color has been set, the <code>control</code> background
+ * color will be returned.
+ *
+ * @param textComponent
+ * @return the the background color of the text component, when no text is
+ * present
+ */
+ public static Color getBackground(final Control control) {
+ final Color temp = (Color) control.getData(BACKGROUND);
+ return temp == null ? control.getBackground() : temp;
+ }
+
+ /**
+ * <p>
+ * Sets the prompts background color on <code>control</code>. This
+ * background color will only be used when no text is present.
+ * </p>
+ *
+ * @param background
+ * @param control
+ * @exception IllegalArgumentException if the control is not a Text Box, a
+ * Combo Box, a StyledText or a CCombo
+ */
+ public static void setBackground(final Color color, final Control control) {
+ checkControl(control);
+ control.setData(BACKGROUND, color);
+ }
+
+ /**
+ * Get the {@link FocusBehavior} of <code>control</code>.
+ *
+ * @param control
+ * @return the {@link FocusBehavior} or {@link FocusBehavior#HIDE_PROMPT} if
+ * none is set
+ */
+ public static FocusBehavior getFocusBehavior(final Control control) {
+ final FocusBehavior temp = (FocusBehavior) control.getData(BEHAVIOR);
+ return temp == null ? FocusBehavior.HIDE_PROMPT : temp;
+
+ }
+
+ /**
+ * Sets the {@link FocusBehavior} on <code>control</code>, if it is the
+ * focus owner.
+ *
+ * @param focusBehavior
+ * @param control
+ * @exception IllegalArgumentException if the control is not a Text Box, a
+ * Combo Box, a StyledText or a CCombo
+ */
+ public static void setFocusBehavior(final FocusBehavior focusBehavior, final Control control) {
+ checkControl(control);
+ control.setData(BEHAVIOR, focusBehavior);
+ }
+
+ /**
+ * Returns the font style of the prompt text, which is a OR mix of
+ * SWT.ITALIC, SWT.NONE or SWT.BOLD
+ *
+ * @param control
+ * @return font style of the prompt text
+ */
+ public static int getFontStyle(final Control control) {
+ final Integer temp = (Integer) control.getData(STYLE);
+ return temp == null ? SWT.ITALIC : temp;
+
+ }
+
+ /**
+ * <p>
+ * Set the style of the prompt font, which is a OR mix of SWT.ITALIC,
+ * SWT.NONE or SWT.BOLD
+ * </p>
+ *
+ * @param fontStyle
+ * @param control
+ * @exception IllegalArgumentException if the control is not a Text Box, a
+ * Combo Box, a StyledText or a CCombo
+ */
+ public static void setFontStyle(final int fontStyle, final Control control) {
+ checkControl(control);
+ control.setData(STYLE, fontStyle);
+ }
+
+ /**
+ * Get the foreground color of the prompt text. If no color has been set,
+ * the <code>GREY</code> color will be returned.
+ *
+ * @param color
+ * @return the color of the prompt text or <code>GREY</code>if none is set
+ */
+ public static Color getForeground(final Control control) {
+ final Color temp = (Color) control.getData(FOREGROUND);
+ return temp == null ? control.getForeground() : temp;
+
+ }
+
+ /**
+ * Sets the foreground color of the prompt on <code>control</code>. This
+ * color will be used when no text is present.
+ *
+ * @param promptTextColor
+ * @param textComponent
+ * @exception IllegalArgumentException if the control is not a Text Box, a
+ * Combo Box, a StyledText or a CCombo
+ */
+ public static void setForeground(final Color color, final Control control) {
+ checkControl(control);
+ control.setData(FOREGROUND, color);
+ }
+
+ /**
+ * Get the prompt text of <code>control</code>.
+ *
+ * @param control
+ * @return the prompt text
+ */
+ public static String getPrompt(final Control control) {
+ return (String) control.getData(PROMPT);
+ }
+
+ /**
+ * <p>
+ * Sets the prompt text on <code>control</code>
+ * </p>
+ *
+ * @param promptText
+ * @param textComponent
+ * @exception IllegalArgumentException if the control is not a Text Box, a
+ * Combo Box, a StyledText or a CCombo
+ */
+ public static void setPrompt(final String promptText, final Control control) {
+ checkControl(control);
+
+ final boolean alreadySet = control.getData(SET) == null ? false : (Boolean) control.getData(SET);
+ if (alreadySet) {
+ throw new IllegalArgumentException("A prompt has already been set on this control !");
+ }
+ control.setData(PROMPT, promptText);
+
+ final BaseFocusControlListener bfl = FocusControlListenerFactory.getFocusControlListenerFor(control);
+ control.addFocusListener(bfl);
+ control.addControlListener(bfl);
+ control.setData(SET, true);
+ }
+
+ /**
+ * Check if the control is a Text, a Combo, a StyledText or a CCombo
+ *
+ * @param control control to check
+ */
+ private static void checkControl(final Control control) {
+ if (!(control instanceof Text) && !(control instanceof Combo) && !(control instanceof StyledText) && !(control instanceof CCombo)) {
+ throw new IllegalArgumentException("PromptSupport can only be used on a Text, a Combo, a StyledText or a CCombo widget.");
+ }
+ }
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/promptSupport/StyledTextFocusControlListener.java b/org.tizen.common.externals/src/org/mihalis/opal/promptSupport/StyledTextFocusControlListener.java
new file mode 100644
index 000000000..2be5bcaf4
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/promptSupport/StyledTextFocusControlListener.java
@@ -0,0 +1,76 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON.
+ * 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:
+ * Peter Weishapl - Inspiration
+ * Laurent CARON (laurent.caron@gmail.com) - initial API and implementation
+ *******************************************************************************/
+package org.mihalis.opal.promptSupport;
+
+import org.eclipse.swt.custom.StyledText;
+
+/**
+ * Focus/Control listener for a StyledText widget
+ */
+class StyledTextFocusControlListener extends BaseFocusControlListener {
+
+ /**
+ * Constructor
+ *
+ * @param control control on which this listener will be attached
+ */
+ public StyledTextFocusControlListener(final StyledText control) {
+ super(control);
+ }
+
+ /**
+ * @see org.mihalis.opal.promptSupport.BaseFocusControlListener#hidePrompt()
+ */
+ @Override
+ protected void hidePrompt() {
+ ((StyledText) this.control).setText("");
+ }
+
+ /**
+ * @see org.mihalis.opal.promptSupport.BaseFocusControlListener#highLightPrompt()
+ */
+ @Override
+ protected void highLightPrompt() {
+ this.control.getDisplay().asyncExec(new Runnable() {
+ @Override
+ public void run() {
+ ((StyledText) StyledTextFocusControlListener.this.control).selectAll();
+
+ }
+ });
+ }
+
+ /**
+ * @see org.mihalis.opal.promptSupport.BaseFocusControlListener#fillPromptText()
+ */
+ @Override
+ protected void fillPromptText() {
+ final String promptText = PromptSupport.getPrompt(this.control);
+ if (promptText != null) {
+ ((StyledText) this.control).setText(promptText);
+ }
+
+ }
+
+ /**
+ * @see org.mihalis.opal.promptSupport.BaseFocusControlListener#isFilled()
+ */
+ @Override
+ protected boolean isFilled() {
+ final String promptText = PromptSupport.getPrompt(this.control);
+ if (promptText != null && promptText.equals(((StyledText) this.control).getText().trim())) {
+ return false;
+ }
+ return !"".equals(((StyledText) this.control).getText().trim());
+ }
+
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/promptSupport/TextFocusControlListener.java b/org.tizen.common.externals/src/org/mihalis/opal/promptSupport/TextFocusControlListener.java
new file mode 100644
index 000000000..f90a975f5
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/promptSupport/TextFocusControlListener.java
@@ -0,0 +1,75 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON.
+ * 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:
+ * Peter Weishapl - Inspiration
+ * Laurent CARON (laurent.caron@gmail.com) - initial API and implementation
+ *******************************************************************************/
+package org.mihalis.opal.promptSupport;
+
+import org.eclipse.swt.widgets.Text;
+
+/**
+ * Focus/Control listener for a Text widget
+ */
+class TextFocusControlListener extends BaseFocusControlListener {
+
+ /**
+ * Constructor
+ *
+ * @param control control on which this listener will be attached
+ */
+ public TextFocusControlListener(final Text control) {
+ super(control);
+ }
+
+ /**
+ * @see org.mihalis.opal.promptSupport.BaseFocusControlListener#hidePrompt()
+ */
+ @Override
+ protected void hidePrompt() {
+ ((Text) this.control).setText("");
+ }
+
+ /**
+ * @see org.mihalis.opal.promptSupport.BaseFocusControlListener#highLightPrompt()
+ */
+ @Override
+ protected void highLightPrompt() {
+ // If we do a select all directly, it's not working !
+ this.control.getDisplay().asyncExec(new Runnable() {
+ @Override
+ public void run() {
+ ((Text) TextFocusControlListener.this.control).selectAll();
+ }
+ });
+ }
+
+ /**
+ * @see org.mihalis.opal.promptSupport.BaseFocusControlListener#fillPromptText()
+ */
+ @Override
+ protected void fillPromptText() {
+ final String promptText = PromptSupport.getPrompt(this.control);
+ if (promptText != null) {
+ ((Text) this.control).setText(promptText);
+ }
+ }
+
+ /**
+ * @see org.mihalis.opal.promptSupport.BaseFocusControlListener#isFilled()
+ */
+ @Override
+ protected boolean isFilled() {
+ final String promptText = PromptSupport.getPrompt(this.control);
+ if (promptText != null && promptText.equals(((Text) this.control).getText().trim())) {
+ return false;
+ }
+ return !"".equals(((Text) this.control).getText().trim());
+ }
+
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/rangeSlider/RangeSlider.java b/org.tizen.common.externals/src/org/mihalis/opal/rangeSlider/RangeSlider.java
new file mode 100755
index 000000000..620042e0a
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/rangeSlider/RangeSlider.java
@@ -0,0 +1,1060 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON.
+ * 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:
+ * Laurent CARON (laurent.caron@gmail.com) - initial API and implementation
+ *******************************************************************************/
+package org.mihalis.opal.rangeSlider;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.SWTException;
+import org.eclipse.swt.events.PaintEvent;
+import org.eclipse.swt.events.PaintListener;
+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.Point;
+import org.eclipse.swt.graphics.Rectangle;
+import org.eclipse.swt.widgets.Canvas;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Event;
+import org.eclipse.swt.widgets.Listener;
+import org.mihalis.opal.utils.SWTGraphicUtil;
+
+/**
+ * Instances of this class provide a separator with a title and/or an image.
+ * <p>
+ * <dl>
+ * <dt><b>Styles:</b></dt>
+ * <dd>BORDER</dd>
+ * <dd>HORIZONTAL</dd>
+ * <dd>VERTICAL</dd> *
+ * <dt><b>Events:</b></dt>
+ * <dd>Selection</dd>
+ * </dl>
+ * </p>
+ */
+public class RangeSlider extends Canvas {
+
+ private enum SELECTED_KNOB {
+ NONE, UPPER, LOWER
+ };
+
+ private int minimum;
+ private int maximum;
+ private int lowerValue;
+ private int upperValue;
+ private final List<SelectionListener> listeners;
+ private final Image slider, sliderHover, sliderDrag, sliderSelected;
+ private final Image vSlider, vSliderHover, vSliderDrag, vSliderSelected;
+ private int orientation;
+ private int increment;
+ private int pageIncrement;
+ private SELECTED_KNOB lastSelected;
+ private boolean dragInProgress;
+ private Point coordUpper;
+ private boolean upperHover;
+ private Point coordLower;
+ private boolean lowerHover;
+ private int previousUpperValue;
+ private int previousLowerValue;
+
+ /**
+ * Constructs a new instance of this class given its parent and a style
+ * value describing its behavior and appearance.
+ * <p>
+ * The style value is either one of the style constants defined in class
+ * <code>SWT</code> which is applicable to instances of this class, or must
+ * be built by <em>bitwise OR</em>'ing together (that is, using the
+ * <code>int</code> "|" operator) two or more of those <code>SWT</code>
+ * style constants. The class description lists the style constants that are
+ * applicable to the class. Style bits are also inherited from superclasses.
+ * </p>
+ *
+ * @param parent a composite control which will be the parent of the new
+ * instance (cannot be null)
+ * @param style the style of control to construct
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the parent is null</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the parent</li>
+ * </ul>
+ *
+ */
+ public RangeSlider(final Composite parent, final int style) {
+ super(parent, SWT.DOUBLE_BUFFERED | ((style & SWT.BORDER) == SWT.BORDER ? SWT.BORDER : SWT.NONE));
+ this.minimum = this.lowerValue = 0;
+ this.maximum = this.upperValue = 100;
+ this.listeners = new ArrayList<SelectionListener>();
+ this.increment = 1;
+ this.pageIncrement = 10;
+ this.lastSelected = SELECTED_KNOB.NONE;
+ this.slider = new Image(getDisplay(), this.getClass().getClassLoader().getResourceAsStream("images/slider-normal.png"));
+ this.sliderHover = new Image(getDisplay(), this.getClass().getClassLoader().getResourceAsStream("images/slider-hover.png"));
+ this.sliderDrag = new Image(getDisplay(), this.getClass().getClassLoader().getResourceAsStream("images/slider-drag.png"));
+ this.sliderSelected = new Image(getDisplay(), this.getClass().getClassLoader().getResourceAsStream("images/slider-selected.png"));
+
+ this.vSlider = new Image(getDisplay(), this.getClass().getClassLoader().getResourceAsStream("images/h-slider-normal.png"));
+ this.vSliderHover = new Image(getDisplay(), this.getClass().getClassLoader().getResourceAsStream("images/h-slider-hover.png"));
+ this.vSliderDrag = new Image(getDisplay(), this.getClass().getClassLoader().getResourceAsStream("images/h-slider-drag.png"));
+ this.vSliderSelected = new Image(getDisplay(), this.getClass().getClassLoader().getResourceAsStream("images/h-slider-selected.png"));
+
+ if ((style & SWT.VERTICAL) == SWT.VERTICAL) {
+ this.orientation = SWT.VERTICAL;
+ } else {
+ this.orientation = SWT.HORIZONTAL;
+ }
+
+ addListener(SWT.Dispose, new Listener() {
+
+ @Override
+ public void handleEvent(final Event event) {
+ SWTGraphicUtil.dispose(RangeSlider.this.slider);
+ SWTGraphicUtil.dispose(RangeSlider.this.sliderHover);
+ SWTGraphicUtil.dispose(RangeSlider.this.sliderDrag);
+ SWTGraphicUtil.dispose(RangeSlider.this.sliderSelected);
+
+ SWTGraphicUtil.dispose(RangeSlider.this.vSlider);
+ SWTGraphicUtil.dispose(RangeSlider.this.vSliderHover);
+ SWTGraphicUtil.dispose(RangeSlider.this.vSliderDrag);
+ SWTGraphicUtil.dispose(RangeSlider.this.vSliderSelected);
+ }
+ });
+
+ addMouseListeners();
+ addListener(SWT.KeyDown, new Listener() {
+
+ @Override
+ public void handleEvent(final Event event) {
+ handleKeyDown(event);
+ }
+ });
+ addPaintListener(new PaintListener() {
+ @Override
+ public void paintControl(final PaintEvent e) {
+ drawWidget(e);
+
+ }
+ });
+
+ }
+
+ /**
+ * Add the mouse listeners (mouse up, mouse down, mouse move, mouse wheel)
+ */
+ private void addMouseListeners() {
+ addListener(SWT.MouseDown, new Listener() {
+ @Override
+ public void handleEvent(final Event e) {
+ handleMouseDown(e);
+ }
+ });
+
+ addListener(SWT.MouseUp, new Listener() {
+ @Override
+ public void handleEvent(final Event e) {
+ handleMouseUp(e);
+ }
+ });
+
+ addListener(SWT.MouseMove, new Listener() {
+ @Override
+ public void handleEvent(final Event e) {
+ handleMouseMove(e);
+ }
+ });
+
+ addListener(SWT.MouseWheel, new Listener() {
+ @Override
+ public void handleEvent(final Event e) {
+ handleMouseWheel(e);
+ }
+ });
+
+ }
+
+ /**
+ * Code executed when the mouse is down
+ *
+ * @param e event
+ */
+ private void handleMouseDown(final Event e) {
+
+ if (this.upperHover) {
+ this.dragInProgress = true;
+ this.lastSelected = SELECTED_KNOB.UPPER;
+ this.previousUpperValue = this.upperValue;
+ return;
+ }
+
+ if (this.lowerHover) {
+ this.dragInProgress = true;
+ this.lastSelected = SELECTED_KNOB.LOWER;
+ this.previousLowerValue = this.lowerValue;
+ return;
+ }
+
+ this.dragInProgress = false;
+ this.lastSelected = SELECTED_KNOB.NONE;
+ }
+
+ /**
+ * Code executed when the mouse is up
+ *
+ * @param e event
+ */
+ private void handleMouseUp(final Event e) {
+ if (!this.dragInProgress) {
+ return;
+ }
+ this.dragInProgress = false;
+ if (!fireSelectionListeners(e)) {
+ if (this.lastSelected == SELECTED_KNOB.UPPER) {
+ this.upperValue = this.previousUpperValue;
+ } else {
+ this.lowerValue = this.previousLowerValue;
+ }
+ redraw();
+ }
+ }
+
+ /**
+ * Fire all selection listeners
+ *
+ * @param event selection event
+ * @return <code>true</code> if no listener cancels the selection,
+ * <code>false</code> otherwise
+ */
+ private boolean fireSelectionListeners(final Event event) {
+ for (final SelectionListener selectionListener : this.listeners) {
+ final SelectionEvent selectionEvent = new SelectionEvent(event);
+ selectionListener.widgetSelected(selectionEvent);
+ if (!selectionEvent.doit) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Code executed when the mouse pointer is moving
+ *
+ * @param e event
+ */
+ private void handleMouseMove(final Event e) {
+ final int x = e.x, y = e.y;
+ final Image img = this.orientation == SWT.HORIZONTAL ? this.slider : this.vSlider;
+ this.upperHover = x >= this.coordUpper.x && x <= this.coordUpper.x + img.getBounds().width && y >= this.coordUpper.y && y <= this.coordUpper.y + img.getBounds().height;
+ this.lowerHover = x >= this.coordLower.x && x <= this.coordLower.x + img.getBounds().width && y >= this.coordLower.y && y <= this.coordLower.y + img.getBounds().height;
+
+ if (this.dragInProgress) {
+ if (this.orientation == SWT.HORIZONTAL) {
+ final int mouseValue = (int) ((x - 9f) / computePixelSizeForHorizonalSlider()) + this.minimum;
+ if (this.lastSelected == SELECTED_KNOB.UPPER) {
+ this.upperValue = (int) (Math.ceil(mouseValue / this.increment) * this.increment) - this.increment;
+ checkUpperValue();
+ } else {
+ this.lowerValue = (int) (Math.ceil(mouseValue / this.increment) * this.increment) - this.increment;
+ checkLowerValue();
+ }
+
+ } else {
+ final int mouseValue = (int) ((y - 9f) / computePixelSizeForVerticalSlider()) + this.minimum;
+ if (this.lastSelected == SELECTED_KNOB.UPPER) {
+ this.upperValue = (int) (Math.ceil(mouseValue / this.increment) * this.increment) - this.increment;
+ checkUpperValue();
+ } else {
+ this.lowerValue = (int) (Math.ceil(mouseValue / this.increment) * this.increment) - this.increment;
+ checkLowerValue();
+ }
+
+ }
+ }
+
+ redraw();
+ }
+
+ /**
+ * Code executed when the mouse wheel is activated
+ *
+ * @param e event
+ */
+ private void handleMouseWheel(final Event e) {
+ if (this.lastSelected == SELECTED_KNOB.NONE) {
+ return;
+ }
+
+ if (this.lastSelected == SELECTED_KNOB.LOWER) {
+ this.lowerValue += e.count * this.increment;
+ checkLowerValue();
+ redraw();
+ } else {
+ this.upperValue += e.count * this.increment;
+ checkUpperValue();
+ redraw();
+ }
+ }
+
+ /**
+ * Check if the lower value is in ranges
+ */
+ private void checkLowerValue() {
+ if (this.lowerValue < this.minimum) {
+ this.lowerValue = this.minimum;
+ }
+ if (this.lowerValue > this.maximum) {
+ this.lowerValue = this.maximum;
+ }
+ if (this.lowerValue > this.upperValue) {
+ this.lowerValue = this.upperValue;
+ }
+ }
+
+ /**
+ * Check if the upper value is in ranges
+ */
+ private void checkUpperValue() {
+ if (this.upperValue < this.minimum) {
+ this.upperValue = this.minimum;
+ }
+ if (this.upperValue > this.maximum) {
+ this.upperValue = this.maximum;
+ }
+ if (this.upperValue < this.lowerValue) {
+ this.upperValue = this.lowerValue;
+ }
+ }
+
+ /**
+ * Draws the widget
+ *
+ * @param e paint event
+ */
+ private void drawWidget(final PaintEvent e) {
+ final Rectangle rect = this.getClientArea();
+ if (rect.width == 0 || rect.height == 0) {
+ return;
+ }
+ e.gc.setAdvanced(true);
+ e.gc.setAntialias(SWT.ON);
+ if (this.orientation == SWT.HORIZONTAL) {
+ drawHorizontalRangeSlider(e.gc);
+ } else {
+ drawVerticalRangeSlider(e.gc);
+ }
+
+ }
+
+ /**
+ * Draw the range slider (horizontal)
+ *
+ * @param gc graphic context
+ */
+ private void drawHorizontalRangeSlider(final GC gc) {
+ drawBackgroundHorizontal(gc);
+ drawBarsHorizontal(gc);
+ this.coordUpper = drawHorizontalKnob(gc, this.upperValue, true);
+ this.coordLower = drawHorizontalKnob(gc, this.lowerValue, false);
+ }
+
+ /**
+ * Draw the background
+ *
+ * @param gc graphic context
+ */
+ private void drawBackgroundHorizontal(final GC gc) {
+ final Rectangle clientArea = this.getClientArea();
+
+ gc.setBackground(getBackground());
+ gc.fillRectangle(clientArea);
+
+ if (isEnabled()) {
+ gc.setForeground(getForeground());
+ } else {
+ gc.setForeground(getDisplay().getSystemColor(SWT.COLOR_GRAY));
+ }
+ gc.drawRoundRectangle(9, 9, clientArea.width - 20, clientArea.height - 20, 3, 3);
+
+ final float pixelSize = computePixelSizeForHorizonalSlider();
+ final int startX = (int) (pixelSize * this.lowerValue);
+ final int endX = (int) (pixelSize * this.upperValue);
+ if (isEnabled()) {
+ gc.setBackground(getForeground());
+ } else {
+ gc.setBackground(getDisplay().getSystemColor(SWT.COLOR_GRAY));
+ }
+ gc.fillRectangle(12 + startX, 9, endX - startX - 6, clientArea.height - 20);
+
+ }
+
+ /**
+ * @return how many pixels corresponds to 1 point of value
+ */
+ private float computePixelSizeForHorizonalSlider() {
+ return (getClientArea().width - 20f) / (this.maximum - this.minimum);
+ }
+
+ /**
+ * Draw the bars
+ *
+ * @param gc graphic context
+ */
+ private void drawBarsHorizontal(final GC gc) {
+ final Rectangle clientArea = this.getClientArea();
+ if (isEnabled()) {
+ gc.setForeground(getForeground());
+ } else {
+ gc.setForeground(getDisplay().getSystemColor(SWT.COLOR_GRAY));
+ }
+
+ final float pixelSize = computePixelSizeForHorizonalSlider();
+ for (int i = 1; i < 10; i++) {
+ final int x = (int) (9 + pixelSize * (this.maximum - this.minimum) / 10 * i);
+ gc.drawLine(x, 4, x, 7);
+ gc.drawLine(x, clientArea.height - 6, x, clientArea.height - 9);
+ }
+
+ }
+
+ /**
+ * Draws an horizontal knob
+ *
+ * @param gc graphic context
+ * @param value corresponding value
+ * @param upper if <code>true</code>, draws the upper knob. If
+ * <code>false</code>, draws the lower knob
+ * @return the coordinate of the upper left corner of the knob
+ */
+ private Point drawHorizontalKnob(final GC gc, final int value, final boolean upper) {
+ final float pixelSize = computePixelSizeForHorizonalSlider();
+ final int x = (int) (pixelSize * value);
+ Image image;
+ if (upper) {
+ if (this.upperHover) {
+ image = this.dragInProgress ? this.sliderDrag : this.sliderHover;
+ } else if (this.lastSelected == SELECTED_KNOB.UPPER) {
+ image = this.sliderSelected;
+ } else {
+ image = this.slider;
+ }
+ } else {
+ if (this.lowerHover) {
+ image = this.dragInProgress ? this.sliderDrag : this.sliderHover;
+ } else if (this.lastSelected == SELECTED_KNOB.LOWER) {
+ image = this.sliderSelected;
+ } else {
+ image = this.slider;
+ }
+ }
+ if (isEnabled()) {
+ gc.drawImage(image, x + 5, getClientArea().height / 2 - this.slider.getBounds().height / 2);
+ } else {
+ final Image temp = new Image(getDisplay(), image, SWT.IMAGE_DISABLE);
+ gc.drawImage(temp, x + 5, getClientArea().height / 2 - this.slider.getBounds().height / 2);
+ temp.dispose();
+ }
+ return new Point(x + 5, getClientArea().height / 2 - this.slider.getBounds().height / 2);
+ }
+
+ /**
+ * Draw the range slider (vertical)
+ *
+ * @param gc graphic context
+ */
+ private void drawVerticalRangeSlider(final GC gc) {
+ drawBackgroundVertical(gc);
+ drawBarsVertical(gc);
+ this.coordUpper = drawVerticalKnob(gc, this.upperValue, true);
+ this.coordLower = drawVerticalKnob(gc, this.lowerValue, false);
+ }
+
+ /**
+ * Draws the background
+ *
+ * @param gc graphic context
+ */
+ private void drawBackgroundVertical(final GC gc) {
+ final Rectangle clientArea = this.getClientArea();
+ gc.setBackground(getBackground());
+ gc.fillRectangle(clientArea);
+
+ if (isEnabled()) {
+ gc.setForeground(getForeground());
+ } else {
+ gc.setForeground(getDisplay().getSystemColor(SWT.COLOR_GRAY));
+ }
+ gc.drawRoundRectangle(9, 9, clientArea.width - 20, clientArea.height - 20, 3, 3);
+
+ final float pixelSize = computePixelSizeForVerticalSlider();
+ final int startY = (int) (pixelSize * this.lowerValue);
+ final int endY = (int) (pixelSize * this.upperValue);
+ if (isEnabled()) {
+ gc.setBackground(getForeground());
+ } else {
+ gc.setBackground(getDisplay().getSystemColor(SWT.COLOR_GRAY));
+ }
+ gc.fillRectangle(9, 12 + startY, clientArea.width - 20, endY - startY - 6);
+
+ }
+
+ /**
+ * @return how many pixels corresponds to 1 point of value
+ */
+ private float computePixelSizeForVerticalSlider() {
+ return (getClientArea().height - 20f) / (this.maximum - this.minimum);
+ }
+
+ /**
+ * Draws the bars
+ *
+ * @param gc graphic context
+ */
+ private void drawBarsVertical(final GC gc) {
+ final Rectangle clientArea = this.getClientArea();
+ if (isEnabled()) {
+ gc.setForeground(getForeground());
+ } else {
+ gc.setForeground(getDisplay().getSystemColor(SWT.COLOR_GRAY));
+ }
+
+ final float pixelSize = computePixelSizeForVerticalSlider();
+ for (int i = 1; i < 10; i++) {
+ final int y = (int) (9 + pixelSize * (this.maximum - this.minimum) / 10 * i);
+ gc.drawLine(4, y, 7, y);
+ gc.drawLine(clientArea.width - 6, y, clientArea.width - 9, y);
+
+ }
+
+ }
+
+ /**
+ * Draws a vertical knob
+ *
+ * @param gc graphic context
+ * @param value corresponding value
+ * @param upper if <code>true</code>, draws the upper knob. If
+ * <code>false</code>, draws the lower knob
+ * @return the coordinate of the upper left corner of the knob
+ */
+ private Point drawVerticalKnob(final GC gc, final int value, final boolean upper) {
+ final float pixelSize = computePixelSizeForVerticalSlider();
+ final int y = (int) (pixelSize * value);
+
+ Image image;
+ if (upper) {
+ if (this.upperHover) {
+ image = this.dragInProgress ? this.vSliderDrag : this.vSliderHover;
+ } else if (this.lastSelected == SELECTED_KNOB.UPPER) {
+ image = this.vSliderSelected;
+ } else {
+ image = this.vSlider;
+ }
+ } else {
+ if (this.lowerHover) {
+ image = this.dragInProgress ? this.vSliderDrag : this.vSliderHover;
+ } else if (this.lastSelected == SELECTED_KNOB.LOWER) {
+ image = this.vSliderSelected;
+ } else {
+ image = this.vSlider;
+ }
+ }
+
+ if (isEnabled()) {
+ gc.drawImage(image, getClientArea().width / 2 - 8, y + 2);
+ } else {
+ final Image temp = new Image(getDisplay(), image, SWT.IMAGE_DISABLE);
+ gc.drawImage(temp, getClientArea().width / 2 - 8, y + 2);
+ temp.dispose();
+
+ }
+ return new Point(getClientArea().width / 2 - 8, y + 2);
+ }
+
+ /**
+ * Code executed when a key is typed
+ *
+ * @param event event
+ */
+ private void handleKeyDown(final Event event) {
+
+ boolean needRedraw = false;
+
+ if (this.lastSelected == SELECTED_KNOB.NONE) {
+ this.lastSelected = SELECTED_KNOB.LOWER;
+ }
+
+ switch (event.keyCode) {
+ case SWT.HOME:
+ if (this.lastSelected == SELECTED_KNOB.UPPER) {
+ this.upperValue = this.minimum;
+ } else {
+ this.lowerValue = this.minimum;
+ }
+ needRedraw = true;
+ break;
+ case SWT.END:
+ if (this.lastSelected == SELECTED_KNOB.UPPER) {
+ this.upperValue = this.maximum;
+ } else {
+ this.upperValue = this.maximum;
+ }
+ needRedraw = true;
+ break;
+ case SWT.PAGE_UP:
+ if (this.lastSelected == SELECTED_KNOB.UPPER) {
+ this.upperValue += this.pageIncrement;
+ } else {
+ this.lowerValue += this.pageIncrement;
+ }
+ needRedraw = true;
+ break;
+ case SWT.PAGE_DOWN:
+ if (this.lastSelected == SELECTED_KNOB.UPPER) {
+ this.upperValue -= this.pageIncrement;
+ } else {
+ this.lowerValue -= this.pageIncrement;
+ }
+ needRedraw = true;
+ break;
+ case SWT.ARROW_LEFT:
+ case SWT.ARROW_UP:
+ if (this.lastSelected == SELECTED_KNOB.UPPER) {
+ this.upperValue -= this.increment;
+ } else {
+ this.lowerValue -= this.increment;
+ }
+ needRedraw = true;
+ break;
+ case SWT.ARROW_RIGHT:
+ case SWT.ARROW_DOWN:
+ if (this.lastSelected == SELECTED_KNOB.UPPER) {
+ this.upperValue += this.increment;
+ } else {
+ this.lowerValue += this.increment;
+ }
+ needRedraw = true;
+ break;
+ default:
+ break;
+ }
+
+ if (needRedraw) {
+ if (this.lastSelected == SELECTED_KNOB.UPPER) {
+ checkUpperValue();
+ } else {
+ checkLowerValue();
+ }
+ redraw();
+ }
+ }
+
+ /**
+ * Adds the listener to the collection of listeners who will be notified
+ * when the user changes the receiver's value, by sending it one of the
+ * messages defined in the <code>SelectionListener</code> interface.
+ * <p>
+ * <code>widgetSelected</code> is called when the user changes the
+ * receiver's value. <code>widgetDefaultSelected</code> is not called.
+ * </p>
+ *
+ * @param listener the listener which should be notified
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the listener is null</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ *
+ * @see SelectionListener
+ * @see #removeSelectionListener
+ */
+ public void addSelectionListener(final SelectionListener listener) {
+ checkWidget();
+ this.listeners.add(listener);
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Composite#computeSize(int, int, boolean)
+ */
+ @Override
+ public Point computeSize(final int wHint, final int hHint, final boolean changed) {
+ final int width, height;
+ checkWidget();
+ if (this.orientation == SWT.HORIZONTAL) {
+ if (wHint < 100) {
+ width = 100;
+ } else {
+ width = wHint;
+ }
+
+ if (hHint < 30) {
+ height = 30;
+ } else {
+ height = hHint;
+ }
+ } else {
+ if (wHint < 30) {
+ width = 30;
+ } else {
+ width = wHint;
+ }
+
+ if (hHint < 100) {
+ height = 100;
+ } else {
+ height = hHint;
+ }
+ }
+
+ return new Point(width, height);
+ }
+
+ /**
+ * Returns the amount that the selected receiver's value will be modified by
+ * when the up/down (or right/left) arrows are pressed.
+ *
+ * @return the increment
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public int getIncrement() {
+ checkWidget();
+ return this.increment;
+ }
+
+ /**
+ * Returns the 'lower selection', which is the lower receiver's position.
+ *
+ * @return the selection
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public int getLowerValue() {
+ checkWidget();
+ return this.lowerValue;
+ }
+
+ /**
+ * Returns the maximum value which the receiver will allow.
+ *
+ * @return the maximum
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public int getMaximum() {
+ checkWidget();
+ return this.maximum;
+ }
+
+ /**
+ * Returns the minimum value which the receiver will allow.
+ *
+ * @return the minimum
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public int getMinimum() {
+ checkWidget();
+ return this.minimum;
+ }
+
+ /**
+ * Returns the amount that the selected receiver's value will be modified by
+ * when the page increment/decrement areas are selected.
+ *
+ * @return the page increment
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public int getPageIncrement() {
+ checkWidget();
+ return this.pageIncrement;
+ }
+
+ /**
+ * Returns the 'selection', which is an array where the first element is the
+ * lower selection, and the second element is the upper selection
+ *
+ * @return the selection
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public int[] getSelection() {
+ checkWidget();
+ final int[] selection = new int[2];
+ selection[0] = this.lowerValue;
+ selection[1] = this.upperValue;
+ return selection;
+ }
+
+ /**
+ * Returns the 'upper selection', which is the upper receiver's position.
+ *
+ * @return the selection
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public int getUpperValue() {
+ checkWidget();
+ return this.upperValue;
+ }
+
+ /**
+ * Removes the listener from the collection of listeners who will be
+ * notified when the user changes the receiver's value.
+ *
+ * @param listener the listener which should no longer be notified
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the listener is null</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ *
+ * @see SelectionListener
+ * @see #addSelectionListener
+ */
+ public void removeSelectionListener(final SelectionListener listener) {
+ checkWidget();
+ this.listeners.remove(listener);
+ }
+
+ /**
+ * Sets the amount that the selected receiver's value will be modified by
+ * when the up/down (or right/left) arrows are pressed to the argument,
+ * which must be at least one.
+ *
+ * @param increment the new increment (must be greater than zero)
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void setIncrement(final int increment) {
+ checkWidget();
+ this.increment = increment;
+ redraw();
+ }
+
+ /**
+ * Sets the 'lower selection', which is the receiver's lower value, to the
+ * argument which must be greater than or equal to zero.
+ *
+ * @param value the new selection (must be zero or greater)
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void setLowerValue(final int value) {
+ checkWidget();
+ if (this.minimum <= value && value <= this.maximum && value <= this.upperValue) {
+ this.lowerValue = value;
+ }
+ redraw();
+ }
+
+ /**
+ * Sets the maximum value that the receiver will allow. This new value will
+ * be ignored if it is not greater than the receiver's current minimum
+ * value. If the new maximum is applied then the receiver's selection value
+ * will be adjusted if necessary to fall within its new range.
+ *
+ * @param value the new maximum, which must be greater than the current
+ * minimum
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void setMaximum(final int value) {
+ checkWidget();
+ if (this.minimum <= value) {
+ this.maximum = value;
+ if (this.lowerValue >= this.maximum) {
+ this.lowerValue = this.maximum;
+ }
+ if (this.upperValue >= this.maximum) {
+ this.upperValue = this.maximum;
+ }
+ }
+ redraw();
+ }
+
+ /**
+ * Sets the minimum value that the receiver will allow. This new value will
+ * be ignored if it is negative or is not less than the receiver's current
+ * maximum value. If the new minimum is applied then the receiver's
+ * selection value will be adjusted if necessary to fall within its new
+ * range.
+ *
+ * @param value the new minimum, which must be nonnegative and less than the
+ * current maximum
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void setMinimum(final int value) {
+ checkWidget();
+ if (this.maximum >= value) {
+ this.minimum = value;
+ if (this.lowerValue <= this.minimum) {
+ this.lowerValue = this.minimum;
+ }
+ if (this.upperValue <= this.minimum) {
+ this.upperValue = this.minimum;
+ }
+ }
+ redraw();
+ }
+
+ /**
+ * Sets the amount that the receiver's value will be modified by when the
+ * page increment/decrement areas are selected to the argument, which must
+ * be at least one.
+ *
+ * @param pageIncrement the page increment (must be greater than zero)
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void setPageIncrement(final int pageIncrement) {
+ checkWidget();
+ this.pageIncrement = pageIncrement;
+ }
+
+ /**
+ * Sets the 'selection', which is the receiver's value, to the argument
+ * which must be greater than or equal to zero.
+ *
+ * @param value the new selection (first value is lower value, second value
+ * is upper value)
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void setSelection(final int[] values) {
+ checkWidget();
+ setLowerValue(values[0]);
+ setUpperValue(values[1]);
+ checkUpperValue();
+ checkLowerValue();
+ redraw();
+ }
+
+ /**
+ * Sets the 'selection', which is the receiver's value, argument which must
+ * be greater than or equal to zero.
+ *
+ * @param lowerValue the new lower selection (must be zero or greater)
+ * @param upperValue the new upper selection (must be zero or greater)
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void setSelection(final int lowerValue, final int upperValue) {
+ checkWidget();
+ setLowerValue(lowerValue);
+ setUpperValue(upperValue);
+ }
+
+ /**
+ * Sets the 'upper selection', which is the upper receiver's value, argument
+ * which must be greater than or equal to zero.
+ *
+ * @param value the new selection (must be zero or greater)
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void setUpperValue(final int value) {
+ checkWidget();
+ if (this.minimum <= value && value <= this.maximum && value >= this.lowerValue) {
+ this.upperValue = value;
+ }
+ redraw();
+ }
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/switchButton/SwitchButton.java b/org.tizen.common.externals/src/org/mihalis/opal/switchButton/SwitchButton.java
new file mode 100644
index 000000000..c3b0c3ce1
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/switchButton/SwitchButton.java
@@ -0,0 +1,938 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON
+ * 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:
+ * Laurent CARON (laurent.caron at gmail dot com) - initial API and implementation
+ *******************************************************************************/
+package org.mihalis.opal.switchButton;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.SWTException;
+import org.eclipse.swt.events.DisposeEvent;
+import org.eclipse.swt.events.DisposeListener;
+import org.eclipse.swt.events.MouseAdapter;
+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.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.Point;
+import org.eclipse.swt.graphics.Rectangle;
+import org.eclipse.swt.widgets.Canvas;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Event;
+
+/**
+ * Instances of this class are simple switch button.
+ * <dl>
+ * <dt><b>Styles:</b></dt>
+ * <dd>(none)</dd>
+ * <dt><b>Events:</b></dt>
+ * <dd>Selection</dd>
+ * </dl>
+ */
+public class SwitchButton extends Canvas {
+
+ /**
+ * Selection
+ */
+ private boolean selection;
+
+ /**
+ * Text displayed for the selected value (default = "On")
+ */
+ private String textForSelect;
+
+ /**
+ * Text displayed for the unselected value (default = "Off")
+ */
+ private String textForUnselect;
+
+ /**
+ * Text corresponding to the button (default is "")
+ */
+ private String text;
+
+ /**
+ * If true, display round rectangles instead of rectangles (default value is
+ * true)
+ */
+ private boolean round;
+
+ /**
+ * if not null, displays a rectangle (or a round rectangle) around the whole
+ * widget. Default value is null.
+ */
+ private Color borderColor;
+
+ /**
+ * if not null, displays a glow effect when the mouse is over the widget.
+ * Default value is null.
+ */
+ private Color focusColor;
+
+ /**
+ * Colors when the button is selected
+ */
+ private Color selectedForegroundColor, selectedBackgroundColor;
+
+ /**
+ * Colors when the button is not selected
+ */
+ private Color unselectedForegroundColor, unselectedBackgroundColor;
+
+ /**
+ * Colors for the button
+ */
+ private Color buttonBorderColor, buttonBackgroundColor1, buttonBackgroundColor2;
+
+ /**
+ * Gap between the button and the text (default value is 5)
+ */
+ private int gap;
+
+ /**
+ * Margin inside the button
+ */
+ private static final int INSIDE_BUTTON_MARGIN = 5;
+
+ /**
+ * Graphical context for this button
+ */
+ private GC gc;
+
+ /**
+ * List of selection listeners
+ */
+ private final List<SelectionListener> listOfSelectionListeners;
+
+ /**
+ * True when the mouse entered the widget
+ */
+ private boolean mouseInside;
+
+ /**
+ * Constructs a new instance of this class given its parent and a style
+ * value describing its behavior and appearance.
+ * <p>
+ * The style value is either one of the style constants defined in class
+ * <code>SWT</code> which is applicable to instances of this class, or must
+ * be built by <em>bitwise OR</em>'ing together (that is, using the
+ * <code>int</code> "|" operator) two or more of those <code>SWT</code>
+ * style constants. The class description lists the style constants that are
+ * applicable to the class. Style bits are also inherited from superclasses.
+ * </p>
+ *
+ * @param parent a composite control which will be the parent of the new
+ * instance (cannot be null)
+ * @param style the style of control to construct
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the parent is null</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the parent</li>
+ * </ul>
+ *
+ */
+ public SwitchButton(final Composite parent, final int style) {
+ super(parent, style | SWT.DOUBLE_BUFFERED);
+
+ this.selection = false;
+ this.textForSelect = "On";
+ this.textForUnselect = "Off";
+ this.round = true;
+ this.borderColor = null;
+ this.focusColor = this.getDisplay().getSystemColor(SWT.COLOR_YELLOW);
+ this.selectedForegroundColor = this.getDisplay().getSystemColor(SWT.COLOR_WHITE);
+ this.selectedBackgroundColor = new Color(this.getDisplay(), 0, 112, 195);
+ this.unselectedForegroundColor = this.getDisplay().getSystemColor(SWT.COLOR_BLACK);
+ this.unselectedBackgroundColor = new Color(this.getDisplay(), 203, 203, 203);
+
+ this.buttonBorderColor = new Color(this.getDisplay(), 96, 96, 96);
+ this.buttonBackgroundColor1 = new Color(this.getDisplay(), 254, 254, 254);
+ this.buttonBackgroundColor2 = new Color(this.getDisplay(), 192, 192, 192);
+
+ this.gap = 5;
+
+ this.listOfSelectionListeners = new ArrayList<SelectionListener>();
+
+ this.addDisposeListener(new DisposeListener() {
+
+ @Override
+ public void widgetDisposed(final DisposeEvent e) {
+ SwitchButton.this.selectedBackgroundColor.dispose();
+ SwitchButton.this.unselectedBackgroundColor.dispose();
+ SwitchButton.this.buttonBorderColor.dispose();
+ SwitchButton.this.buttonBackgroundColor1.dispose();
+ SwitchButton.this.buttonBackgroundColor2.dispose();
+ }
+ });
+
+ this.addPaintListener(new PaintListener() {
+ @Override
+ public void paintControl(final PaintEvent event) {
+ SwitchButton.this.onPaint(event);
+ }
+ });
+
+ this.addMouseListener(new MouseAdapter() {
+
+ /**
+ * @see org.eclipse.swt.events.MouseAdapter#mouseUp(org.eclipse.swt.events.MouseEvent)
+ */
+ @Override
+ public void mouseUp(final MouseEvent e) {
+ if (SwitchButton.this.fireSelectionListeners(e)) {
+ SwitchButton.this.selection = !SwitchButton.this.selection;
+ SwitchButton.this.redraw();
+ }
+ }
+
+ });
+
+ this.mouseInside = false;
+ this.addMouseTrackListener(new MouseTrackListener() {
+
+ @Override
+ public void mouseHover(final MouseEvent e) {
+ SwitchButton.this.mouseInside = true;
+ SwitchButton.this.redraw();
+ }
+
+ @Override
+ public void mouseExit(final MouseEvent e) {
+ SwitchButton.this.mouseInside = false;
+ SwitchButton.this.redraw();
+ }
+
+ @Override
+ public void mouseEnter(final MouseEvent e) {
+ SwitchButton.this.mouseInside = true;
+ SwitchButton.this.redraw();
+ }
+ });
+
+ }
+
+ /**
+ * Paint the widget
+ *
+ * @param event paint event
+ */
+ private void onPaint(final PaintEvent event) {
+ final Rectangle rect = this.getClientArea();
+ if (rect.width == 0 || rect.height == 0) {
+ return;
+ }
+ this.gc = event.gc;
+ this.gc.setAntialias(SWT.ON);
+
+ final Point buttonSize = this.computeButtonSize();
+ this.drawSwitchButton(buttonSize);
+ this.drawText(buttonSize);
+
+ if (this.borderColor != null) {
+ this.drawBorder();
+ }
+
+ }
+
+ /**
+ * Draw the switch button
+ *
+ * @param buttonSize size of the button
+ */
+ private void drawSwitchButton(final Point buttonSize) {
+ // Draw the background of the button
+ this.gc.setForeground(this.buttonBorderColor);
+ if (this.round) {
+ this.gc.drawRoundRectangle(2, 2, buttonSize.x, buttonSize.y, 3, 3);
+ } else {
+ this.gc.drawRectangle(2, 2, buttonSize.x, buttonSize.y);
+ }
+
+ this.drawRightPart(buttonSize);
+ this.drawLeftPart(buttonSize);
+ this.gc.setClipping(this.getClientArea());
+ this.drawToggleButton(buttonSize);
+ }
+
+ /**
+ * Draw the right part of the button
+ *
+ * @param buttonSize size of the button
+ */
+ private void drawRightPart(final Point buttonSize) {
+ this.gc.setForeground(this.selectedBackgroundColor);
+ this.gc.setBackground(this.selectedBackgroundColor);
+ this.gc.setClipping(3, 3, buttonSize.x / 2, buttonSize.y - 1);
+ if (this.round) {
+ this.gc.fillRoundRectangle(2, 2, buttonSize.x, buttonSize.y, 3, 3);
+ } else {
+ this.gc.fillRectangle(2, 2, buttonSize.x, buttonSize.y);
+ }
+ this.gc.setForeground(this.selectedForegroundColor);
+ final Point textSize = this.gc.textExtent(this.textForSelect);
+ this.gc.drawString(this.textForSelect, (buttonSize.x / 2 - textSize.x) / 2 + 3, (buttonSize.y - textSize.y) / 2 + 3);
+ }
+
+ /**
+ * Draw the left part of the button
+ *
+ * @param buttonSize size of the button
+ */
+ private void drawLeftPart(final Point buttonSize) {
+ this.gc.setForeground(this.unselectedBackgroundColor);
+ this.gc.setBackground(this.unselectedBackgroundColor);
+ this.gc.setClipping(buttonSize.x / 2 + 3, 3, buttonSize.x / 2, buttonSize.y - 1);
+ if (this.round) {
+ this.gc.fillRoundRectangle(2, 2, buttonSize.x, buttonSize.y, 3, 3);
+ } else {
+ this.gc.fillRectangle(2, 2, buttonSize.x, buttonSize.y);
+ }
+ this.gc.setForeground(this.unselectedForegroundColor);
+ final Point textSize = this.gc.textExtent(this.textForUnselect);
+
+ this.gc.drawString(this.textForUnselect, buttonSize.x / 2 + (buttonSize.x / 2 - textSize.x) / 2 + 3, (buttonSize.y - textSize.y) / 2 + 3);
+ }
+
+ /**
+ * Draw the toggle button
+ *
+ * @param buttonSize size of the button
+ */
+ private void drawToggleButton(final Point buttonSize) {
+ this.gc.setForeground(this.buttonBackgroundColor1);
+ this.gc.setBackground(this.buttonBackgroundColor2);
+ if (this.selection) {
+ this.gc.fillGradientRectangle(3, 3, buttonSize.x / 2, buttonSize.y, true);
+ } else {
+ this.gc.fillGradientRectangle(buttonSize.x / 2, 3, buttonSize.x / 2 + 2, buttonSize.y - 1, true);
+ }
+
+ this.gc.setForeground(this.buttonBorderColor);
+ if (this.selection) {
+ this.gc.drawRoundRectangle(2, 2, buttonSize.x / 2, buttonSize.y, 3, 3);
+ } else {
+ this.gc.drawRoundRectangle(buttonSize.x / 2, 2, buttonSize.x / 2 + 2, buttonSize.y, 3, 3);
+ }
+
+ if (this.focusColor != null && this.mouseInside) {
+ this.gc.setForeground(this.focusColor);
+ this.gc.setLineWidth(2);
+ if (this.selection) {
+ this.gc.drawRoundRectangle(3, 3, buttonSize.x / 2, buttonSize.y - 1, 3, 3);
+ } else {
+ this.gc.drawRoundRectangle(buttonSize.x / 2 + 1, 3, buttonSize.x / 2, buttonSize.y - 2, 3, 3);
+ }
+ this.gc.setLineWidth(1);
+ }
+
+ }
+
+ /**
+ * @return the button size
+ */
+ private Point computeButtonSize() {
+ // Compute size for the left part
+ final Point sizeForLeftPart = this.gc.stringExtent(this.textForSelect);
+ // Compute size for the right part
+ final Point sizeForRightPart = this.gc.stringExtent(this.textForUnselect);
+
+ // Compute whole size
+ final int width = Math.max(sizeForLeftPart.x, sizeForRightPart.x) * 2 + 2 * INSIDE_BUTTON_MARGIN;
+ final int height = Math.max(sizeForLeftPart.y, sizeForRightPart.y) + 2 * INSIDE_BUTTON_MARGIN;
+
+ return new Point(width, height);
+ }
+
+ /**
+ * Draws the text besides the button
+ *
+ * @param buttonSize whole size of the button
+ */
+ private void drawText(final Point buttonSize) {
+ this.gc.setForeground(this.getForeground());
+ this.gc.setBackground(this.getBackground());
+
+ final int widgetHeight = this.computeSize(0, 0, true).y;
+ final int textHeight = this.gc.stringExtent(this.text).y;
+ final int x = 2 + buttonSize.x + this.gap;
+
+ this.gc.drawString(this.text, x, (widgetHeight - textHeight) / 2);
+ }
+
+ /**
+ * Draw (eventually) the border around the button
+ */
+ private void drawBorder() {
+ if (this.borderColor == null) {
+ return;
+ }
+
+ this.gc.setForeground(this.borderColor);
+ final Point temp = this.computeSize(0, 0, false);
+ if (this.round) {
+ this.gc.drawRoundRectangle(0, 0, temp.x - 2, temp.y - 2, 3, 3);
+ } else {
+ this.gc.drawRectangle(0, 0, temp.x - 2, temp.y - 2);
+ }
+
+ }
+
+ /**
+ * Fire the selection listeners
+ *
+ * @param mouseEvent mouse event
+ * @return true if the selection could be changed, false otherwise
+ */
+ private boolean fireSelectionListeners(final MouseEvent mouseEvent) {
+ for (final SelectionListener listener : this.listOfSelectionListeners) {
+ final Event event = new Event();
+
+ event.button = mouseEvent.button;
+ event.display = this.getDisplay();
+ event.item = null;
+ event.widget = this;
+ event.data = null;
+ event.time = mouseEvent.time;
+ event.x = mouseEvent.x;
+ event.y = mouseEvent.y;
+
+ final SelectionEvent selEvent = new SelectionEvent(event);
+ listener.widgetSelected(selEvent);
+ if (!selEvent.doit) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Adds the listener to the collection of listeners who will be notified
+ * when the control is selected by the user, by sending it one of the
+ * messages defined in the <code>SelectionListener</code> interface.
+ * <p>
+ * <code>widgetSelected</code> is called when the control is selected by the
+ * user. <code>widgetDefaultSelected</code> is not called.
+ * </p>
+ *
+ * @param listener the listener which should be notified
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the listener is null</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ *
+ * @see SelectionListener
+ * @see #removeSelectionListener
+ * @see SelectionEvent
+ */
+ public void addSelectionListener(final SelectionListener listener) {
+ this.checkWidget();
+ if (listener == null) {
+ SWT.error(SWT.ERROR_NULL_ARGUMENT);
+ }
+ this.listOfSelectionListeners.add(listener);
+ }
+
+ /**
+ * Removes the listener from the collection of listeners who will be
+ * notified when the control is selected by the user.
+ *
+ * @param listener the listener which should no longer be notified
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the listener is null</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ *
+ * @see SelectionListener
+ * @see #addSelectionListener
+ */
+ public void removeSelectionListener(final SelectionListener listener) {
+ this.checkWidget();
+ if (listener == null) {
+ SWT.error(SWT.ERROR_NULL_ARGUMENT);
+ }
+ this.listOfSelectionListeners.remove(listener);
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Composite#computeSize(int, int, boolean)
+ */
+ @Override
+ public Point computeSize(final int wHint, final int hHint, final boolean changed) {
+ this.checkWidget();
+ boolean disposeGC = false;
+ if (this.gc == null) {
+ this.gc = new GC(this);
+ disposeGC = true;
+ }
+
+ final Point buttonSize = this.computeButtonSize();
+ int width = buttonSize.x;
+ int height = buttonSize.y;
+
+ if (this.text != null && this.text.trim().length() > 0) {
+ final Point textSize = this.gc.textExtent(this.text);
+ width += textSize.x + this.gap + 1;
+ }
+
+ width += 4;
+ height += 6;
+
+ if (disposeGC) {
+ this.gc.dispose();
+ }
+
+ return new Point(width, height);
+ }
+
+ /**
+ * @return the selection state of the button
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public boolean getSelection() {
+ this.checkWidget();
+ return this.selection;
+ }
+
+ /**
+ * @param selection the selection state of the button
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void setSelection(final boolean selection) {
+ this.checkWidget();
+ this.selection = selection;
+ }
+
+ /**
+ * @return the text used to display the selection
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public String getTextForSelect() {
+ this.checkWidget();
+ return this.textForSelect;
+ }
+
+ /**
+ * @param textForSelect the text used to display the selection
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void setTextForSelect(final String textForSelect) {
+ this.checkWidget();
+ this.textForSelect = textForSelect;
+ }
+
+ /**
+ * @return the text used to display the unselected option
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public String getTextForUnselect() {
+ this.checkWidget();
+ return this.textForUnselect;
+ }
+
+ /**
+ * @param textForUnselect the text used to display the unselected option
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void setTextForUnselect(final String textForUnselect) {
+ this.checkWidget();
+ this.textForUnselect = textForUnselect;
+ }
+
+ /**
+ * @return the text displayed in the widget
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public String getText() {
+ this.checkWidget();
+ return this.text;
+ }
+
+ /**
+ * @param the text displayed in the widget
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void setText(final String text) {
+ this.checkWidget();
+ this.text = text;
+ }
+
+ /**
+ * @return the round flag
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public boolean isRound() {
+ this.checkWidget();
+ return this.round;
+ }
+
+ /**
+ * @param round the round flag to set. If true, the widget is composed of
+ * round rectangle instead of rectangles
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void setRound(final boolean round) {
+ this.checkWidget();
+ this.round = round;
+ }
+
+ /**
+ * @return the border's color. If null, no border is displayed
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public Color getBorderColor() {
+ this.checkWidget();
+ return this.borderColor;
+ }
+
+ /**
+ * @param borderColor the border's color. If null, no border is displayed.
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void setBorderColor(final Color borderColor) {
+ this.checkWidget();
+ this.borderColor = borderColor;
+ }
+
+ /**
+ * @return the focus color. If null, no focus effect is displayed.
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public Color getFocusColor() {
+ this.checkWidget();
+ return this.focusColor;
+ }
+
+ /**
+ * @param focusColor the focus color to set. If null, no focus effect is
+ * displayed.
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void setFocusColor(final Color focusColor) {
+ this.checkWidget();
+ this.focusColor = focusColor;
+ }
+
+ /**
+ * @return the foreground color of the left part of the widget (selection is
+ * on)
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public Color getSelectedForegroundColor() {
+ this.checkWidget();
+ return this.selectedForegroundColor;
+ }
+
+ /**
+ * @param the foreground color of the left part of the widget (selection is
+ * on)
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void setSelectedForegroundColor(final Color selectedForegroundColor) {
+ this.checkWidget();
+ this.selectedForegroundColor = selectedForegroundColor;
+ }
+
+ /**
+ * @return the background color of the left part of the widget (selection is
+ * on)
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public Color getSelectedBackgroundColor() {
+ this.checkWidget();
+ return this.selectedBackgroundColor;
+ }
+
+ /**
+ * @param the background color of the left part of the widget (selection is
+ * on)
+ */
+ public void setSelectedBackgroundColor(final Color selectedBackgroundColor) {
+ this.checkWidget();
+ this.selectedBackgroundColor = selectedBackgroundColor;
+ }
+
+ /**
+ * @return the foreground color of the left part of the widget (selection is
+ * on)
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public Color getUnselectedForegroundColor() {
+ this.checkWidget();
+ return this.unselectedForegroundColor;
+ }
+
+ /**
+ * @param unselectedForegroundColor the foreground color of the left part of
+ * the widget (selection is on)
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void setUnselectedForegroundColor(final Color unselectedForegroundColor) {
+ this.checkWidget();
+ this.unselectedForegroundColor = unselectedForegroundColor;
+ }
+
+ /**
+ * @return the background color of the left part of the widget (selection is
+ * on)
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public Color getUnselectedBackgroundColor() {
+ this.checkWidget();
+ return this.unselectedBackgroundColor;
+ }
+
+ /**
+ * @param unselectedBackgroundColor the background color of the left part of
+ * the widget (selection is on)
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void setUnselectedBackgroundColor(final Color unselectedBackgroundColor) {
+ this.checkWidget();
+ this.unselectedBackgroundColor = unselectedBackgroundColor;
+ }
+
+ /**
+ * @return the border color of the switch button
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public Color getButtonBorderColor() {
+ this.checkWidget();
+ return this.buttonBorderColor;
+ }
+
+ /**
+ * @param buttonBorderColor the border color of the switch button
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void setButtonBorderColor(final Color buttonBorderColor) {
+ this.checkWidget();
+ this.buttonBorderColor = buttonBorderColor;
+ }
+
+ /**
+ * @return the first color of the toggle button
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public Color getButtonBackgroundColor1() {
+ this.checkWidget();
+ return this.buttonBackgroundColor1;
+ }
+
+ /**
+ * @param buttonBackgroundColor1 the first color of the toggle button
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void setButtonBackgroundColor1(final Color buttonBackgroundColor1) {
+ this.checkWidget();
+ this.buttonBackgroundColor1 = buttonBackgroundColor1;
+ }
+
+ /**
+ * @return the second color of the toggle button
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public Color getButtonBackgroundColor2() {
+ this.checkWidget();
+ return this.buttonBackgroundColor2;
+ }
+
+ /**
+ * @param buttonBackgroundColor2 the second color of the toggle button
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void setButtonBackgroundColor2(final Color buttonBackgroundColor2) {
+ this.checkWidget();
+ this.buttonBackgroundColor2 = buttonBackgroundColor2;
+ }
+
+ /**
+ * @return the gap value
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public int getGap() {
+ this.checkWidget();
+ return this.gap;
+ }
+
+ /**
+ * @param gap the gap value to set
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void setGap(final int gap) {
+ this.checkWidget();
+ this.gap = gap;
+ }
+
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/textAssist/TextAssist.java b/org.tizen.common.externals/src/org/mihalis/opal/textAssist/TextAssist.java
new file mode 100755
index 000000000..08bcebc73
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/textAssist/TextAssist.java
@@ -0,0 +1,694 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON.
+ * 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 (Snippet 320)
+ * Laurent CARON (laurent.caron@gmail.com) - Make a widget from the snippet
+ *******************************************************************************/
+package org.mihalis.opal.textAssist;
+
+import java.util.List;
+
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.SWTException;
+import org.eclipse.swt.events.ModifyListener;
+import org.eclipse.swt.events.SelectionListener;
+import org.eclipse.swt.events.VerifyListener;
+import org.eclipse.swt.graphics.Font;
+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.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 org.eclipse.swt.widgets.Text;
+import org.eclipse.swt.widgets.Widget;
+
+/**
+ * Instances of this class are selectable user interface objects that allow the
+ * user to enter and modify text. The difference with the Text widget is that
+ * when the user types something, some propositions are displayed.
+ *
+ * @see org.eclipse.swt.widgets.Text
+ */
+public class TextAssist extends Composite {
+
+ private final Text text;
+ private final Shell popup;
+ private final Table table;
+ private TextAssistContentProvider contentProvider;
+ private int numberOfLines;
+
+ /**
+ * Constructs a new instance of this class given its parent and a style
+ * value describing its behavior and appearance.
+ * <p>
+ * The style value is either one of the style constants defined in class
+ * <code>SWT</code> which is applicable to instances of this class, or must
+ * be built by <em>bitwise OR</em>'ing together (that is, using the
+ * <code>int</code> "|" operator) two or more of those <code>SWT</code>
+ * style constants. The class description lists the style constants that are
+ * applicable to the class. Style bits are also inherited from superclasses.
+ * </p>
+ *
+ * @param parent a composite control which will be the parent of the new
+ * instance (cannot be null)
+ * @param style the style of control to construct
+ * @param contentProvider the content provider
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the parent is null</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the parent</li>
+ * <li>ERROR_INVALID_SUBCLASS - if this class is not an
+ * allowed subclass</li>
+ * </ul>
+ *
+ * @see SWT#SINGLE
+ * @see SWT#MULTI
+ * @see SWT#READ_ONLY
+ * @see SWT#WRAP
+ * @see SWT#LEFT
+ * @see SWT#RIGHT
+ * @see SWT#CENTER
+ * @see SWT#PASSWORD
+ * @see SWT#SEARCH
+ * @see SWT#ICON_SEARCH
+ * @see SWT#ICON_CANCEL
+ * @see Widget#checkSubclass
+ * @see Widget#getStyle
+ */
+ public TextAssist(final Composite parent, final int style, final TextAssistContentProvider contentProvider) {
+ super(parent, style);
+ this.contentProvider = contentProvider;
+ this.contentProvider.setTextAssist(this);
+
+ this.setLayout(new FillLayout());
+ this.numberOfLines = 10;
+ this.text = new Text(this, style);
+ this.popup = new Shell(this.getDisplay(), SWT.ON_TOP);
+ this.popup.setLayout(new FillLayout());
+ this.table = new Table(this.popup, SWT.SINGLE);
+
+ this.text.addListener(SWT.KeyDown, createKeyDownListener());
+ this.text.addListener(SWT.Modify, createModifyListener());
+ this.text.addListener(SWT.FocusOut, createFocusOutListener());
+
+ this.table.addListener(SWT.DefaultSelection, new Listener() {
+ @Override
+ public void handleEvent(final Event event) {
+ TextAssist.this.text.setText(TextAssist.this.table.getSelection()[0].getText());
+ TextAssist.this.popup.setVisible(false);
+ }
+ });
+ this.table.addListener(SWT.KeyDown, new Listener() {
+ @Override
+ public void handleEvent(final Event event) {
+ if (event.keyCode == SWT.ESC) {
+ TextAssist.this.popup.setVisible(false);
+ }
+ }
+ });
+
+ this.table.addListener(SWT.FocusOut, createFocusOutListener());
+
+ getShell().addListener(SWT.Move, new Listener() {
+ @Override
+ public void handleEvent(final Event event) {
+ TextAssist.this.popup.setVisible(false);
+ }
+ });
+ }
+
+ /**
+ * @return a listener for the keydown event
+ */
+ private Listener createKeyDownListener() {
+ return new Listener() {
+ @Override
+ public void handleEvent(final Event event) {
+ switch (event.keyCode) {
+ case SWT.ARROW_DOWN:
+ int index = (TextAssist.this.table.getSelectionIndex() + 1) % TextAssist.this.table.getItemCount();
+ TextAssist.this.table.setSelection(index);
+ event.doit = false;
+ break;
+ case SWT.ARROW_UP:
+ index = TextAssist.this.table.getSelectionIndex() - 1;
+ if (index < 0) {
+ index = TextAssist.this.table.getItemCount() - 1;
+ }
+ TextAssist.this.table.setSelection(index);
+ event.doit = false;
+ break;
+ case SWT.CR:
+ if (TextAssist.this.popup.isVisible() && TextAssist.this.table.getSelectionIndex() != -1) {
+ TextAssist.this.text.setText(TextAssist.this.table.getSelection()[0].getText());
+ TextAssist.this.popup.setVisible(false);
+ }
+ break;
+ case SWT.ESC:
+ TextAssist.this.popup.setVisible(false);
+ break;
+
+ default:
+ break;
+ }
+ }
+ };
+ }
+
+ /**
+ * @return a listener for the modify event
+ */
+ private Listener createModifyListener() {
+ return new Listener() {
+ @Override
+ public void handleEvent(final Event event) {
+ final String string = TextAssist.this.text.getText();
+ if (string.length() == 0) {
+ TextAssist.this.popup.setVisible(false);
+ return;
+ }
+
+ List<String> values = TextAssist.this.contentProvider.getContent(string);
+ if (values == null || values.isEmpty()) {
+ TextAssist.this.popup.setVisible(false);
+ return;
+ }
+
+ if (values.size() > TextAssist.this.numberOfLines) {
+ values = values.subList(0, TextAssist.this.numberOfLines);
+ }
+
+ TextAssist.this.table.removeAll();
+ final int numberOfRows = Math.min(values.size(), TextAssist.this.numberOfLines);
+ for (int i = 0; i < numberOfRows; i++) {
+ final TableItem tableItem = new TableItem(TextAssist.this.table, SWT.NONE);
+ tableItem.setText(values.get(i));
+ }
+
+ final Point point = TextAssist.this.text.toDisplay(TextAssist.this.text.getLocation().x, TextAssist.this.text.getSize().y + TextAssist.this.text.getBorderWidth() - 3);
+ int x = point.x;
+ int y = point.y;
+
+ final Rectangle displayRect = getMonitor().getClientArea();
+ final Rectangle parentRect = getDisplay().map(getParent(), null, getBounds());
+ TextAssist.this.popup.pack();
+ final int width = TextAssist.this.popup.getBounds().width;
+ final int height = TextAssist.this.popup.getBounds().height;
+
+ if (y + height > displayRect.y + displayRect.height) {
+ y = parentRect.y - height;
+ }
+ if (x + width > displayRect.x + displayRect.width) {
+ x = displayRect.x + displayRect.width - width;
+ }
+
+ TextAssist.this.popup.setLocation(x, y);
+ TextAssist.this.popup.setVisible(true);
+
+ }
+ };
+ }
+
+ /**
+ * @return a listener for the FocusOut event
+ */
+ private Listener createFocusOutListener() {
+ return new Listener() {
+ @Override
+ public void handleEvent(final Event event) {
+ /* async is needed to wait until focus reaches its new Control */
+ TextAssist.this.getDisplay().asyncExec(new Runnable() {
+ @Override
+ public void run() {
+ if (TextAssist.this.getDisplay().isDisposed()) {
+ return;
+ }
+ final Control control = TextAssist.this.getDisplay().getFocusControl();
+ if (control == null || control != TextAssist.this.text && control != TextAssist.this.table) {
+ TextAssist.this.popup.setVisible(false);
+ }
+ }
+ });
+ }
+ };
+ }
+
+ /**
+ * @return the contentProvider
+ */
+ public TextAssistContentProvider getContentProvider() {
+ checkWidget();
+ return this.contentProvider;
+ }
+
+ /**
+ * @param contentProvider the contentProvider to set
+ */
+ public void setContentProvider(final TextAssistContentProvider contentProvider) {
+ checkWidget();
+ this.contentProvider = contentProvider;
+ }
+
+ /**
+ * @return the numberOfLines
+ */
+ public int getNumberOfLines() {
+ checkWidget();
+ return this.numberOfLines;
+ }
+
+ /**
+ * @param numberOfLines the numberOfLines to set
+ */
+ public void setNumberOfLines(final int numberOfLines) {
+ checkWidget();
+ this.numberOfLines = numberOfLines;
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Text#addModifyListener(org.eclipse.swt.events.ModifyListener)
+ */
+ public void addModifyListener(final ModifyListener listener) {
+ checkWidget();
+ this.text.addModifyListener(listener);
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Text#addSelectionListener(org.eclipse.swt.events.SelectionListener)
+ */
+ public void addSelectionListener(final SelectionListener listener) {
+ checkWidget();
+ this.text.addSelectionListener(listener);
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Text#addVerifyListener(org.eclipse.swt.events.VerifyListener)
+ */
+ public void addVerifyListener(final VerifyListener listener) {
+ checkWidget();
+ this.text.addVerifyListener(listener);
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Text#append(java.lang.String)
+ */
+ public void append(final String string) {
+ checkWidget();
+ this.text.append(string);
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Text#clearSelection()
+ */
+ public void clearSelection() {
+ checkWidget();
+ this.text.clearSelection();
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Text#computeSize(int, int, boolean)
+ */
+ @Override
+ public Point computeSize(final int wHint, final int hHint, final boolean changed) {
+ checkWidget();
+ return this.text.computeSize(wHint, hHint, changed);
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Text#computeTrim(int, int, int, int)
+ */
+ @Override
+ public Rectangle computeTrim(final int x, final int y, final int width, final int height) {
+ checkWidget();
+ return super.computeTrim(x, y, width, height);
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Text#copy()
+ */
+ public void copy() {
+ checkWidget();
+ this.text.copy();
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Text#cut()
+ */
+ public void cut() {
+ checkWidget();
+ this.text.cut();
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Text#getCaretLineNumber()
+ */
+ public int getCaretLineNumber() {
+ checkWidget();
+ return this.text.getCaretLineNumber();
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Text#getCaretLocation()
+ */
+ public Point getCaretLocation() {
+ checkWidget();
+ return this.text.getCaretLocation();
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Text#getCaretPosition()
+ */
+ public int getCaretPosition() {
+ checkWidget();
+ return this.text.getCaretPosition();
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Text#getCharCount()
+ */
+ public int getCharCount() {
+ checkWidget();
+ return this.text.getCharCount();
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Text#getDoubleClickEnabled()
+ */
+ public boolean getDoubleClickEnabled() {
+ checkWidget();
+ return this.text.getDoubleClickEnabled();
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Text#getEchoChar()
+ */
+ public char getEchoChar() {
+ checkWidget();
+ return this.text.getEchoChar();
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Text#getEditable()
+ */
+ public boolean getEditable() {
+ checkWidget();
+ return this.text.getEditable();
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Text#getLineCount()
+ */
+ public int getLineCount() {
+ checkWidget();
+ return this.text.getLineCount();
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Text#getLineDelimiter()
+ */
+ public String getLineDelimiter() {
+ checkWidget();
+ return this.text.getLineDelimiter();
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Text#getLineHeight()
+ */
+ public int getLineHeight() {
+ checkWidget();
+ return this.text.getLineHeight();
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Text#getMessage()
+ */
+ public String getMessage() {
+ checkWidget();
+ return this.text.getMessage();
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Text#getOrientation()
+ */
+ public int getOrientation() {
+ checkWidget();
+ return this.text.getOrientation();
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Text#getSelection()
+ */
+ public Point getSelection() {
+ checkWidget();
+ return this.text.getSelection();
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Text#getSelectionCount()
+ */
+ public int getSelectionCount() {
+ checkWidget();
+ return this.text.getSelectionCount();
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Text#getSelectionText()
+ */
+ public String getSelectionText() {
+ checkWidget();
+ return this.text.getSelectionText();
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Text#getTabs()
+ */
+ public int getTabs() {
+ checkWidget();
+ return this.text.getTabs();
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Text#getText()
+ */
+ public String getText() {
+ checkWidget();
+ return this.text.getText();
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Text#getText(int, int)
+ */
+ public String getText(final int start, final int end) {
+ checkWidget();
+ return this.text.getText(start, end);
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Text#getTextLimit()
+ */
+ public int getTextLimit() {
+ checkWidget();
+ return this.text.getTextLimit();
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Text#getTopIndex()
+ */
+ public int getTopIndex() {
+ checkWidget();
+ return this.text.getTopIndex();
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Text#getTopPixel()
+ */
+ public int getTopPixel() {
+ checkWidget();
+ return this.text.getTopPixel();
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Text#insert(java.lang.String)
+ */
+ public void insert(final String string) {
+ checkWidget();
+ this.text.insert(string);
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Text#paste()
+ */
+ public void paste() {
+ checkWidget();
+ this.text.paste();
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Text#removeModifyListener(org.eclipse.swt.events.ModifyListener)
+ */
+ public void removeModifyListener(final ModifyListener listener) {
+ checkWidget();
+ this.text.removeModifyListener(listener);
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Text#removeSelectionListener(org.eclipse.swt.events.SelectionListener)
+ */
+ public void removeSelectionListener(final SelectionListener listener) {
+ checkWidget();
+ this.text.removeSelectionListener(listener);
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Text#removeVerifyListener(org.eclipse.swt.events.VerifyListener)
+ */
+ public void removeVerifyListener(final VerifyListener listener) {
+ checkWidget();
+ this.text.removeVerifyListener(listener);
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Text#selectAll()
+ */
+ public void selectAll() {
+ checkWidget();
+ this.text.selectAll();
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Text#setDoubleClickEnabled(boolean)
+ */
+ public void setDoubleClickEnabled(final boolean doubleClick) {
+ checkWidget();
+ this.text.setDoubleClickEnabled(doubleClick);
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Text#setEchoChar(char)
+ */
+ public void setEchoChar(final char echo) {
+ checkWidget();
+ this.text.setEchoChar(echo);
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Text#setEditable(boolean)
+ */
+ public void setEditable(final boolean editable) {
+ checkWidget();
+ this.text.setEditable(editable);
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Text#setFont(org.eclipse.swt.graphics.Font)
+ */
+ @Override
+ public void setFont(final Font font) {
+ checkWidget();
+ this.text.setFont(font);
+ this.table.setFont(font);
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Text#setMessage(java.lang.String)
+ */
+ public void setMessage(final String string) {
+ checkWidget();
+ this.text.setMessage(string);
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Text#setOrientation(int)
+ */
+ public void setOrientation(final int orientation) {
+ checkWidget();
+ this.text.setOrientation(orientation);
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Text#setRedraw(boolean)
+ */
+ @Override
+ public void setRedraw(final boolean redraw) {
+ checkWidget();
+ this.text.setRedraw(redraw);
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Text#setSelection(int, int)
+ */
+ public void setSelection(final int start, final int end) {
+ checkWidget();
+ this.text.setSelection(start, end);
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Text#setSelection(int)
+ */
+ public void setSelection(final int start) {
+ checkWidget();
+ this.text.setSelection(start);
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Text#setSelection(org.eclipse.swt.graphics.Point)
+ */
+ public void setSelection(final Point selection) {
+ checkWidget();
+ this.text.setSelection(selection);
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Text#setTabs(int)
+ */
+ public void setTabs(final int tabs) {
+ checkWidget();
+ this.text.setTabs(tabs);
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Text#setText(java.lang.String)
+ */
+ public void setText(final String text) {
+ checkWidget();
+ this.text.setText(text);
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Text#setTextLimit(int)
+ */
+ public void setTextLimit(final int textLimit) {
+ checkWidget();
+ this.text.setTextLimit(textLimit);
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Text#setTopIndex(int)
+ */
+ public void setTopIndex(final int topIndex) {
+ checkWidget();
+ this.text.setTopIndex(topIndex);
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Text#showSelection()
+ */
+ public void showSelection() {
+ checkWidget();
+ this.text.showSelection();
+ }
+
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/textAssist/TextAssistContentProvider.java b/org.tizen.common.externals/src/org/mihalis/opal/textAssist/TextAssistContentProvider.java
new file mode 100644
index 000000000..313fb6803
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/textAssist/TextAssistContentProvider.java
@@ -0,0 +1,46 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON.
+ * 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:
+ * Laurent CARON (laurent.caron@gmail.com) - initial API and implementation
+ *******************************************************************************/
+package org.mihalis.opal.textAssist;
+
+import java.util.List;
+
+/**
+ * This class is a content provider for the TextAssist widget. When the user
+ * types something, an instance returns an arraylist of proposition based on the
+ * typed text.
+ *
+ */
+public abstract class TextAssistContentProvider {
+ private TextAssist textAssist;
+
+ /**
+ * Provides the content
+ *
+ * @param entry text typed by the user
+ * @return an array list of String that contains propositions for the entry
+ * typed by the user
+ */
+ public abstract List<String> getContent(final String entry);
+
+ /**
+ * @param textAssist the textAssist to set
+ */
+ protected void setTextAssist(final TextAssist textAssist) {
+ this.textAssist = textAssist;
+ }
+
+ /**
+ * @return the max number of propositions.
+ */
+ protected int getMaxNumberOfLines() {
+ return this.textAssist.getNumberOfLines();
+ }
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/tipOfTheDay/TipOfTheDay.java b/org.tizen.common.externals/src/org/mihalis/opal/tipOfTheDay/TipOfTheDay.java
new file mode 100755
index 000000000..4ec53c7c7
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/tipOfTheDay/TipOfTheDay.java
@@ -0,0 +1,524 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON
+ * 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:
+ * Laurent CARON (laurent.caron at gmail dot com) - initial API and implementation
+ *******************************************************************************/
+package org.mihalis.opal.tipOfTheDay;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Random;
+
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.browser.Browser;
+import org.eclipse.swt.events.SelectionAdapter;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.graphics.Font;
+import org.eclipse.swt.graphics.FontData;
+import org.eclipse.swt.graphics.Image;
+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.Display;
+import org.eclipse.swt.widgets.Event;
+import org.eclipse.swt.widgets.Group;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Listener;
+import org.eclipse.swt.widgets.Shell;
+import org.mihalis.opal.header.Header;
+import org.mihalis.opal.utils.ResourceManager;
+import org.mihalis.opal.utils.SWTGraphicUtil;
+
+/**
+ * Instances of this class are a "Tip of Day" box, which is composed of
+ * <p>
+ * <dl>
+ * <dt><b>A tip</b></dt>
+ * <dt><b>2 buttons to navigate between types</b></dt>
+ * <dt><b>A close button</b></dt>
+ * <dt><b>A checkbox "show tip on startup"</b></dt>
+ * <dd>(optional)</dd>
+ * <dt><b>A checkbox "remember the password"</b></dt>
+ * <dd>(optional)</dd>
+ * </dl>
+ * </p>
+ */
+public class TipOfTheDay {
+
+ /**
+ * Types of opal dialog
+ */
+ public enum TipStyle {
+ TWO_COLUMNS, TWO_COLUMNS_LARGE, HEADER
+ }
+
+ private final List<String> tips;
+ private boolean displayShowOnStartup = true;
+ private boolean showOnStartup = true;
+ private Shell shell;
+ private Button close;
+ private int index;
+ private Browser tipArea;
+ private String fontName;
+ private TipStyle style;
+ private Image image;
+
+ /**
+ * Constructor
+ */
+ public TipOfTheDay() {
+ this.tips = new ArrayList<String>();
+ this.index = -1;
+ final Font temp = Display.getDefault().getSystemFont();
+ final FontData[] fontData = temp.getFontData();
+ if (fontData != null && fontData.length > 0) {
+ this.fontName = fontData[0].getName();
+ } else {
+ this.fontName = "Arial";
+ }
+ this.style = TipStyle.TWO_COLUMNS;
+
+ }
+
+ /**
+ * Open the "tip of the day" box
+ *
+ * @param parent the parent shell
+ */
+ public void open(final Shell parent) {
+ if (this.index == -1) {
+ this.index = new Random().nextInt(this.tips.size());
+ }
+ buildShell(parent);
+ if (this.style == TipStyle.HEADER) {
+ buildHeader();
+ } else {
+ buildLeftColumn();
+ }
+ buildTip();
+ buildButtons();
+ openShell();
+ }
+
+ /**
+ * Build the shell
+ *
+ * @param parent parent shell
+ */
+ private void buildShell(final Shell parent) {
+ this.shell = new Shell(parent, SWT.SYSTEM_MODAL | SWT.TITLE | SWT.BORDER | SWT.CLOSE | SWT.RESIZE);
+ this.shell.setText(ResourceManager.getLabel(ResourceManager.TIP_OF_THE_DAY));
+ this.shell.setLayout(new GridLayout(this.style == TipStyle.HEADER ? 1 : 2, false));
+
+ this.shell.addListener(SWT.Traverse, new Listener() {
+ @Override
+ public void handleEvent(final Event event) {
+ switch (event.detail) {
+ case SWT.TRAVERSE_ESCAPE:
+ TipOfTheDay.this.shell.dispose();
+ event.detail = SWT.TRAVERSE_NONE;
+ event.doit = false;
+ break;
+ default:
+ break;
+ }
+ }
+ });
+ }
+
+ /**
+ * Build the header
+ */
+ private void buildHeader() {
+ final Header header = new Header(this.shell, SWT.NONE);
+ final GridData gd = new GridData(GridData.FILL, GridData.BEGINNING, true, false);
+ gd.heightHint = 80;
+ header.setLayoutData(gd);
+ header.setTitle(ResourceManager.getLabel(ResourceManager.DID_YOU_KNOW));
+ if (this.image == null) {
+ final Image img = SWTGraphicUtil.createImage("images/light2.png");
+ header.setImage(img);
+ this.shell.addListener(SWT.Dispose, new Listener() {
+
+ @Override
+ public void handleEvent(final Event event) {
+ img.dispose();
+
+ }
+ });
+ } else {
+ header.setImage(this.image);
+ }
+ }
+
+ /**
+ * Build the left column
+ */
+ private void buildLeftColumn() {
+ final Composite composite = new Composite(this.shell, SWT.NONE);
+ int numberOfRows = 1;
+ if (this.style == TipStyle.TWO_COLUMNS_LARGE) {
+ numberOfRows = this.displayShowOnStartup ? 5 : 4;
+ }
+
+ final GridData gd = new GridData(GridData.FILL, GridData.BEGINNING, false, true, 1, numberOfRows);
+ composite.setLayoutData(gd);
+ final FillLayout compositeLayout = new FillLayout();
+ compositeLayout.marginWidth = 2;
+ composite.setLayout(compositeLayout);
+ final Label label = new Label(composite, SWT.NONE);
+ if (this.image == null) {
+ final Image img = SWTGraphicUtil.createImage("images/light1.png");
+ label.setImage(img);
+ this.shell.addListener(SWT.Dispose, new Listener() {
+
+ @Override
+ public void handleEvent(final Event event) {
+ img.dispose();
+ }
+ });
+ } else {
+ label.setImage(this.image);
+ }
+ }
+
+ /**
+ * Build the tip area
+ */
+ private void buildTip() {
+ if (this.style == TipStyle.TWO_COLUMNS) {
+ final Group group = new Group(this.shell, SWT.NONE);
+ final GridData gd = new GridData(GridData.FILL, GridData.FILL, true, true);
+ gd.widthHint = 300;
+ gd.heightHint = 120;
+ group.setLayoutData(gd);
+ group.setText(ResourceManager.getLabel(ResourceManager.DID_YOU_KNOW));
+ final FillLayout fillLayout = new FillLayout();
+ fillLayout.marginWidth = 15;
+ group.setLayout(fillLayout);
+
+ this.tipArea = new Browser(group, SWT.BORDER);
+ } else if (this.style == TipStyle.TWO_COLUMNS_LARGE) {
+ final Label title = new Label(this.shell, SWT.NONE);
+ final GridData gd = new GridData(GridData.FILL, GridData.FILL, true, false);
+ gd.verticalIndent = 15;
+ title.setLayoutData(gd);
+ final Font tempFont = SWTGraphicUtil.buildFontFrom(title, SWT.BOLD, 16);
+ title.setText(ResourceManager.getLabel(ResourceManager.TIP_OF_THE_DAY));
+ title.setFont(tempFont);
+ this.shell.addListener(SWT.Dispose, new Listener() {
+
+ @Override
+ public void handleEvent(final Event event) {
+ tempFont.dispose();
+ }
+ });
+ final Label separator = new Label(this.shell, SWT.SEPARATOR | SWT.HORIZONTAL);
+ separator.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, false));
+
+ this.tipArea = new Browser(this.shell, SWT.BORDER);
+ final GridData gdTipArea = new GridData(GridData.FILL, GridData.FILL, true, true);
+ gdTipArea.heightHint = 120;
+ this.tipArea.setLayoutData(gdTipArea);
+
+ } else {
+ this.tipArea = new Browser(this.shell, SWT.BORDER);
+ final GridData gd = new GridData(GridData.FILL, GridData.FILL, true, true);
+ gd.heightHint = 120;
+ this.tipArea.setLayoutData(gd);
+ }
+ fillTipArea();
+
+ }
+
+ /**
+ * Fill the tip area with the selected tip
+ */
+ private void fillTipArea() {
+ this.tipArea.setText("<html><body bgcolor=\"#ffffff\" text=\"#000000\"><p style=\"font-family:" + this.fontName + ";font-size=12px\">" //
+ + this.tips.get(this.index) + "</p></body></html>");
+ }
+
+ /**
+ * Build the button (checkbox, previous tip, next tip, close)
+ */
+ private void buildButtons() {
+ final Composite composite = new Composite(this.shell, SWT.NONE);
+ int numberOfColumns;
+ if (this.style == TipStyle.HEADER) {
+ numberOfColumns = 1;
+ } else if (this.style == TipStyle.TWO_COLUMNS) {
+ numberOfColumns = 2;
+ } else {
+ numberOfColumns = 1;
+ }
+
+ final GridData gd = new GridData(GridData.FILL, GridData.BEGINNING, false, false, numberOfColumns, 1);
+ composite.setLayoutData(gd);
+ final GridLayout gridLayout = new GridLayout();
+ gridLayout.marginWidth = 2;
+ if (this.style == TipStyle.TWO_COLUMNS_LARGE) {
+ composite.setLayout(new GridLayout(3, false));
+ } else {
+ composite.setLayout(new GridLayout(this.displayShowOnStartup ? 4 : 3, false));
+ }
+
+ final GridData gridShowOnStartup, gridPrevious, gridNext, gridClose;
+ if (this.style == TipStyle.TWO_COLUMNS_LARGE) {
+ gridShowOnStartup = new GridData(GridData.BEGINNING, GridData.BEGINNING, true, false, 3, 1);
+
+ gridPrevious = new GridData(GridData.END, GridData.CENTER, true, false);
+ gridPrevious.widthHint = 120;
+
+ gridNext = new GridData(GridData.CENTER, GridData.CENTER, false, false);
+ gridNext.widthHint = 120;
+
+ gridClose = new GridData(GridData.BEGINNING, GridData.CENTER, true, false);
+ gridClose.widthHint = 120;
+
+ } else {
+ gridShowOnStartup = new GridData(GridData.BEGINNING, GridData.CENTER, true, false);
+
+ gridPrevious = new GridData(GridData.END, GridData.CENTER, this.showOnStartup ? false : true, false);
+ gridPrevious.widthHint = 120;
+
+ gridNext = new GridData(GridData.FILL, GridData.CENTER, false, false);
+ gridNext.widthHint = 120;
+
+ gridClose = new GridData(GridData.FILL, GridData.CENTER, false, false);
+ gridClose.widthHint = 120;
+ }
+
+ if (this.displayShowOnStartup) {
+ buildShowOnStartup(composite, gridShowOnStartup);
+ }
+
+ buildPreviousButton(composite, gridPrevious);
+ buildNextButton(composite, gridNext);
+ buildCloseButton(composite, gridClose);
+
+ }
+
+ /**
+ * Build the "show on startup" checkbox
+ *
+ * @param composite parent composite
+ * @param gridData associated grid data
+ */
+ private void buildShowOnStartup(final Composite composite, final GridData gridData) {
+ final Button checkBox = new Button(composite, SWT.CHECK);
+ checkBox.setLayoutData(gridData);
+ checkBox.setText(ResourceManager.getLabel(ResourceManager.SHOW_TIP_AT_STARTUP));
+ checkBox.setSelection(this.showOnStartup);
+ checkBox.addListener(SWT.Selection, new Listener() {
+
+ @Override
+ public void handleEvent(final Event event) {
+ TipOfTheDay.this.showOnStartup = checkBox.getSelection();
+ }
+ });
+
+ }
+
+ /**
+ * Build the "previous tip" button
+ *
+ * @param composite parent composite
+ * @param gridData associated grid data
+ */
+ private void buildPreviousButton(final Composite composite, final GridData gridData) {
+ final Button previous = new Button(composite, SWT.PUSH);
+ previous.setText(ResourceManager.getLabel(ResourceManager.PREVIOUS_TIP));
+ previous.setLayoutData(gridData);
+ previous.addSelectionListener(new SelectionAdapter() {
+
+ /**
+ * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
+ */
+ @Override
+ public void widgetSelected(final SelectionEvent e) {
+ if (TipOfTheDay.this.index == 0) {
+ setIndex(TipOfTheDay.this.tips.size() - 1);
+ } else {
+ setIndex(TipOfTheDay.this.index - 1);
+ }
+ }
+
+ });
+
+ }
+
+ /**
+ * Build the "next tip" button
+ *
+ * @param composite parent composite
+ * @param gridData associated grid data
+ */
+ private void buildNextButton(final Composite composite, final GridData gridData) {
+ final Button next = new Button(composite, SWT.PUSH);
+ next.setText(ResourceManager.getLabel(ResourceManager.NEXT_TIP));
+
+ next.setLayoutData(gridData);
+ next.addSelectionListener(new SelectionAdapter() {
+
+ /**
+ * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
+ */
+ @Override
+ public void widgetSelected(final SelectionEvent e) {
+ if (TipOfTheDay.this.index == TipOfTheDay.this.tips.size() - 1) {
+ setIndex(0);
+ } else {
+ setIndex(TipOfTheDay.this.index + 1);
+ }
+ }
+
+ });
+ }
+
+ /**
+ * Build the "close" button
+ *
+ * @param composite parent composite
+ * @param gridData associated grid data
+ */
+ private void buildCloseButton(final Composite composite, final GridData gridData) {
+ this.close = new Button(composite, SWT.PUSH);
+ this.close.setText(ResourceManager.getLabel(ResourceManager.CLOSE));
+
+ this.close.setLayoutData(gridData);
+ this.close.addSelectionListener(new SelectionAdapter() {
+
+ /**
+ * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
+ */
+ @Override
+ public void widgetSelected(final SelectionEvent e) {
+ TipOfTheDay.this.shell.dispose();
+ }
+
+ });
+
+ }
+
+ /**
+ * Open the shell
+ */
+ private void openShell() {
+ this.shell.setDefaultButton(this.close);
+ this.shell.pack();
+ this.shell.open();
+ SWTGraphicUtil.centerShell(this.shell);
+
+ while (!this.shell.isDisposed()) {
+ if (!this.shell.getDisplay().readAndDispatch()) {
+ this.shell.getDisplay().sleep();
+ }
+ }
+
+ }
+
+ /**
+ * Add a tip
+ *
+ * @param tip tip to add
+ * @return the current object
+ */
+ public TipOfTheDay addTip(final String tip) {
+ this.tips.add(tip);
+ return this;
+ }
+
+ /**
+ * @return the image
+ */
+ public Image getImage() {
+ return this.image;
+ }
+
+ /**
+ * @return the index of the current tip
+ */
+ public int getIndex() {
+ return this.index;
+ }
+
+ /**
+ * @return the style of the window
+ */
+ public TipStyle getStyle() {
+ return this.style;
+ }
+
+ /**
+ * @return all the the tips
+ */
+ public List<String> getTips() {
+ return this.tips;
+ }
+
+ /**
+ * @return if <code>true</code>, the "Show On Startup" checkbox is displayed
+ */
+ public boolean isDisplayShowOnStartup() {
+ return this.displayShowOnStartup;
+ }
+
+ /**
+ * @return the value of the checkbox "Show On Startup"
+ */
+ public boolean isShowOnStartup() {
+ return this.showOnStartup;
+ }
+
+ /**
+ * @param if <code>true</code>, the checkbox "Show on startup" is displayed
+ */
+ public void setDisplayShowOnStartup(final boolean displayShowOnStartup) {
+ this.displayShowOnStartup = displayShowOnStartup;
+ }
+
+ /**
+ * @param index the index of the selected tip. By default, the tip is chosen
+ * randomly
+ */
+ public void setIndex(final int index) {
+ if (index < 0 || index >= this.tips.size() || this.tips.get(index) == null) {
+ throw new IllegalArgumentException("Index should be between 0 and " + (this.tips.size() - 1) + " (entered value:" + index + ")");
+ }
+
+ this.index = index;
+ if (this.tipArea != null && !this.tipArea.isDisposed()) {
+ fillTipArea();
+ }
+ }
+
+ /**
+ * @param image the image to set
+ */
+ public void setImage(final Image image) {
+ this.image = image;
+ }
+
+ /**
+ * @param the value of the checkbox "Show on startup"
+ */
+ public void setShowOnStartup(final boolean showOnStartup) {
+ this.showOnStartup = showOnStartup;
+ }
+
+ /**
+ * @param style the style of the window
+ */
+ public void setStyle(final TipStyle style) {
+ this.style = style;
+ }
+
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/titledSeparator/TitledSeparator.java b/org.tizen.common.externals/src/org/mihalis/opal/titledSeparator/TitledSeparator.java
new file mode 100644
index 000000000..12f708b7f
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/titledSeparator/TitledSeparator.java
@@ -0,0 +1,314 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON.
+ * 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:
+ * Laurent CARON (laurent.caron@gmail.com) - initial API and implementation
+ *******************************************************************************/
+package org.mihalis.opal.titledSeparator;
+
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.SWTException;
+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.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.Layout;
+import org.eclipse.swt.widgets.Listener;
+import org.mihalis.opal.utils.SWTGraphicUtil;
+
+/**
+ * Instances of this class provide a separator with a title and/or an image.
+ * <p>
+ * <dl>
+ * <dt><b>Styles:</b></dt>
+ * <dd>BORDER</dd>
+ * <dt><b>Events:</b></dt>
+ * <dd>(none)</dd>
+ * </dl>
+ * </p>
+ */
+public class TitledSeparator extends Composite {
+
+ private int alignment;
+ private Image image;
+ private String text;
+
+ /**
+ * Constructs a new instance of this class given its parent and a style
+ * value describing its behavior and appearance.
+ * <p>
+ * The style value is either one of the style constants defined in class
+ * <code>SWT</code> which is applicable to instances of this class, or must
+ * be built by <em>bitwise OR</em>'ing together (that is, using the
+ * <code>int</code> "|" operator) two or more of those <code>SWT</code>
+ * style constants. The class description lists the style constants that are
+ * applicable to the class. Style bits are also inherited from superclasses.
+ * </p>
+ *
+ * @param parent a composite control which will be the parent of the new
+ * instance (cannot be null)
+ * @param style the style of control to construct
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the parent is null</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the parent</li>
+ * </ul>
+ *
+ */
+ public TitledSeparator(final Composite parent, final int style) {
+ super(parent, style);
+ this.alignment = SWT.LEFT;
+
+ final Color originalColor = new Color(getDisplay(), 0, 88, 150);
+ setForeground(originalColor);
+
+ final Font originalFont;
+ final FontData[] fontData = getFont().getFontData();
+ if (fontData != null && fontData.length > 0) {
+ final FontData fd = fontData[0];
+ fd.setStyle(SWT.BOLD);
+ originalFont = new Font(getDisplay(), fd);
+ setFont(originalFont);
+ } else {
+ originalFont = null;
+ }
+
+ this.addListener(SWT.Resize, new Listener() {
+ @Override
+ public void handleEvent(final Event event) {
+ redrawComposite();
+ }
+ });
+
+ this.addListener(SWT.Dispose, new Listener() {
+ @Override
+ public void handleEvent(final Event event) {
+ SWTGraphicUtil.dispose(originalColor);
+ SWTGraphicUtil.dispose(originalFont);
+ }
+ });
+
+ }
+
+ /**
+ * Redraw the composite
+ */
+ private void redrawComposite() {
+ // Dispose previous content
+ for (final Control c : this.getChildren()) {
+ c.dispose();
+ }
+
+ int numberOfColumns = 1;
+
+ if (this.text != null) {
+ numberOfColumns++;
+ }
+ if (this.image != null) {
+ numberOfColumns++;
+ }
+
+ if (this.alignment == SWT.CENTER) {
+ numberOfColumns++;
+ }
+
+ super.setLayout(new GridLayout(numberOfColumns, false));
+ createContent();
+ }
+
+ /**
+ * Create the content
+ */
+ private void createContent() {
+ switch (this.alignment) {
+ case SWT.CENTER:
+ createSeparator();
+ createTitle();
+ break;
+ case SWT.LEFT:
+ createTitle();
+ createSeparator();
+ break;
+ default:
+ createSeparator();
+ createTitle();
+ break;
+ }
+
+ }
+
+ /**
+ * Create a separator
+ */
+ private void createSeparator() {
+ final Label separator = new Label(this, SWT.SEPARATOR | SWT.HORIZONTAL);
+ separator.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false));
+ separator.setBackground(getBackground());
+ }
+
+ /**
+ * Create the title
+ */
+ private void createTitle() {
+
+ if (this.image != null) {
+ final Label imageLabel = createLabel();
+ imageLabel.setImage(this.image);
+ }
+
+ if (this.text != null && !this.text.trim().equals("")) {
+ final Label textLabel = createLabel();
+ textLabel.setText(this.text);
+
+ }
+
+ }
+
+ /**
+ * @return a SWT label
+ */
+ private Label createLabel() {
+ final Label label = new Label(this, SWT.NONE);
+ label.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, false, false));
+ label.setFont(getFont());
+ label.setForeground(getForeground());
+ label.setBackground(getBackground());
+ return label;
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Composite#setLayout(org.eclipse.swt.widgets.Layout)
+ */
+ @Override
+ public void setLayout(final Layout layout) {
+ throw new UnsupportedOperationException("Not supported");
+ }
+
+ /**
+ * Returns a value which describes the position of the text or image in the
+ * receiver. The value will be one of <code>LEFT</code>, <code>RIGHT</code>
+ * or <code>CENTER</code>.
+ *
+ * @return the alignment
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+
+ public int getAlignment() {
+ checkWidget();
+ return this.alignment;
+ }
+
+ /**
+ * Returns the receiver's image if it has one, or null if it does not.
+ *
+ * @return the receiver's image
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public Image getImage() {
+ checkWidget();
+ return this.image;
+ }
+
+ /**
+ * Returns the receiver's text.
+ *
+ * @return the receiver's text
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public String getText() {
+ checkWidget();
+ return this.text;
+ }
+
+ /**
+ * Controls how text will be displayed in the receiver. The argument should
+ * be one of <code>LEFT</code>, <code>RIGHT</code> or <code>CENTER</code>.
+ *
+ * @param alignment the new alignment
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void setAlignment(final int alignment) {
+ checkWidget();
+ this.alignment = alignment;
+ }
+
+ /**
+ * Sets the receiver's image to the argument, which may be null indicating
+ * that no image should be displayed.
+ *
+ * @param image the image to display on the receiver (may be null)
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_INVALID_ARGUMENT - if the image has been
+ * disposed</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void setImage(final Image image) {
+ checkWidget();
+ this.image = image;
+ }
+
+ /**
+ * Sets the receiver's text.
+ *
+ * @param string the new text
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the text is null</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void setText(final String text) {
+ checkWidget();
+ this.text = text;
+ }
+
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/transitionComposite/DownUpAppearTransition.java b/org.tizen.common.externals/src/org/mihalis/opal/transitionComposite/DownUpAppearTransition.java
new file mode 100644
index 000000000..56f826540
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/transitionComposite/DownUpAppearTransition.java
@@ -0,0 +1,34 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON.
+ * 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:
+ * Laurent CARON (laurent.caron@gmail.com) - initial API and implementation
+ *******************************************************************************/
+package org.mihalis.opal.transitionComposite;
+
+/**
+ * In this transition, the second control is behind, the first control is
+ * sliding from down to up
+ */
+public class DownUpAppearTransition extends VerticalTransition {
+
+ /**
+ * @see org.mihalis.opal.transitionComposite.VerticalTransition#getCoeff()
+ */
+ @Override
+ protected int getCoeff() {
+ return -1;
+ }
+
+ /**
+ * @see org.mihalis.opal.transitionComposite.VerticalTransition#secondIsBehind()
+ */
+ @Override
+ protected boolean secondIsBehind() {
+ return false;
+ }
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/transitionComposite/DownUpTransition.java b/org.tizen.common.externals/src/org/mihalis/opal/transitionComposite/DownUpTransition.java
new file mode 100644
index 000000000..2844d8210
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/transitionComposite/DownUpTransition.java
@@ -0,0 +1,33 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON.
+ * 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:
+ * Laurent CARON (laurent.caron@gmail.com) - initial API and implementation
+ *******************************************************************************/
+package org.mihalis.opal.transitionComposite;
+
+/**
+ * In this transition, both control are sliding (vertical movement, down to up)
+ */
+public class DownUpTransition extends VerticalTransition {
+
+ /**
+ * @see org.mihalis.opal.transitionComposite.VerticalTransition#getCoeff()
+ */
+ @Override
+ protected int getCoeff() {
+ return -1;
+ }
+
+ /**
+ * @see org.mihalis.opal.transitionComposite.VerticalTransition#secondIsBehind()
+ */
+ @Override
+ protected boolean secondIsBehind() {
+ return true;
+ }
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/transitionComposite/HorizontalTransition.java b/org.tizen.common.externals/src/org/mihalis/opal/transitionComposite/HorizontalTransition.java
new file mode 100644
index 000000000..a68403d6f
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/transitionComposite/HorizontalTransition.java
@@ -0,0 +1,86 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON.
+ * 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:
+ * Laurent CARON (laurent.caron@gmail.com) - initial API and implementation
+ *******************************************************************************/
+package org.mihalis.opal.transitionComposite;
+
+import org.eclipse.swt.widgets.Control;
+
+/**
+ * Instances of this class are horizontal transitions (right>left,
+ * left>right...)
+ */
+public abstract class HorizontalTransition implements Transition {
+
+ /**
+ * @see org.mihalis.opal.transitionComposite.Transition#performTransition(org.eclipse.swt.widgets.Control,
+ * org.eclipse.swt.widgets.Control)
+ */
+ @Override
+ public void performTransition(final Control first, final Control second) {
+ if (first.isDisposed() || second.isDisposed()) {
+ return;
+ }
+
+ final int[] currentPosition = new int[1];
+ currentPosition[0] = 0;
+ final int maxValue = first.getParent().getClientArea().width;
+
+ first.setBounds(0, 0, first.getBounds().width, first.getBounds().height);
+ second.setBounds(0, -1 * second.getBounds().width, second.getBounds().width, second.getBounds().height);
+
+ first.moveAbove(second);
+ second.setVisible(true);
+
+ if (first.isDisposed() || first.getDisplay().isDisposed()) {
+ return;
+ }
+ first.getDisplay().timerExec(0, new Runnable() {
+
+ @Override
+ public void run() {
+
+ if (first.isDisposed() || second.isDisposed()) {
+ return;
+ }
+
+ currentPosition[0] = currentPosition[0] + 10;
+ if (currentPosition[0] > maxValue) {
+ first.setVisible(false);
+ second.setVisible(true);
+ second.setBounds(0, 0, first.getBounds().width, first.getBounds().height);
+ return;
+ }
+
+ first.setBounds(getCoeff() * currentPosition[0], 0, first.getBounds().width, first.getBounds().height);
+
+ if (secondIsBehind()) {
+ second.setBounds(-1 * getCoeff() * (maxValue - currentPosition[0]), 0, second.getBounds().width, second.getBounds().height);
+ }
+
+ if (!first.isDisposed() && !first.getDisplay().isDisposed()) {
+ first.getDisplay().timerExec(10, this);
+ }
+ }
+
+ });
+
+ }
+
+ /**
+ * @return the multiplicator coefficient
+ */
+ protected abstract int getCoeff();
+
+ /**
+ * @return <code>true</code> if the second composite is behind the first
+ * one, <code>false</code> otherwise
+ */
+ protected abstract boolean secondIsBehind();
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/transitionComposite/LeftRightAppearTransition.java b/org.tizen.common.externals/src/org/mihalis/opal/transitionComposite/LeftRightAppearTransition.java
new file mode 100644
index 000000000..55239df39
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/transitionComposite/LeftRightAppearTransition.java
@@ -0,0 +1,35 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON.
+ * 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:
+ * Laurent CARON (laurent.caron@gmail.com) - initial API and implementation
+ *******************************************************************************/
+package org.mihalis.opal.transitionComposite;
+
+/**
+ * In this transition, the second control is behind, the first control is
+ * sliding from left to right
+ */
+public class LeftRightAppearTransition extends HorizontalTransition {
+
+ /**
+ * @see org.mihalis.opal.transitionComposite.HorizontalTransition#getCoeff()
+ */
+ @Override
+ protected int getCoeff() {
+ return 1;
+ }
+
+ /**
+ * @see org.mihalis.opal.transitionComposite.HorizontalTransition#secondIsBehind()
+ */
+ @Override
+ protected boolean secondIsBehind() {
+ return false;
+ }
+
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/transitionComposite/LeftRightTransition.java b/org.tizen.common.externals/src/org/mihalis/opal/transitionComposite/LeftRightTransition.java
new file mode 100644
index 000000000..a7df75243
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/transitionComposite/LeftRightTransition.java
@@ -0,0 +1,35 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON.
+ * 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:
+ * Laurent CARON (laurent.caron@gmail.com) - initial API and implementation
+ *******************************************************************************/
+package org.mihalis.opal.transitionComposite;
+
+/**
+ * In this transition, both control are sliding (vertical movement, left to
+ * right)
+ */
+public class LeftRightTransition extends HorizontalTransition {
+
+ /**
+ * @see org.mihalis.opal.transitionComposite.HorizontalTransition#getCoeff()
+ */
+ @Override
+ protected int getCoeff() {
+ return 1;
+ }
+
+ /**
+ * @see org.mihalis.opal.transitionComposite.HorizontalTransition#secondIsBehind()
+ */
+ @Override
+ protected boolean secondIsBehind() {
+ return true;
+ }
+
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/transitionComposite/NoTransition.java b/org.tizen.common.externals/src/org/mihalis/opal/transitionComposite/NoTransition.java
new file mode 100644
index 000000000..cbdee8eb4
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/transitionComposite/NoTransition.java
@@ -0,0 +1,31 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON.
+ * 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:
+ * Laurent CARON (laurent.caron@gmail.com) - initial API and implementation
+ *******************************************************************************/
+package org.mihalis.opal.transitionComposite;
+
+import org.eclipse.swt.widgets.Control;
+
+/**
+ * This transition is simple, because there is no effect :)
+ *
+ */
+class NoTransition implements Transition {
+
+ /**
+ * @see org.mihalis.opal.transitionComposite.Transition#performTransition(org.eclipse.swt.widgets.Control,
+ * org.eclipse.swt.widgets.Control)
+ */
+ @Override
+ public void performTransition(final Control first, final Control second) {
+ first.setVisible(false);
+ second.setVisible(true);
+ }
+
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/transitionComposite/RightLeftAppearTransition.java b/org.tizen.common.externals/src/org/mihalis/opal/transitionComposite/RightLeftAppearTransition.java
new file mode 100644
index 000000000..94a38bb6f
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/transitionComposite/RightLeftAppearTransition.java
@@ -0,0 +1,35 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON.
+ * 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:
+ * Laurent CARON (laurent.caron@gmail.com) - initial API and implementation
+ *******************************************************************************/
+package org.mihalis.opal.transitionComposite;
+
+/**
+ * In this transition, the second control is behind, the first control is
+ * sliding from right to left
+ */
+public class RightLeftAppearTransition extends HorizontalTransition {
+
+ /**
+ * @see org.mihalis.opal.transitionComposite.HorizontalTransition#getCoeff()
+ */
+ @Override
+ protected int getCoeff() {
+ return -1;
+ }
+
+ /**
+ * @see org.mihalis.opal.transitionComposite.HorizontalTransition#secondIsBehind()
+ */
+ @Override
+ protected boolean secondIsBehind() {
+ return false;
+ }
+
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/transitionComposite/RightLeftTransition.java b/org.tizen.common.externals/src/org/mihalis/opal/transitionComposite/RightLeftTransition.java
new file mode 100644
index 000000000..cf3c80341
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/transitionComposite/RightLeftTransition.java
@@ -0,0 +1,35 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON.
+ * 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:
+ * Laurent CARON (laurent.caron@gmail.com) - initial API and implementation
+ *******************************************************************************/
+package org.mihalis.opal.transitionComposite;
+
+/**
+ * In this transition, both control are sliding (vertical movement, right to
+ * left)
+ */
+public class RightLeftTransition extends HorizontalTransition {
+
+ /**
+ * @see org.mihalis.opal.transitionComposite.HorizontalTransition#getCoeff()
+ */
+ @Override
+ protected int getCoeff() {
+ return -1;
+ }
+
+ /**
+ * @see org.mihalis.opal.transitionComposite.HorizontalTransition#secondIsBehind()
+ */
+ @Override
+ protected boolean secondIsBehind() {
+ return true;
+ }
+
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/transitionComposite/TRANSITIONS.java b/org.tizen.common.externals/src/org/mihalis/opal/transitionComposite/TRANSITIONS.java
new file mode 100644
index 000000000..0a7785621
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/transitionComposite/TRANSITIONS.java
@@ -0,0 +1,18 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON.
+ * 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:
+ * Laurent CARON (laurent.caron@gmail.com) - initial API and implementation
+ *******************************************************************************/
+package org.mihalis.opal.transitionComposite;
+
+/**
+ * This enumeration is a list of transitions
+ */
+public enum TRANSITIONS {
+ LEFT_TO_RIGHT, LEFT_TO_RIGHT_AND_APPEAR, RIGHT_TO_LEFT, RIGHT_TO_LEFT_AND_APPEAR, UP_TO_DOWN, UP_TO_DOWN_AND_APPEAR, DOWN_TO_UP, DOWN_TO_UP_AND_APPEAR, NONE
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/transitionComposite/Transition.java b/org.tizen.common.externals/src/org/mihalis/opal/transitionComposite/Transition.java
new file mode 100644
index 000000000..2921698ec
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/transitionComposite/Transition.java
@@ -0,0 +1,28 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON.
+ * 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:
+ * Laurent CARON (laurent.caron@gmail.com) - initial API and implementation
+ *******************************************************************************/
+package org.mihalis.opal.transitionComposite;
+
+import org.eclipse.swt.widgets.Control;
+
+/**
+ * This interface describes a transition
+ */
+interface Transition {
+
+ /**
+ * Performs a transition between 2 controls of a TransitionComposite
+ *
+ * @param first first control
+ * @param second second control
+ */
+ void performTransition(Control first, Control second);
+
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/transitionComposite/TransitionComposite.java b/org.tizen.common.externals/src/org/mihalis/opal/transitionComposite/TransitionComposite.java
new file mode 100644
index 000000000..93ac865b0
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/transitionComposite/TransitionComposite.java
@@ -0,0 +1,274 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON.
+ * 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:
+ * Laurent CARON (laurent.caron@gmail.com) - initial API and implementation
+ *******************************************************************************/
+package org.mihalis.opal.transitionComposite;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.SWTException;
+import org.eclipse.swt.graphics.Point;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Event;
+import org.eclipse.swt.widgets.Listener;
+
+/**
+ * Instances of this class provide a multi-part composite. You can perform
+ * transitions when you move from one part to another
+ * <p>
+ * <dl>
+ * <dt><b>Styles:</b></dt>
+ * <dd>BORDER</dd>
+ * <dt><b>Events:</b></dt>
+ * <dd>(none)</dd>
+ * </dl>
+ * </p>
+ */
+public class TransitionComposite extends Composite {
+
+ private final List<Control> controls;
+ private int selection = 0;
+ private TRANSITIONS transition = TRANSITIONS.NONE;
+
+ /**
+ * Constructs a new instance of this class given its parent and a style
+ * value describing its behavior and appearance.
+ * <p>
+ * The style value is either one of the style constants defined in class
+ * <code>SWT</code> which is applicable to instances of this class, or must
+ * be built by <em>bitwise OR</em>'ing together (that is, using the
+ * <code>int</code> "|" operator) two or more of those <code>SWT</code>
+ * style constants. The class description lists the style constants that are
+ * applicable to the class. Style bits are also inherited from superclasses.
+ * </p>
+ *
+ * @param parent a composite control which will be the parent of the new
+ * instance (cannot be null)
+ * @param style the style of control to construct
+ *
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the parent is null</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the parent</li>
+ * </ul>
+ *
+ */
+ public TransitionComposite(final Composite parent, final int style) {
+ super(parent, style);
+ this.controls = new ArrayList<Control>();
+
+ addListener(SWT.Resize, new Listener() {
+ @Override
+ public void handleEvent(final Event e) {
+ TransitionComposite.this.controls.get(TransitionComposite.this.selection).setBounds(getClientArea());
+ }
+ });
+ }
+
+ /**
+ * Add a control to this composite
+ *
+ * @param control control to add
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void addControl(final Control control) {
+ checkWidget();
+ this.controls.add(control);
+ if (this.controls.size() == 1) {
+ control.setVisible(true);
+ } else {
+ control.setVisible(false);
+ }
+ }
+
+ /**
+ * @see org.eclipse.swt.widgets.Composite#computeSize(int, int, boolean)
+ */
+ @Override
+ public Point computeSize(final int wHint, final int hHint, final boolean changed) {
+ int width = 0, height = 0;
+ for (final Control control : this.controls) {
+ final Point point = control.computeSize(wHint, hHint, changed);
+ width = Math.max(width, point.x);
+ height = Math.max(height, point.y);
+ }
+ return new Point(Math.max(width, wHint), Math.max(height, hHint));
+ }
+
+ /**
+ * @return the current transition
+ * @exception IllegalArgumentException <ul>
+ * <li>ERROR_NULL_ARGUMENT - if the listener is null</li>
+ * </ul>
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public TRANSITIONS getTransition() {
+ checkWidget();
+ return this.transition;
+ }
+
+ /**
+ * Move selection to the first control
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void moveToFirst() {
+ checkWidget();
+ changeSelectionTo(0);
+ }
+
+ /**
+ * Move selection to the last control
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void moveToLast() {
+ checkWidget();
+ changeSelectionTo(this.controls.size() - 1);
+ }
+
+ /**
+ * Move selection to the next control
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void moveToNext() {
+ checkWidget();
+ final int index = this.selection + 1;
+ if (index == this.controls.size()) {
+ return;
+ }
+ changeSelectionTo(index);
+ }
+
+ /**
+ * Move selection to the previous control
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void moveToPrevious() {
+ checkWidget();
+ final int index = this.selection - 1;
+ if (index < 0) {
+ return;
+ }
+ changeSelectionTo(index);
+ }
+
+ /**
+ * Move selection to a given index
+ *
+ * @param index index of the new selection
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void setSelection(final int index) {
+ checkWidget();
+ if (index < 0 || index > this.controls.size() - 1) {
+ return;
+ }
+ changeSelectionTo(index);
+ }
+
+ /**
+ * Change current selection
+ *
+ * @param index index of the new selection
+ */
+ private void changeSelectionTo(final int index) {
+
+ final Transition t = TransitionFactory.getTransitionFor(this.transition);
+ t.performTransition(this.controls.get(this.selection), this.controls.get(index));
+
+ this.selection = index;
+ this.controls.get(this.selection).setBounds(getClientArea());
+ }
+
+ /**
+ * Move selection to a given control
+ *
+ * @param control control newly selected
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+ public void setSelection(final Control control) {
+ checkWidget();
+ for (int i = 0; i < this.controls.size(); i++) {
+ if (this.controls.get(i) != null && this.controls.get(i).equals(control)) {
+ changeSelectionTo(i);
+ return;
+ }
+ }
+ }
+
+ /**
+ * Move selection to the first control
+ *
+ * @param transition new transition
+ *
+ * @exception SWTException <ul>
+ * <li>ERROR_WIDGET_DISPOSED - if the receiver has been
+ * disposed</li>
+ * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
+ * thread that created the receiver</li>
+ * </ul>
+ */
+
+ public void setTransition(final TRANSITIONS transition) {
+ checkWidget();
+ this.transition = transition;
+ }
+
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/transitionComposite/TransitionFactory.java b/org.tizen.common.externals/src/org/mihalis/opal/transitionComposite/TransitionFactory.java
new file mode 100755
index 000000000..ef73b8b49
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/transitionComposite/TransitionFactory.java
@@ -0,0 +1,48 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON.
+ * 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:
+ * Laurent CARON (laurent.caron@gmail.com) - initial API and implementation
+ *******************************************************************************/
+package org.mihalis.opal.transitionComposite;
+
+/**
+ * This class is a transition factory
+ */
+public class TransitionFactory {
+
+ /**
+ * @param transition transition to get
+ * @return a transition corresponding to the <code>transition</code>
+ * parameter
+ */
+ public static Transition getTransitionFor(final TRANSITIONS transition) {
+ switch (transition) {
+ case DOWN_TO_UP:
+ return new DownUpTransition();
+ case DOWN_TO_UP_AND_APPEAR:
+ return new DownUpAppearTransition();
+ case LEFT_TO_RIGHT:
+ return new LeftRightTransition();
+ case LEFT_TO_RIGHT_AND_APPEAR:
+ return new LeftRightAppearTransition();
+ case NONE:
+ return new NoTransition();
+ case RIGHT_TO_LEFT:
+ return new RightLeftTransition();
+ case RIGHT_TO_LEFT_AND_APPEAR:
+ return new RightLeftAppearTransition();
+ case UP_TO_DOWN:
+ return new UpDownTransition();
+ case UP_TO_DOWN_AND_APPEAR:
+ return new UpDownAppearTransition();
+ default:
+ return null;
+ }
+ }
+
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/transitionComposite/UpDownAppearTransition.java b/org.tizen.common.externals/src/org/mihalis/opal/transitionComposite/UpDownAppearTransition.java
new file mode 100644
index 000000000..b849657d3
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/transitionComposite/UpDownAppearTransition.java
@@ -0,0 +1,34 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON.
+ * 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:
+ * Laurent CARON (laurent.caron@gmail.com) - initial API and implementation
+ *******************************************************************************/
+package org.mihalis.opal.transitionComposite;
+
+/**
+ * In this transition, the second control is behind, the first control is
+ * sliding from up to down
+ */
+public class UpDownAppearTransition extends VerticalTransition {
+
+ /**
+ * @see org.mihalis.opal.transitionComposite.VerticalTransition#getCoeff()
+ */
+ @Override
+ protected int getCoeff() {
+ return 1;
+ }
+
+ /**
+ * @see org.mihalis.opal.transitionComposite.VerticalTransition#secondIsBehind()
+ */
+ @Override
+ protected boolean secondIsBehind() {
+ return false;
+ }
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/transitionComposite/UpDownTransition.java b/org.tizen.common.externals/src/org/mihalis/opal/transitionComposite/UpDownTransition.java
new file mode 100644
index 000000000..e352a59bf
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/transitionComposite/UpDownTransition.java
@@ -0,0 +1,27 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON.
+ * 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:
+ * Laurent CARON (laurent.caron@gmail.com) - initial API and implementation
+ *******************************************************************************/
+package org.mihalis.opal.transitionComposite;
+
+/**
+ * In this transition, both control are sliding (vertical movement, up to down)
+ */
+public class UpDownTransition extends VerticalTransition {
+
+ @Override
+ protected int getCoeff() {
+ return 1;
+ }
+
+ @Override
+ protected boolean secondIsBehind() {
+ return true;
+ }
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/transitionComposite/VerticalTransition.java b/org.tizen.common.externals/src/org/mihalis/opal/transitionComposite/VerticalTransition.java
new file mode 100644
index 000000000..ffe09424c
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/transitionComposite/VerticalTransition.java
@@ -0,0 +1,84 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON.
+ * 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:
+ * Laurent CARON (laurent.caron@gmail.com) - initial API and implementation
+ *******************************************************************************/
+package org.mihalis.opal.transitionComposite;
+
+import org.eclipse.swt.widgets.Control;
+
+/**
+ * Instances of this class are vertical transitions (down>up, up>down...)
+ */
+abstract class VerticalTransition implements Transition {
+
+ /**
+ * @see org.mihalis.opal.transitionComposite.Transition#performTransition(org.eclipse.swt.widgets.Control,
+ * org.eclipse.swt.widgets.Control)
+ */
+ @Override
+ public void performTransition(final Control first, final Control second) {
+ if (first.isDisposed() || second.isDisposed()) {
+ return;
+ }
+
+ final int[] currentPosition = new int[1];
+ currentPosition[0] = 0;
+ final int maxValue = first.getParent().getClientArea().height;
+
+ first.setBounds(0, 0, first.getBounds().width, first.getBounds().height);
+ second.setBounds(0, -1 * second.getBounds().width, second.getBounds().width, second.getBounds().height);
+
+ first.moveAbove(second);
+ second.setVisible(true);
+
+ if (first.isDisposed() || first.getDisplay().isDisposed()) {
+ return;
+ }
+
+ first.getDisplay().timerExec(0, new Runnable() {
+
+ @Override
+ public void run() {
+
+ if (first.isDisposed() || second.isDisposed()) {
+ return;
+ }
+
+ currentPosition[0] = currentPosition[0] + 10;
+ if (currentPosition[0] > maxValue) {
+ first.setVisible(false);
+ second.setBounds(0, 0, first.getBounds().width, first.getBounds().height);
+
+ return;
+ }
+
+ first.setBounds(0, getCoeff() * currentPosition[0], first.getBounds().width, first.getBounds().height);
+ if (secondIsBehind()) {
+ second.setBounds(0, -1 * getCoeff() * (maxValue - currentPosition[0]), second.getBounds().width, second.getBounds().height);
+ }
+ if (!first.isDisposed() && !first.getDisplay().isDisposed()) {
+ first.getDisplay().timerExec(15, this);
+ }
+ }
+
+ });
+
+ }
+
+ /**
+ * @return the multiplicator coefficient
+ */
+ protected abstract int getCoeff();
+
+ /**
+ * @return <code>true</code> if the second composite is behind the first
+ * one, <code>false</code> otherwise
+ */
+ protected abstract boolean secondIsBehind();
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/utils/FileToolbox.java b/org.tizen.common.externals/src/org/mihalis/opal/utils/FileToolbox.java
new file mode 100644
index 000000000..7201ffc28
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/utils/FileToolbox.java
@@ -0,0 +1,47 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON
+ * 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:
+ * Laurent CARON (laurent.caron at gmail dot com) - initial API and implementation
+ *******************************************************************************/
+package org.mihalis.opal.utils;
+
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.MalformedURLException;
+import java.net.URL;
+
+public class FileToolbox {
+
+ /**
+ * Loads a file into a stream
+ *
+ * @param fileName file name
+ * @return a stream composed of this file
+ */
+ public static InputStream getInputStream(final String fileName) {
+ if (fileName.startsWith("jar:")) {
+ URL url;
+ try {
+ url = new URL(fileName);
+ return url.openStream();
+ } catch (final MalformedURLException e) {
+ throw new RuntimeException(e);
+ } catch (final IOException e) {
+ throw new RuntimeException(e);
+ }
+ } else {
+ try {
+ return new FileInputStream(fileName);
+ } catch (final FileNotFoundException e) {
+ throw new RuntimeException(e);
+ }
+ }
+ }
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/utils/HTMLStyledTextParser.java b/org.tizen.common.externals/src/org/mihalis/opal/utils/HTMLStyledTextParser.java
new file mode 100644
index 000000000..d92804794
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/utils/HTMLStyledTextParser.java
@@ -0,0 +1,179 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON
+ * 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:
+ * Laurent CARON (laurent.caron at gmail dot com) - Initial implementation and API
+ *******************************************************************************/
+package org.mihalis.opal.utils;
+
+import java.io.IOException;
+import java.io.StringReader;
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.swing.text.MutableAttributeSet;
+import javax.swing.text.html.HTML.Tag;
+import javax.swing.text.html.HTMLEditorKit;
+import javax.swing.text.html.HTMLEditorKit.ParserCallback;
+import javax.swing.text.html.parser.ParserDelegator;
+
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.custom.StyleRange;
+import org.eclipse.swt.custom.StyledText;
+
+/**
+ * Instances of this class are used to convert HTML content of a styled text
+ * into style ranges
+ */
+public class HTMLStyledTextParser extends ParserCallback {
+
+ private final List<StyleRange> listOfStyles;
+ private final StyledText styledText;
+ private int position;
+ private final StringBuilder outputString;
+
+ private StyleRange currentStyleRange;
+ private TagType currentTagType;
+ private int currentPosition;
+
+ private enum TagType {
+ B, U, I
+ };
+
+ /**
+ * Constructor
+ *
+ * @param styledText styled text to analyze
+ */
+ HTMLStyledTextParser(final StyledText styledText) {
+ super();
+ this.styledText = styledText;
+ this.position = -1;
+ this.listOfStyles = new ArrayList<StyleRange>();
+ this.currentStyleRange = null;
+ this.currentTagType = null;
+ this.currentPosition = 0;
+ this.outputString = new StringBuilder();
+ }
+
+ /**
+ * @see javax.swing.text.html.HTMLEditorKit.ParserCallback#handleStartTag(javax.swing.text.html.HTML.Tag,
+ * javax.swing.text.MutableAttributeSet, int)
+ */
+ @Override
+ public void handleStartTag(final Tag t, final MutableAttributeSet a, final int pos) {
+ if (t == Tag.B) {
+ this.currentStyleRange = new StyleRange();
+ this.currentTagType = TagType.B;
+ this.currentPosition = this.position;
+ }
+ if (t == Tag.I) {
+ this.currentStyleRange = new StyleRange();
+ this.currentTagType = TagType.I;
+ this.currentPosition = this.position;
+ }
+ if (t == Tag.U) {
+ this.currentStyleRange = new StyleRange();
+ this.currentTagType = TagType.U;
+ this.currentPosition = this.position;
+ }
+
+ }
+
+ /**
+ * @see javax.swing.text.html.HTMLEditorKit.ParserCallback#handleEndTag(javax.swing.text.html.HTML.Tag,
+ * int)
+ */
+ @Override
+ public void handleEndTag(final Tag t, final int pos) {
+
+ if (t != Tag.B && t != Tag.I && t != Tag.U) {
+ return;
+ }
+
+ int style;
+ boolean underline;
+ if (t == Tag.B) {
+ if (TagType.B != this.currentTagType) {
+ throw new RuntimeException("Error parsing [" + this.styledText.getText() + "] : bad syntax");
+ }
+ style = SWT.BOLD;
+ underline = false;
+ } else if (t == Tag.I) {
+ if (TagType.I != this.currentTagType) {
+ throw new RuntimeException("Error parsing [" + this.styledText.getText() + "] : bad syntax");
+ }
+ style = SWT.ITALIC;
+ underline = false;
+ } else if (t == Tag.U) {
+ if (TagType.U != this.currentTagType) {
+ throw new RuntimeException("Error parsing [" + this.styledText.getText() + "] : bad syntax");
+ }
+ style = SWT.NORMAL;
+ underline = true;
+ } else {
+ style = SWT.NORMAL;
+ underline = false;
+ }
+
+ this.currentStyleRange.start = this.currentPosition;
+ this.currentStyleRange.length = this.position - this.currentPosition + 1;
+ this.currentStyleRange.fontStyle = style;
+ this.currentStyleRange.underline = underline;
+ this.listOfStyles.add(this.currentStyleRange);
+
+ this.currentStyleRange = null;
+ this.currentTagType = null;
+ }
+
+ /**
+ * @see javax.swing.text.html.HTMLEditorKit.ParserCallback#handleError(java.lang.String,
+ * int)
+ */
+ @Override
+ public void handleError(final String errorMsg, final int pos) {
+ throw new RuntimeException("Parsing error: " + errorMsg + " at " + pos);
+ }
+
+ /**
+ * @see javax.swing.text.html.HTMLEditorKit.ParserCallback#handleText(char[],
+ * int)
+ */
+ @Override
+ public void handleText(final char[] data, final int pos) {
+ this.outputString.append(data);
+ this.position += data.length;
+ }
+
+ /**
+ * @see javax.swing.text.html.HTMLEditorKit.ParserCallback#handleSimpleTag(javax.swing.text.html.HTML.Tag,
+ * javax.swing.text.MutableAttributeSet, int)
+ */
+ @Override
+ public void handleSimpleTag(final Tag t, final MutableAttributeSet a, final int pos) {
+ if (t == Tag.BR) {
+ this.outputString.append("\n");
+ this.position += t.toString().length();
+
+ }
+ }
+
+ /**
+ * Parse the content, build the list of style ranges and apply them to the
+ * styled text widget
+ *
+ * @throws IOException
+ */
+ public void parse() throws IOException {
+ final HTMLEditorKit.Parser parser = new ParserDelegator();
+ parser.parse(new StringReader(this.styledText.getText()), this, true);
+ this.styledText.setText(this.outputString.toString());
+ this.styledText.setStyleRanges(this.listOfStyles.toArray(new StyleRange[this.listOfStyles.size()]));
+
+ }
+
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/utils/ResourceManager.java b/org.tizen.common.externals/src/org/mihalis/opal/utils/ResourceManager.java
new file mode 100644
index 000000000..da60f64a5
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/utils/ResourceManager.java
@@ -0,0 +1,56 @@
+package org.mihalis.opal.utils;
+
+import java.util.ResourceBundle;
+
+public class ResourceManager {
+ private static final ResourceBundle RSC = ResourceBundle.getBundle("resources/opal");
+
+ public static final String OK = "Ok";
+ public static final String CANCEL = "Cancel";
+ public static final String CLOSE = "Close";
+ public static final String YES = "Yes";
+ public static final String NO = "No";
+
+ public static final String MEGABYTES = "megabytes";
+ public static final String PERFORM_GC = "performGC";
+
+ public static final String LOGIN = "login";
+ public static final String NAME = "name";
+ public static final String PASSWORD = "password";
+ public static final String REMEMBER_PASSWORD = "rememberPassword";
+ public static final String LOGIN_FAILED = "loginFailed";
+
+ public static final String INPUT = "Input";
+ public static final String APPLICATION_ERROR = "ApplicationError";
+ public static final String INFORMATION = "Information";
+ public static final String WARNING = "Warning";
+ public static final String CHOICE = "Choice";
+ public static final String EXCEPTION = "Exception";
+ public static final String SELECT = "Select";
+ public static final String FEWER_DETAILS = "FewerDetails";
+ public static final String MORE_DETAILS = "MoreDetails";
+
+ public static final String TIP_OF_THE_DAY = "tipOfTheDay";
+ public static final String DID_YOU_KNOW = "didYouKnow";
+ public static final String SHOW_TIP_AT_STARTUP = "showTipAtStartup";
+ public static final String PREVIOUS_TIP = "previousTip";
+ public static final String NEXT_TIP = "nextTip";
+
+ public static final String CHOOSE = "choose";
+ public static final String PREFERENCES = "preferences";
+ public static final String VALID_URL = "validURL";
+ public static final String CHOOSE_DIRECTORY = "chooseDirectory";
+ public static final String ITALIC = "italic";
+ public static final String BOLD = "bold";
+
+ /**
+ * Get a translated label
+ *
+ * @param key key to get
+ * @return the translated value of the key
+ */
+ public static String getLabel(final String key) {
+ return RSC.getString(key);
+ }
+
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/utils/SWTGraphicUtil.java b/org.tizen.common.externals/src/org/mihalis/opal/utils/SWTGraphicUtil.java
new file mode 100644
index 000000000..e28dd529b
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/utils/SWTGraphicUtil.java
@@ -0,0 +1,463 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON
+ * 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:
+ * Laurent CARON (laurent.caron at gmail dot com) - Initial implementation and API
+ *******************************************************************************/
+package org.mihalis.opal.utils;
+
+import java.io.IOException;
+import java.util.ArrayList;
+
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.custom.StyledText;
+import org.eclipse.swt.events.DisposeEvent;
+import org.eclipse.swt.events.DisposeListener;
+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.PaletteData;
+import org.eclipse.swt.graphics.RGB;
+import org.eclipse.swt.graphics.Rectangle;
+import org.eclipse.swt.graphics.Resource;
+import org.eclipse.swt.graphics.Transform;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.Monitor;
+import org.eclipse.swt.widgets.Shell;
+
+/**
+ * This class is a singleton that provides useful methods
+ */
+public class SWTGraphicUtil {
+
+ /**
+ * Constructor
+ */
+ private SWTGraphicUtil() {
+ }
+
+ /**
+ * Dispose safely any SWT resource when a control is disposed
+ *
+ * @param r the resource to dispose
+ */
+ public static void dispose(final Control control, final Resource r) {
+ control.addDisposeListener(new DisposeListener() {
+
+ @Override
+ public void widgetDisposed(final DisposeEvent e) {
+ dispose(r);
+ }
+ });
+ }
+
+ /**
+ * Dispose safely any SWT resource
+ *
+ * @param r the resource to dispose
+ */
+ public static void dispose(final Resource r) {
+ if (r != null && !r.isDisposed()) {
+ r.dispose();
+ }
+ }
+
+ /**
+ * Loads an image and create a SWT Image corresponding to this file
+ *
+ * @param fileName file name of the image
+ * @return an image
+ * @see org.eclipse.swt.graphics.Image
+ */
+ public static Image createImage(final String fileName) {
+ return new Image(Display.getCurrent(), SWTGraphicUtil.class.getClassLoader().getResourceAsStream(fileName));
+ }
+
+ /**
+ * Create a reflected image of a source Inspired by Daniel Spiewak
+ * (http://www.eclipsezone.com/eclipse/forums/t91013.html)
+ *
+ * @param source source to be reflected
+ * @return the source image with a reflection
+ */
+ public static Image createReflectedImage(final Image source) {
+ if (source == null) {
+ return null;
+ }
+
+ if (source.isDisposed()) {
+ SWT.error(SWT.ERROR_WIDGET_DISPOSED);
+ }
+
+ // Create a new image
+ final Rectangle sourceBounds = source.getBounds();
+ final Image newImage = new Image(source.getDevice(), new Rectangle(0, 0, sourceBounds.width, (int) (sourceBounds.height * 1.5)));
+ final GC gc = new GC(newImage);
+ gc.setAdvanced(true);
+
+ gc.drawImage(source, 0, 0);
+
+ // Add the reflection
+ final Transform t = new Transform(source.getDevice());
+ t.setElements(1, 0, 0, -.5f, 0, sourceBounds.height + sourceBounds.height / 2);
+ gc.setTransform(t);
+
+ gc.drawImage(source, 0, 0);
+
+ t.dispose();
+ gc.dispose();
+
+ // And add the alpha mask
+ final ImageData imgData = newImage.getImageData();
+ final int width = imgData.width;
+ final int height = imgData.height;
+ final byte[] alphaData = new byte[height * width];
+
+ final byte[] noAlpha = new byte[width];
+ for (int x = 0; x < width; x++) {
+ noAlpha[x] = (byte) 255;
+ }
+
+ for (int y = 0; y < height; y++) {
+ final byte[] alphaRow = new byte[width];
+ if (y < sourceBounds.height) {
+ System.arraycopy(noAlpha, 0, alphaData, y * width, width);
+ } else {
+ for (int x = 0; x < width; x++) {
+ alphaRow[x] = (byte) (255 - 255 * y / height);
+ }
+ System.arraycopy(alphaRow, 0, alphaData, y * width, width);
+ }
+
+ }
+ imgData.alphaData = alphaData;
+ return new Image(source.getDevice(), imgData);
+ }
+
+ /**
+ * Returns a new scaled image.
+ *
+ * @param source the image to be scaled
+ * @param newWidth new width of the image
+ * @param newHeight new height of the image
+ * @return a scaled image of the source
+ */
+ public static Image resize(final Image source, final int newWidth, final int newHeight) {
+
+ if (source == null) {
+ return null;
+ }
+
+ if (source.isDisposed()) {
+ SWT.error(SWT.ERROR_WIDGET_DISPOSED);
+ }
+
+ final Image scaledImage = new Image(source.getDevice(), newWidth, newHeight);
+ final GC gc = new GC(scaledImage);
+ gc.setAntialias(SWT.ON);
+ gc.setInterpolation(SWT.HIGH);
+ gc.drawImage(source, 0, 0, source.getBounds().width, source.getBounds().height, 0, 0, newWidth, newHeight);
+ gc.dispose();
+
+ return scaledImage;
+ }
+
+ /**
+ * Create a reflected and resized version of an image
+ *
+ * @param source source image to be scaled and reflected
+ * @param newWidth new width of the scaled image
+ * @param newHeight new height of the scaled image
+ * @return the resized and reflected image
+ */
+ public static Image createReflectedResizedImage(final Image source, final int newWidth, final int newHeight) {
+ if (source == null) {
+ return null;
+ }
+
+ if (source.isDisposed()) {
+ SWT.error(SWT.ERROR_WIDGET_DISPOSED);
+ }
+
+ final Image newImage = new Image(source.getDevice(), newWidth, (int) (newHeight * 1.5));
+ final GC gc = new GC(newImage);
+ gc.setAntialias(SWT.ON);
+ gc.setInterpolation(SWT.HIGH);
+ gc.drawImage(source, 0, 0, source.getBounds().width, source.getBounds().height, 0, 0, newWidth, newHeight);
+
+ // Add the reflection
+ final Transform t = new Transform(source.getDevice());
+ t.setElements(1, 0, 0, -.5f, 0, (float) (newHeight * 1.5));
+ gc.setTransform(t);
+
+ gc.drawImage(source, 0, 0, source.getBounds().width, source.getBounds().height, 0, 0, newWidth, newHeight);
+
+ t.dispose();
+ gc.dispose();
+
+ // And add the alpha mask
+ final ImageData imgData = newImage.getImageData();
+ final int width = imgData.width;
+ final int height = imgData.height;
+ final byte[] alphaData = new byte[height * width];
+
+ final byte[] noAlpha = new byte[width];
+ for (int x = 0; x < width; x++) {
+ noAlpha[x] = (byte) 255;
+ }
+
+ for (int y = 0; y < height; y++) {
+ final byte[] alphaRow = new byte[width];
+ if (y < newHeight) {
+ System.arraycopy(noAlpha, 0, alphaData, y * width, width);
+ } else {
+ for (int x = 0; x < width; x++) {
+ alphaRow[x] = (byte) (255 - 255 * y / height);
+ }
+ System.arraycopy(alphaRow, 0, alphaData, y * width, width);
+ }
+
+ }
+ imgData.alphaData = alphaData;
+ return new Image(source.getDevice(), imgData);
+
+ }
+
+ /**
+ * Center a shell on the screen
+ *
+ * @param shell shell to center
+ */
+ public static void centerShell(final Shell shell) {
+ final Monitor primary = shell.getDisplay().getPrimaryMonitor();
+ final Rectangle bounds = primary.getBounds();
+ final Rectangle rect = shell.getBounds();
+ final int x = bounds.x + (bounds.width - rect.width) / 2;
+ final int y = bounds.y + (bounds.height - rect.height) / 2;
+ shell.setLocation(x, y);
+ }
+
+ /**
+ * Apply a very basic HTML formating to a text stored in a StyledText
+ * widget. Supported tags are <B>, <I> and <U>
+ *
+ * @param styledText styled text that contains an HTML text
+ */
+ public static void applyHTMLFormating(final StyledText styledText) {
+ try {
+ new HTMLStyledTextParser(styledText).parse();
+ } catch (final IOException e) {
+ e.printStackTrace();
+ }
+ }
+
+ /**
+ * @param originalImageData The ImageData to be average blurred.
+ * Transparency information will be ignored.
+ * @param radius the number of radius pixels to consider when blurring
+ * image.
+ * @return A blurred copy of the image data, or null if an error occured.
+ * @author Nicholas Rajendram
+ * @see http://www.jasonwaltman.com/thesis/filter-blur.html
+ * @see http://www.blackpawn.com/texts/blur/default.html
+ */
+ public static ImageData blur(final ImageData originalImageData, int radius) {
+ /*
+ * This method will vertically blur all the pixels in a row at once.
+ * This blurring is performed incrementally to each row.
+ *
+ * In order to vertically blur any given pixel, maximally (radius * 2 +
+ * 1) pixels must be examined. Since each of these pixels exists in the
+ * same column, they span across a series of consecutive rows. These
+ * rows are horizontally blurred before being cached and used as input
+ * for the vertical blur. Blurring a pixel horizontally and then
+ * vertically is equivalent to blurring the pixel with both its
+ * horizontal and vertical neighbours at once.
+ *
+ * Pixels are blurred under the notion of a 'summing scope'. A certain
+ * scope of pixels in a column are summed then averaged to determine a
+ * target pixel's resulting RGB value. When the next lower target pixel
+ * is being calculated, the topmost pixel is removed from the summing
+ * scope (by subtracting its RGB) and a new pixel is added to the bottom
+ * of the scope (by adding its RGB). In this sense, the summing scope is
+ * moving downward.
+ */
+ if (radius < 1) {
+ return originalImageData;
+ }
+ // prepare new image data with 24-bit direct palette to hold blurred
+ // copy of image
+ final ImageData newImageData = new ImageData(originalImageData.width, originalImageData.height, 24, new PaletteData(0xFF, 0xFF00, 0xFF0000));
+ if (radius >= newImageData.height || radius >= newImageData.width) {
+ radius = Math.min(newImageData.height, newImageData.width) - 1;
+ }
+ // initialize cache
+ final ArrayList<RGB[]> rowCache = new ArrayList<RGB[]>();
+ final int cacheSize = radius * 2 + 1 > newImageData.height ? newImageData.height : radius * 2 + 1; // number
+ // of
+ // rows
+ // of
+ // imageData
+ // we
+ // cache
+ int cacheStartIndex = 0; // which row of imageData the cache begins with
+ for (int row = 0; row < cacheSize; row++) {
+ // row data is horizontally blurred before caching
+ rowCache.add(rowCache.size(), blurRow(originalImageData, row, radius));
+ }
+ // sum red, green, and blue values separately for averaging
+ final RGB[] rowRGBSums = new RGB[newImageData.width];
+ final int[] rowRGBAverages = new int[newImageData.width];
+ int topSumBoundary = 0; // current top row of summed values scope
+ int targetRow = 0; // row with RGB averages to be determined
+ int bottomSumBoundary = 0; // current bottom row of summed values scope
+ int numRows = 0; // number of rows included in current summing scope
+ for (int i = 0; i < newImageData.width; i++) {
+ rowRGBSums[i] = new RGB(0, 0, 0);
+ }
+ while (targetRow < newImageData.height) {
+ if (bottomSumBoundary < newImageData.height) {
+ do {
+ // sum pixel RGB values for each column in our radius scope
+ for (int col = 0; col < newImageData.width; col++) {
+ rowRGBSums[col].red += rowCache.get(bottomSumBoundary - cacheStartIndex)[col].red;
+ rowRGBSums[col].green += rowCache.get(bottomSumBoundary - cacheStartIndex)[col].green;
+ rowRGBSums[col].blue += rowCache.get(bottomSumBoundary - cacheStartIndex)[col].blue;
+ }
+ numRows++;
+ bottomSumBoundary++; // move bottom scope boundary lower
+ if (bottomSumBoundary < newImageData.height && bottomSumBoundary - cacheStartIndex > radius * 2) {
+ // grow cache
+ rowCache.add(rowCache.size(), blurRow(originalImageData, bottomSumBoundary, radius));
+ }
+ } while (bottomSumBoundary <= radius); // to initialize
+ // rowRGBSums at start
+ }
+ if (targetRow - topSumBoundary > radius) {
+ // subtract values of top row from sums as scope of summed
+ // values moves down
+ for (int col = 0; col < newImageData.width; col++) {
+ rowRGBSums[col].red -= rowCache.get(topSumBoundary - cacheStartIndex)[col].red;
+ rowRGBSums[col].green -= rowCache.get(topSumBoundary - cacheStartIndex)[col].green;
+ rowRGBSums[col].blue -= rowCache.get(topSumBoundary - cacheStartIndex)[col].blue;
+ }
+ numRows--;
+ topSumBoundary++; // move top scope boundary lower
+ rowCache.remove(0); // remove top row which is out of summing
+ // scope
+ cacheStartIndex++;
+ }
+ // calculate each column's RGB-averaged pixel
+ for (int col = 0; col < newImageData.width; col++) {
+ rowRGBAverages[col] = newImageData.palette.getPixel(new RGB(rowRGBSums[col].red / numRows, rowRGBSums[col].green / numRows, rowRGBSums[col].blue / numRows));
+ }
+ // replace original pixels
+ newImageData.setPixels(0, targetRow, newImageData.width, rowRGBAverages, 0);
+ targetRow++;
+ }
+ return newImageData;
+ }
+
+ /**
+ * Average blurs a given row of image data. Returns the blurred row as a
+ * matrix of separated RGB values.
+ */
+ private static RGB[] blurRow(final ImageData originalImageData, final int row, final int radius) {
+ final RGB[] rowRGBAverages = new RGB[originalImageData.width]; // resulting
+ // rgb
+ // averages
+ final int[] lineData = new int[originalImageData.width];
+ originalImageData.getPixels(0, row, originalImageData.width, lineData, 0);
+ int r = 0, g = 0, b = 0; // sum red, green, and blue values separately
+ // for averaging
+ int leftSumBoundary = 0; // beginning index of summed values scope
+ int targetColumn = 0; // column of RGB average to be determined
+ int rightSumBoundary = 0; // ending index of summed values scope
+ int numCols = 0; // number of columns included in current summing scope
+ RGB rgb;
+ while (targetColumn < lineData.length) {
+ if (rightSumBoundary < lineData.length) {
+ // sum RGB values for each pixel in our radius scope
+ do {
+ rgb = originalImageData.palette.getRGB(lineData[rightSumBoundary]);
+ r += rgb.red;
+ g += rgb.green;
+ b += rgb.blue;
+ numCols++;
+ rightSumBoundary++;
+ } while (rightSumBoundary <= radius); // to initialize summing
+ // scope at start
+ }
+ // subtract sum of left pixel as summing scope moves right
+ if (targetColumn - leftSumBoundary > radius) {
+ rgb = originalImageData.palette.getRGB(lineData[leftSumBoundary]);
+ r -= rgb.red;
+ g -= rgb.green;
+ b -= rgb.blue;
+ numCols--;
+ leftSumBoundary++;
+ }
+ // calculate RGB averages
+ rowRGBAverages[targetColumn] = new RGB(r / numCols, g / numCols, b / numCols);
+ targetColumn++;
+ }
+ return rowRGBAverages;
+ }
+
+ /**
+ * Enable/disable all widgets of a control
+ *
+ * @param control control to enable/disable
+ * @param enable <code>true</code> to enable, <code>false</code> to disable
+ */
+ public static void enable(final Control control, final boolean enable) {
+ if (control instanceof Composite) {
+ for (final Control c : ((Composite) control).getChildren()) {
+ enable(c, enable);
+ }
+ }
+ control.setEnabled(enable);
+ }
+
+ /**
+ * Build a font from a given control. Useful if we just want a bold label
+ * for example
+ *
+ * @param control control that handle the default font
+ * @param style new style
+ * @return a font with the given style
+ */
+ public static Font buildFontFrom(final Control control, final int style) {
+ final Font temp = control.getFont();
+ final FontData[] fontData = temp.getFontData();
+ if (fontData == null || fontData.length == 0) {
+ return temp;
+ }
+ return new Font(control.getDisplay(), fontData[0].getName(), fontData[0].getHeight(), style);
+ }
+
+ /**
+ * Build a font from a given control. Useful if we just want a bold label
+ * for example
+ *
+ * @param control control that handle the default font
+ * @param style new style
+ * @return a font with the given style
+ */
+ public static Font buildFontFrom(final Control control, final int style, final int size) {
+ final Font temp = control.getFont();
+ final FontData[] fontData = temp.getFontData();
+ if (fontData == null || fontData.length == 0) {
+ return temp;
+ }
+ return new Font(control.getDisplay(), fontData[0].getName(), size, style);
+ }
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/utils/SimpleSelectionAdapter.java b/org.tizen.common.externals/src/org/mihalis/opal/utils/SimpleSelectionAdapter.java
new file mode 100644
index 000000000..1299df6b2
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/utils/SimpleSelectionAdapter.java
@@ -0,0 +1,47 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON.
+ * 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:
+ * Laurent CARON (laurent.caron at gmail dot com) - initial API and implementation
+ *******************************************************************************/
+
+package org.mihalis.opal.utils;
+
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.events.SelectionListener;
+
+/**
+ * This class is an adapter for the SelectionListener. Both behaviours (DefaultSelected and Selected) are doing the same thing
+ */
+public abstract class SimpleSelectionAdapter implements SelectionListener {
+
+ /**
+ * @see org.eclipse.swt.events.SelectionListener#widgetDefaultSelected(org.eclipse.swt.events.SelectionEvent)
+ */
+ @Override
+ public void widgetDefaultSelected(final SelectionEvent e) {
+ this.handle(e);
+
+ }
+
+ /**
+ * @see org.eclipse.swt.events.SelectionListener#widgetSelected(org.eclipse.swt.events.SelectionEvent)
+ */
+ @Override
+ public void widgetSelected(final SelectionEvent e) {
+ this.handle(e);
+
+ }
+
+ /**
+ * Sent when selection occurs in the control.
+ *
+ * @param e - an event containing information about the selection
+ */
+ public abstract void handle(SelectionEvent e);
+
+}
diff --git a/org.tizen.common.externals/src/org/mihalis/opal/utils/StringUtil.java b/org.tizen.common.externals/src/org/mihalis/opal/utils/StringUtil.java
new file mode 100644
index 000000000..7c1994c86
--- /dev/null
+++ b/org.tizen.common.externals/src/org/mihalis/opal/utils/StringUtil.java
@@ -0,0 +1,73 @@
+/*******************************************************************************
+ * Copyright (c) 2011 Laurent CARON
+ * 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:
+ * Laurent CARON (laurent.caron at gmail dot com) - Initial implementation and API
+ *******************************************************************************/
+package org.mihalis.opal.utils;
+
+import java.io.PrintWriter;
+import java.io.StringWriter;
+
+/**
+ * This class provides useful String manipulation methods
+ *
+ */
+public class StringUtil {
+ /**
+ * Check if a string is empty or null
+ *
+ * @param source source string
+ * @return <code>true</code> is the string is empty or null,
+ * <code>false</code> otherwise
+ */
+ public static boolean isEmpty(final String source) {
+ return source == null || source.trim().isEmpty();
+ }
+
+ /**
+ * Converts exception stack trace as string
+ *
+ * @param exception exception to convert
+ * @return a string that contains the exception
+ */
+ public static final String stackStraceAsString(final Throwable exception) {
+ final StringWriter stringWriter = new StringWriter();
+ exception.printStackTrace(new PrintWriter(stringWriter));
+ return stringWriter.toString();
+ }
+
+ /**
+ * Insert a string in a middle of another string
+ *
+ * @param source source string
+ * @param newEntry string to insert into source
+ * @param position position to insert source
+ * @return the new string
+ */
+ public static String insertString(final String source, final String newEntry, final int position) {
+ final StringBuilder sb = new StringBuilder();
+ sb.append(source.substring(0, position)).append(newEntry).append(source.substring(position));
+ return sb.toString();
+ }
+
+ /**
+ * Remove a character in a String
+ *
+ * @param source source string
+ * @param position position of the character to remove
+ * @return the string without the character
+ */
+ public static String removeCharAt(final String source, final int position) {
+ final StringBuilder sb = new StringBuilder();
+ if (position == source.length()) {
+ return source;
+ }
+ sb.append(source.substring(0, position)).append(source.substring(position + 1));
+ return sb.toString();
+ }
+}
diff --git a/org.tizen.common.externals/src/org/tizen/common/externals/ExternalsPlugin.java b/org.tizen.common.externals/src/org/tizen/common/externals/ExternalsPlugin.java
new file mode 100644
index 000000000..208ca6df5
--- /dev/null
+++ b/org.tizen.common.externals/src/org/tizen/common/externals/ExternalsPlugin.java
@@ -0,0 +1,50 @@
+package org.tizen.common.externals;
+
+import org.eclipse.ui.plugin.AbstractUIPlugin;
+import org.osgi.framework.BundleContext;
+
+/**
+ * The activator class controls the plug-in life cycle
+ */
+public class ExternalsPlugin extends AbstractUIPlugin {
+
+ // The plug-in ID
+ public static final String PLUGIN_ID = "org.tizen.common.extras"; //$NON-NLS-1$
+
+ // The shared instance
+ private static ExternalsPlugin plugin;
+
+ /**
+ * The constructor
+ */
+ public ExternalsPlugin() {
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
+ */
+ public void start(BundleContext context) throws Exception {
+ super.start(context);
+ plugin = this;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
+ */
+ public void stop(BundleContext context) throws Exception {
+ plugin = null;
+ super.stop(context);
+ }
+
+ /**
+ * Returns the shared instance
+ *
+ * @return the shared instance
+ */
+ public static ExternalsPlugin getDefault() {
+ return plugin;
+ }
+
+}
diff --git a/org.tizen.common.feature/build.properties b/org.tizen.common.feature/build.properties
index bee14d1b4..a8b9447d0 100644
--- a/org.tizen.common.feature/build.properties
+++ b/org.tizen.common.feature/build.properties
@@ -2,5 +2,4 @@ bin.includes = feature.xml,\
license.html,\
feature.properties,\
epl-v10.html,\
- LICENSE-2.0.htm
-root = rootfiles
+ LICENSE-2.0.htm \ No newline at end of file
diff --git a/org.tizen.common.feature/feature.xml b/org.tizen.common.feature/feature.xml
index 30796d6a0..71fb7d8ba 100644
--- a/org.tizen.common.feature/feature.xml
+++ b/org.tizen.common.feature/feature.xml
@@ -1,21 +1,21 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<feature
- id="org.tizen.common.feature"
- label="Tizen Common Tools"
- version="1.0.0.qualifier"
- provider-name="Samsung"
- plugin="org.tizen.base.platform"
- license-feature="org.tizen.base.feature">
-
- <description>
- Common library for Tizen SDK.
- </description>
-
- <copyright>
- Copyright (c) 2010-2011, Samsung Electronics Co., LTD. All rights reserved.
- </copyright>
-
- <license url="license.html">
+<?xml version="1.0" encoding="UTF-8"?>
+<feature
+ id="org.tizen.common.feature"
+ label="Tizen Common Tools"
+ version="1.0.0.qualifier"
+ provider-name="Tizen"
+ plugin="org.tizen.base.platform"
+ license-feature="org.tizen.base.feature">
+
+ <description>
+ Common library for Tizen SDK.
+ </description>
+
+ <copyright>
+ Copyright (c)
+ </copyright>
+
+ <license url="license.html">
Tizen SDK
Tizen SDK contains software portions licensed under various open source licenses as well as proprietary components. All open source software portions (&quot;Open Source Software&quot;) are licensed under the open source licenses that accompany such Open Source Software.
@@ -26,18 +26,32 @@ Except for the Open Source Software contained in Tizen SDK, all other software p
You may access and download Tizen SDK Open Source Software at: http://developer.tizen.org/download/tizenopensdk.tar.gz
-BY CLICKING THE &quot;I AGREE&quot; BUTTON OR BY USING ANY PART OF TIZEN SDK, YOU AGREE (ON BEHALF OF YOURSELF AND/OR YOUR COMPANY) TO THE OPEN SOURCE SOFTWARE LICENSE TERMS AND THE TIZEN SOFTWARE DEVELOPMENT KIT LICENSE AGREEMENT. IF YOU DO NOT AGREE WITH THE OPEN SOURCE SOFTWARE LICENSE TERMS OR THE TIZEN SOFTWARE DEVELOPMENT KIT LICENSE AGREEMENT, YOU MAY NOT DOWNLOAD OR USE TIZEN SDK.
- </license>
-
- <plugin
- id="org.tizen.common"
- download-size="0"
- install-size="0"
- version="0.0.0"
- unpack="false"/>
+BY CLICKING THE &quot;I AGREE&quot; BUTTON OR BY USING ANY PART OF TIZEN SDK, YOU AGREE (ON BEHALF OF YOURSELF AND/OR YOUR COMPANY) TO THE OPEN SOURCE SOFTWARE LICENSE TERMS AND THE TIZEN SOFTWARE DEVELOPMENT KIT LICENSE AGREEMENT. IF YOU DO NOT AGREE WITH THE OPEN SOURCE SOFTWARE LICENSE TERMS OR THE TIZEN SOFTWARE DEVELOPMENT KIT LICENSE AGREEMENT, YOU MAY NOT DOWNLOAD OR USE TIZEN SDK.
+ </license>
+
+ <plugin
+ id="org.tizen.common"
+ download-size="0"
+ install-size="0"
+ version="0.0.0"
+ unpack="false"/>
+
+ <plugin
+ id="org.tizen.common.connection"
+ download-size="0"
+ install-size="0"
+ version="0.0.0"
+ unpack="false"/>
+
+ <plugin
+ id="org.tizen.common.externals"
+ download-size="0"
+ install-size="0"
+ version="0.0.0"
+ unpack="false"/>
<plugin
- id="org.tizen.common.connection"
+ id="org.tizen.common.verrari"
download-size="0"
install-size="0"
version="0.0.0"
diff --git a/org.tizen.common.feature/rootfiles/resources/icons/tizen-sdk-ide.ico b/org.tizen.common.feature/rootfiles/resources/icons/tizen-sdk-ide.ico
deleted file mode 100644
index 35e30a873..000000000
--- a/org.tizen.common.feature/rootfiles/resources/icons/tizen-sdk-ide.ico
+++ /dev/null
Binary files differ
diff --git a/org.tizen.common.verrari/.classpath b/org.tizen.common.verrari/.classpath
new file mode 100644
index 000000000..a885b9bd5
--- /dev/null
+++ b/org.tizen.common.verrari/.classpath
@@ -0,0 +1,9 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+ <classpathentry exported="true" kind="lib" path="lib/jsoup-1.6.3.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="src" path="test/src"/>
+ <classpathentry kind="output" path="bin"/>
+</classpath>
diff --git a/org.tizen.common.verrari/.project b/org.tizen.common.verrari/.project
new file mode 100644
index 000000000..6b5e76348
--- /dev/null
+++ b/org.tizen.common.verrari/.project
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>org.tizen.common.verrari</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/org.tizen.common.verrari/.settings/org.eclipse.jdt.core.prefs b/org.tizen.common.verrari/.settings/org.eclipse.jdt.core.prefs
new file mode 100644
index 000000000..c3c3ee186
--- /dev/null
+++ b/org.tizen.common.verrari/.settings/org.eclipse.jdt.core.prefs
@@ -0,0 +1,8 @@
+#Tue Jul 24 20:15:30 KST 2012
+eclipse.preferences.version=1
+org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
+org.eclipse.jdt.core.compiler.compliance=1.6
+org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
+org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
+org.eclipse.jdt.core.compiler.source=1.6
diff --git a/org.tizen.common.verrari/META-INF/MANIFEST.MF b/org.tizen.common.verrari/META-INF/MANIFEST.MF
new file mode 100644
index 000000000..a3df065ca
--- /dev/null
+++ b/org.tizen.common.verrari/META-INF/MANIFEST.MF
@@ -0,0 +1,28 @@
+Manifest-Version: 1.0
+Bundle-ManifestVersion: 2
+Bundle-Name: %Bundle-Name
+Bundle-SymbolicName: org.tizen.common.verrari
+Bundle-Version: 1.0.0.qualifier
+Bundle-Activator: org.tizen.common.verrari.Activator
+Bundle-Vendor: %Bundle-Vendor
+Require-Bundle: org.eclipse.ui,
+ org.eclipse.core.runtime,
+ org.tizen.common
+Bundle-RequiredExecutionEnvironment: JavaSE-1.6
+Bundle-ActivationPolicy: lazy
+Bundle-ClassPath: lib/jsoup-1.6.3.jar,
+ .
+Export-Package: org.jsoup,
+ org.jsoup.examples,
+ org.jsoup.helper,
+ org.jsoup.nodes,
+ org.jsoup.parser,
+ org.jsoup.safety,
+ org.jsoup.select,
+ org.tizen.common.verrari,
+ org.tizen.common.verrari.engine,
+ org.tizen.common.verrari.engine.freemarker,
+ org.tizen.common.verrari.engine.jsoup,
+ org.tizen.common.verrari.model,
+ org.tizen.common.verrari.target,
+ org.tizen.common.verrari.template
diff --git a/org.tizen.common.verrari/OSGI-INF/l10n/bundle.properties b/org.tizen.common.verrari/OSGI-INF/l10n/bundle.properties
new file mode 100644
index 000000000..c4f377d84
--- /dev/null
+++ b/org.tizen.common.verrari/OSGI-INF/l10n/bundle.properties
@@ -0,0 +1,3 @@
+#Properties file for org.tizen.common.verrari
+Bundle-Vendor = Samsung Electronics
+Bundle-Name = Tizen Verrari - Template Engine \ No newline at end of file
diff --git a/org.tizen.common.verrari/about.html b/org.tizen.common.verrari/about.html
new file mode 100644
index 000000000..e96d83591
--- /dev/null
+++ b/org.tizen.common.verrari/about.html
@@ -0,0 +1,41 @@
+<!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>May, 2011</p>
+<h3>Tizen SDK</h3>
+
+<p><a href="http://www.tizen.org/" target="_blank">Tizen SDK</a>
+is a set of Eclipse plug-ins that helps programmers to develop applications for
+the mobile platform.</p>
+
+<h3>License</h3>
+
+<p>See <a href="about_files/LICENSE-2.0.htm">Apache License, Version 2.0</a>.</p>
+
+<h3>Third Party Content</h3>
+
+<p>The Content includes items that have been sourced from third parties as set out below. If you did not
+receive this Content directly from the Eclipse Foundation, the following is provided for informational
+purposes only, and you should look to the Redistributor's license for terms and conditions of use.</p>
+
+<h4>jsoup</h4>
+<p>
+jsoup is a Java library for working with real-world HTML. It provides a very convenient API for extracting and manipulating data, using the best of DOM, CSS, and jquery-like methods
+</p>
+
+<p>
+A copy of the license is included in <a href="about_files/jsoup-LICENSE.txt">about_files/jsoup-LICENSE.txt</a>. The home page is located at:
+<ul>
+<a href="http://jsoup.org/">http://jsoup.org/</a>
+</ul>
+</p>
+
+</body>
+</html> \ No newline at end of file
diff --git a/org.tizen.common.verrari/about_files/LICENSE-2.0.htm b/org.tizen.common.verrari/about_files/LICENSE-2.0.htm
new file mode 100644
index 000000000..f7ca65649
--- /dev/null
+++ b/org.tizen.common.verrari/about_files/LICENSE-2.0.htm
@@ -0,0 +1,191 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<html lang="en">
+ <head>
+ <title>Apache License, Version 2.0</title>
+
+ <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
+ <meta property="og:image" content="http://www.apache.org/images/asf_logo.gif" />
+
+ <link rel="stylesheet" type="text/css" media="screen" href="/css/style.css">
+ <link rel="stylesheet" type="text/css" media="screen" href="/css/code.css">
+
+ <script type="text/javascript" src="/js/jquery.js"></script>
+ <script type="text/javascript" src="/js/apache_boot.js"></script>
+
+
+
+
+ <!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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. -->
+ </head>
+
+ <body>
+ <div id="page" class="container_16">
+ <div id="header" class="grid_8">
+ <h1>The Apache Software Foundation</h1>
+ <h2>Apache License, Version 2.0</h2>
+ </div>
+
+ <div class="clear"></div>
+ <div id="content" class="grid_16"><div class="section-content"><p>Apache License<br></br>Version 2.0, January 2004<br></br>
+<a href="http://www.apache.org/licenses/">http://www.apache.org/licenses/</a> </p>
+<p>TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION</p>
+<p><strong><a name="definitions">1. Definitions</a></strong>.</p>
+<p>"License" shall mean the terms and conditions for use, reproduction, and
+distribution as defined by Sections 1 through 9 of this document.</p>
+<p>"Licensor" shall mean the copyright owner or entity authorized by the
+copyright owner that is granting the License.</p>
+<p>"Legal Entity" 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, "control" 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.</p>
+<p>"You" (or "Your") shall mean an individual or Legal Entity exercising
+permissions granted by this License.</p>
+<p>"Source" form shall mean the preferred form for making modifications,
+including but not limited to software source code, documentation source,
+and configuration files.</p>
+<p>"Object" 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.</p>
+<p>"Work" 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).</p>
+<p>"Derivative Works" 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.</p>
+<p>"Contribution" 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, "submitted" 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 "Not a
+Contribution."</p>
+<p>"Contributor" 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.</p>
+<p><strong><a name="copyright">2. Grant of Copyright License</a></strong>. 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.</p>
+<p><strong><a name="patent">3. Grant of Patent License</a></strong>. 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.</p>
+<p><strong><a name="redistribution">4. Redistribution</a></strong>. 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:</p>
+<ol>
+<li>
+<p>You must give any other recipients of the Work or Derivative Works a
+copy of this License; and</p>
+</li>
+<li>
+<p>You must cause any modified files to carry prominent notices stating
+that You changed the files; and</p>
+</li>
+<li>
+<p>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</p>
+</li>
+<li>
+<p>If the Work includes a "NOTICE" 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.</p>
+</li>
+</ol>
+<p><strong><a name="contributions">5. Submission of Contributions</a></strong>. 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.</p>
+<p><strong><a name="trademarks">6. Trademarks</a></strong>. 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.</p>
+<p><strong><a name="no-warranty">7. Disclaimer of Warranty</a></strong>. Unless required by
+applicable law or agreed to in writing, Licensor provides the Work (and
+each Contributor provides its Contributions) 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. 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.</p>
+<p><strong><a name="no-liability">8. Limitation of Liability</a></strong>. 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.</p>
+<p><strong><a name="additional">9. Accepting Warranty or Additional Liability</a></strong>.
+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.</p>
+<p>END OF TERMS AND CONDITIONS</p>
+
+ <div class="clear"></div>
+
+ </div>
+ <div id="copyright" class="container_16">
+ <p>Copyright &#169; 2011 The Apache Software Foundation, Licensed under the <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache License, Version 2.0</a>.<br/>Apache and the Apache feather logo are trademarks of The Apache Software Foundation.</p>
+ </div>
+ </body>
+</html>
diff --git a/org.tizen.common.verrari/about_files/jsoup-LICENSE.txt b/org.tizen.common.verrari/about_files/jsoup-LICENSE.txt
new file mode 100644
index 000000000..fda732e78
--- /dev/null
+++ b/org.tizen.common.verrari/about_files/jsoup-LICENSE.txt
@@ -0,0 +1,21 @@
+The MIT License
+
+Copyright (c) 2009, 2010, 2011, 2012 Jonathan Hedley <jonathan@hedley.net>
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE. \ No newline at end of file
diff --git a/org.tizen.common.verrari/build.properties b/org.tizen.common.verrari/build.properties
new file mode 100644
index 000000000..e4e272e37
--- /dev/null
+++ b/org.tizen.common.verrari/build.properties
@@ -0,0 +1,9 @@
+source.. = src/
+output.. = bin/
+bin.includes = META-INF/,\
+ .,\
+ template/,\
+ about.html,\
+ about_files/,\
+ OSGI-INF/,\
+ lib/jsoup-1.6.3.jar
diff --git a/org.tizen.common.verrari/lib/jsoup-1.6.3.jar b/org.tizen.common.verrari/lib/jsoup-1.6.3.jar
new file mode 100644
index 000000000..b3421d59b
--- /dev/null
+++ b/org.tizen.common.verrari/lib/jsoup-1.6.3.jar
Binary files differ
diff --git a/org.tizen.common.verrari/src/org/tizen/common/verrari/Activator.java b/org.tizen.common.verrari/src/org/tizen/common/verrari/Activator.java
new file mode 100644
index 000000000..590aabfb1
--- /dev/null
+++ b/org.tizen.common.verrari/src/org/tizen/common/verrari/Activator.java
@@ -0,0 +1,78 @@
+/*
+ * Verrari - TemplateEngine
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * Changhyun Lee <changhyun1.lee@samsung.com>
+ * Hyeongseok Heo <hyeongseok.heo@samsung.com>
+ * Kangho Kim <kh5325.kim@samsung.com>
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+
+package org.tizen.common.verrari;
+
+import org.eclipse.ui.plugin.AbstractUIPlugin;
+import org.osgi.framework.BundleContext;
+
+/**
+ * The activator class controls the plug-in life cycle
+ */
+public class Activator extends AbstractUIPlugin {
+
+ // The plug-in ID
+ public static final String PLUGIN_ID = "org.tizen.common.verrari"; //$NON-NLS-1$
+
+ // The shared instance
+ private static Activator plugin;
+
+ /**
+ * The constructor
+ */
+ public Activator() {
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
+ */
+ public void start(BundleContext context) throws Exception {
+ super.start(context);
+ plugin = this;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
+ */
+ public void stop(BundleContext context) throws Exception {
+ plugin = null;
+ super.stop(context);
+ }
+
+ /**
+ * Returns the shared instance
+ *
+ * @return the shared instance
+ */
+ public static Activator getDefault() {
+ return plugin;
+ }
+
+}
diff --git a/org.tizen.common.verrari/src/org/tizen/common/verrari/engine/AbstractTemplateEngine.java b/org.tizen.common.verrari/src/org/tizen/common/verrari/engine/AbstractTemplateEngine.java
new file mode 100644
index 000000000..7aafb07ce
--- /dev/null
+++ b/org.tizen.common.verrari/src/org/tizen/common/verrari/engine/AbstractTemplateEngine.java
@@ -0,0 +1,131 @@
+/*
+ * Verrari - TemplateEngine
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * Changhyun Lee <changhyun1.lee@samsung.com>
+ * Hyeongseok Heo <hyeongseok.heo@samsung.com>
+ * Kangho Kim <kh5325.kim@samsung.com>
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+
+package org.tizen.common.verrari.engine;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.tizen.common.verrari.model.IModel;
+import org.tizen.common.verrari.model.IModelProvider;
+import org.tizen.common.verrari.model.StaticModelProvider;
+import org.tizen.common.verrari.target.TargetGroup;
+import org.tizen.common.verrari.target.TargetUnit;
+import org.tizen.common.verrari.template.ITemplate;
+import org.tizen.common.verrari.template.ITemplateProvider;
+import org.tizen.common.verrari.template.StaticTemplateProvider;
+
+/**
+ * AbstractTemplateEngine.
+ *
+ * Initialization for ITemplateProvider, IModelProvider and sharedVariables.
+ *
+ * @author ChangHyun Lee{@literal <changhyun1.lee@samsung.com>} (S-Core)
+ */
+public abstract class AbstractTemplateEngine implements ITemplateEngine {
+
+ protected IModelProvider modelProvider;
+ protected ITemplateProvider templateProvider;
+ protected HashMap<Object, Object> sharedVariables;
+
+ public AbstractTemplateEngine() {
+ modelProvider = new StaticModelProvider();
+ templateProvider = new StaticTemplateProvider();
+ sharedVariables = new HashMap<Object, Object>();
+ }
+
+ @Override
+ public void setTemplate(String key, ITemplate template) {
+ templateProvider.addTemplate(key, template);
+ }
+
+ @Override
+ public ITemplate getTemplate(String key) {
+ return templateProvider.getTemplate(key);
+ }
+
+ @Override
+ public ITemplateProvider getTemplateProvider() {
+ return templateProvider;
+ }
+
+ @Override
+ public void setModel(String key, IModel model) {
+ modelProvider.addModel(key, model);
+ }
+
+ @Override
+ public IModel getModel(String key) {
+ return modelProvider.getModel(key);
+ }
+
+ @Override
+ public IModelProvider getModelProvider() {
+ return modelProvider;
+ }
+
+ @Override
+ public void generate(TargetUnit unit) throws Exception {
+ applySharedVariable();
+ }
+
+ @Override
+ public void genearteGroup(TargetGroup group) throws Exception {
+ if (!group.isEmpty()) {
+ List<TargetUnit> targetList = group.getTargetUnits();
+ for (TargetUnit unit : targetList) {
+ generate(unit);
+ }
+ }
+ }
+
+ @Override
+ public void setSharedVariable(Object key, Object value) {
+ sharedVariables.put(key, value);
+ }
+
+ @Override
+ public Object getSharedVariable(Object key) {
+ return sharedVariables.get(key);
+ }
+
+ @Override
+ public void clearSharedVariable() {
+ sharedVariables.clear();
+ }
+
+ public void applySharedVariable() {
+ Map<String, IModel> models = getModelProvider().getModels();
+ for (IModel model : models.values()) {
+ for (Object key : sharedVariables.keySet()) {
+ model.put(key, sharedVariables.get(key));
+ }
+ }
+ }
+}
diff --git a/org.tizen.common.verrari/src/org/tizen/common/verrari/engine/ITemplateEngine.java b/org.tizen.common.verrari/src/org/tizen/common/verrari/engine/ITemplateEngine.java
new file mode 100644
index 000000000..73932efb2
--- /dev/null
+++ b/org.tizen.common.verrari/src/org/tizen/common/verrari/engine/ITemplateEngine.java
@@ -0,0 +1,63 @@
+/*
+ * Verrari - TemplateEngine
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * Changhyun Lee <changhyun1.lee@samsung.com>
+ * Hyeongseok Heo <hyeongseok.heo@samsung.com>
+ * Kangho Kim <kh5325.kim@samsung.com>
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+
+package org.tizen.common.verrari.engine;
+
+import org.tizen.common.verrari.model.IModel;
+import org.tizen.common.verrari.model.IModelProvider;
+import org.tizen.common.verrari.target.TargetGroup;
+import org.tizen.common.verrari.target.TargetUnit;
+import org.tizen.common.verrari.template.ITemplate;
+import org.tizen.common.verrari.template.ITemplateProvider;
+
+/**
+ * ITemplateEngine.
+ *
+ * Common Template Engine Interface
+ *
+ * @author ChangHyun Lee{@literal <changhyun1.lee@samsung.com>} (S-Core)
+ */
+public interface ITemplateEngine {
+
+ public void setTemplate(String key, ITemplate template);
+ public ITemplate getTemplate(String key);
+ public ITemplateProvider getTemplateProvider();
+
+ public void setModel(String key, IModel model);
+ public IModel getModel(String key);
+ public IModelProvider getModelProvider();
+
+ public void generate(TargetUnit unit) throws Exception;
+ public void genearteGroup(TargetGroup group) throws Exception;
+
+ public void setSharedVariable(Object key, Object value);
+ public Object getSharedVariable(Object key);
+ public void clearSharedVariable();
+ public String getEngineVersion();
+
+}
diff --git a/org.tizen.common.verrari/src/org/tizen/common/verrari/engine/TemplateEngineFactory.java b/org.tizen.common.verrari/src/org/tizen/common/verrari/engine/TemplateEngineFactory.java
new file mode 100644
index 000000000..ea1cc13da
--- /dev/null
+++ b/org.tizen.common.verrari/src/org/tizen/common/verrari/engine/TemplateEngineFactory.java
@@ -0,0 +1,87 @@
+/*
+ * Verrari - TemplateEngine
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * Changhyun Lee <changhyun1.lee@samsung.com>
+ * Hyeongseok Heo <hyeongseok.heo@samsung.com>
+ * Kangho Kim <kh5325.kim@samsung.com>
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+
+package org.tizen.common.verrari.engine;
+
+import org.tizen.common.Factory;
+import org.tizen.common.FactoryWithArgument;
+import org.tizen.common.verrari.engine.freemarker.FreemarkerTemplateEngine;
+import org.tizen.common.verrari.engine.jsoup.JsoupTemplateEngine;
+
+/**
+ * TemplateEngineFactory.
+ *
+ * Create to template engine.
+ *
+ * @author ChangHyun Lee{@literal <changhyun1.lee@samsung.com>} (S-Core)
+ */
+@SuppressWarnings("rawtypes")
+public class TemplateEngineFactory implements Factory<ITemplateEngine> ,FactoryWithArgument<ITemplateEngine, Class> {
+
+ protected static Factory<ITemplateEngine> instance;
+ static {
+ instance = new TemplateEngineFactory();
+ }
+
+ /**
+ * get template engine factory instance.
+ *
+ * @return TemplateEngineFactory
+ */
+ public static Factory<ITemplateEngine> getInstance() {
+ return instance;
+ }
+
+ /**
+ * Create Default template engine
+ *
+ * @return ITemplateEngine {@link ITemplateEngine}
+ */
+ @Override
+ public ITemplateEngine create() {
+ return new FreemarkerTemplateEngine();
+ }
+
+ /**
+ * Create template engine
+ *
+ * @param engineClass TemplateEngineClass
+ * @return ITemplateEngine {@link ITemplateEngine}
+ */
+ @Override
+ public ITemplateEngine create(Class engineClass) {
+ if (FreemarkerTemplateEngine.class.equals(engineClass)) {
+ return new FreemarkerTemplateEngine();
+ } else if (JsoupTemplateEngine.class.equals(engineClass)) {
+ return new JsoupTemplateEngine();
+ } else {
+ return null;
+ }
+ }
+
+}
diff --git a/org.tizen.common.verrari/src/org/tizen/common/verrari/engine/freemarker/FreemarkerTemplateEngine.java b/org.tizen.common.verrari/src/org/tizen/common/verrari/engine/freemarker/FreemarkerTemplateEngine.java
new file mode 100644
index 000000000..00c9314cc
--- /dev/null
+++ b/org.tizen.common.verrari/src/org/tizen/common/verrari/engine/freemarker/FreemarkerTemplateEngine.java
@@ -0,0 +1,92 @@
+/*
+ * Verrari - TemplateEngine
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * Changhyun Lee <changhyun1.lee@samsung.com>
+ * Hyeongseok Heo <hyeongseok.heo@samsung.com>
+ * Kangho Kim <kh5325.kim@samsung.com>
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+
+package org.tizen.common.verrari.engine.freemarker;
+
+import java.io.BufferedWriter;
+import java.util.Locale;
+
+import org.tizen.common.util.FreeMarkerUtil;
+import org.tizen.common.verrari.engine.AbstractTemplateEngine;
+import org.tizen.common.verrari.model.MapModel;
+import org.tizen.common.verrari.target.TargetUnit;
+import org.tizen.common.verrari.template.FileTemplate;
+
+import freemarker.template.Configuration;
+import freemarker.template.Template;
+
+
+/**
+ * FreemarkerTemplateEngine.
+ *
+ * @author ChangHyun Lee{@literal <changhyun1.lee@samsung.com>} (S-Core)
+ */
+public class FreemarkerTemplateEngine extends AbstractTemplateEngine {
+
+ protected Configuration cfg;
+
+ public FreemarkerTemplateEngine() {
+ cfg = FreeMarkerUtil.getDefaultConfiguration();
+ }
+
+ public Configuration getConfiguration() {
+ return cfg;
+ }
+
+ @Override
+ public void generate(TargetUnit unit) throws Exception {
+ super.generate(unit);
+ MapModel model = (MapModel) getModel(unit.getModelKey());
+ if (null == model) {
+ throw new Exception("Model is Empty.");
+ }
+
+ FileTemplate template = (FileTemplate) getTemplate(unit.getTemplateKey());
+ if (null == template) {
+ throw new Exception("Template is Empty.");
+ }
+ Template freemarkerTemplate = cfg.getTemplate(template.getContainer().getPath());
+ cfg.setEncoding(Locale.getDefault(), unit.getEncoding());
+
+ freemarkerTemplate.process(model.getContainer(), new BufferedWriter(unit.getWriter()));
+ //freemarkertemp.process(model.getModel(), new OutputStreamWriter(System.out));
+
+ // TODO:: XML Parser
+// Map<String, Object> root = new HashMap<String, Object>();
+// NodeModel model2 = NodeModel.parse(new File("template/html/test.xml"));
+// root.put("doc", model2);
+
+ }
+
+ @SuppressWarnings("static-access")
+ @Override
+ public String getEngineVersion() {
+ return cfg.getVersionNumber();
+ }
+
+}
diff --git a/org.tizen.common.verrari/src/org/tizen/common/verrari/engine/jsoup/JsoupTemplateEngine.java b/org.tizen.common.verrari/src/org/tizen/common/verrari/engine/jsoup/JsoupTemplateEngine.java
new file mode 100644
index 000000000..21cb6ca2b
--- /dev/null
+++ b/org.tizen.common.verrari/src/org/tizen/common/verrari/engine/jsoup/JsoupTemplateEngine.java
@@ -0,0 +1,110 @@
+/*
+ * Verrari - TemplateEngine
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * Changhyun Lee <changhyun1.lee@samsung.com>
+ * Hyeongseok Heo <hyeongseok.heo@samsung.com>
+ * Kangho Kim <kh5325.kim@samsung.com>
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+
+package org.tizen.common.verrari.engine.jsoup;
+
+import java.io.File;
+import java.io.Writer;
+import java.util.Map;
+
+import org.jsoup.Jsoup;
+import org.jsoup.nodes.Attribute;
+import org.jsoup.nodes.Attributes;
+import org.jsoup.nodes.Document;
+import org.jsoup.nodes.Element;
+import org.jsoup.select.Elements;
+import org.tizen.common.verrari.engine.AbstractTemplateEngine;
+import org.tizen.common.verrari.model.MapModel;
+import org.tizen.common.verrari.target.TargetUnit;
+import org.tizen.common.verrari.template.FileTemplate;
+
+/**
+ * JsoupTemplateEngine.
+ * HTML Parser.
+ *
+ * @author ChangHyun Lee{@literal <changhyun1.lee@samsung.com>} (S-Core)
+ */
+public class JsoupTemplateEngine extends AbstractTemplateEngine {
+
+ public JsoupTemplateEngine() {
+ }
+
+ @Override
+ public void generate(TargetUnit unit) throws Exception {
+ super.generate(unit);
+
+ MapModel model = (MapModel) getModel(unit.getModelKey());
+ if (null == model) {
+ throw new Exception("Model is Empty.");
+ }
+
+ FileTemplate template = (FileTemplate) getTemplate(unit.getTemplateKey());
+ if (null == template) {
+ throw new Exception("Template is Empty.");
+ }
+
+ generate(template.getContainer(), (Map) model.getContainer(), template.getEncoding(), unit.getWriter());
+ }
+
+ public Document generate(File template, Map model, String encoding) throws Exception {
+ Document doc = Jsoup.parse(template, encoding);
+ Map<Object, Object> root = (Map<Object, Object>) model;
+ for (Map.Entry<Object, Object> entry : root.entrySet()) {
+ Elements elements = doc.select((String) entry.getKey());
+ if (!elements.isEmpty()) {
+ Element element = elements.get(0);
+ Object attr = entry.getValue() ;
+ if (attr instanceof Attribute) {
+ element.attr(((Attribute) attr).getKey(), ((Attribute) attr).getValue());
+ } else if (attr instanceof Attributes){
+ Attributes attributes = (Attributes) attr;
+ for (Attribute attribute : attributes) {
+ element.attr(attribute.getKey(), attribute.getValue());;
+ }
+ } else {
+ element.attr((String)entry.getKey(), (String)attr);
+ }
+ }
+ }
+ return doc;
+ }
+
+ public void generate(File template, Map model, String encoding, Writer write) throws Exception {
+ Document doc = generate(template, model, encoding);
+ write.write(doc.html());
+ write.flush();
+ }
+
+ @Override
+ public String getEngineVersion() {
+ // FIXME::
+ // Platform.getBundle("org.jsoup").getHeaders().get("Bundle-Version");
+ return "1.6.3";
+ }
+
+} \ No newline at end of file
diff --git a/org.tizen.common.verrari/src/org/tizen/common/verrari/model/IModel.java b/org.tizen.common.verrari/src/org/tizen/common/verrari/model/IModel.java
new file mode 100644
index 000000000..2c01b7856
--- /dev/null
+++ b/org.tizen.common.verrari/src/org/tizen/common/verrari/model/IModel.java
@@ -0,0 +1,44 @@
+/*
+ * Verrari - TemplateEngine
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * Changhyun Lee <changhyun1.lee@samsung.com>
+ * Hyeongseok Heo <hyeongseok.heo@samsung.com>
+ * Kangho Kim <kh5325.kim@samsung.com>
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+
+package org.tizen.common.verrari.model;
+
+/**
+ * IModel.
+ *
+ * Common Model Interface
+ *
+ * @author ChangHyun Lee{@literal <changhyun1.lee@samsung.com>} (S-Core)
+ */
+public interface IModel {
+
+ public void put(Object key, Object value);
+ public Object get(Object key);
+ public Object getContainer();
+
+}
diff --git a/org.tizen.common.verrari/src/org/tizen/common/verrari/model/IModelProvider.java b/org.tizen.common.verrari/src/org/tizen/common/verrari/model/IModelProvider.java
new file mode 100644
index 000000000..198146219
--- /dev/null
+++ b/org.tizen.common.verrari/src/org/tizen/common/verrari/model/IModelProvider.java
@@ -0,0 +1,48 @@
+/*
+ * Verrari - TemplateEngine
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * Changhyun Lee <changhyun1.lee@samsung.com>
+ * Hyeongseok Heo <hyeongseok.heo@samsung.com>
+ * Kangho Kim <kh5325.kim@samsung.com>
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+
+package org.tizen.common.verrari.model;
+
+import java.util.Map;
+
+/**
+ * IModelProvider.
+ *
+ * Management for models.
+ *
+ * @author ChangHyun Lee{@literal <changhyun1.lee@samsung.com>} (S-Core)
+ */
+public interface IModelProvider {
+
+ public void addModel(String key, IModel model);
+ public IModel getModel(String key);
+ public IModel removeModel(String key);
+ public Map<String, IModel> getModels();
+ public boolean isEmpty();
+
+}
diff --git a/org.tizen.common.verrari/src/org/tizen/common/verrari/model/MapModel.java b/org.tizen.common.verrari/src/org/tizen/common/verrari/model/MapModel.java
new file mode 100644
index 000000000..25986c656
--- /dev/null
+++ b/org.tizen.common.verrari/src/org/tizen/common/verrari/model/MapModel.java
@@ -0,0 +1,71 @@
+/*
+ * Verrari - TemplateEngine
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * Changhyun Lee <changhyun1.lee@samsung.com>
+ * Hyeongseok Heo <hyeongseok.heo@samsung.com>
+ * Kangho Kim <kh5325.kim@samsung.com>
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+
+package org.tizen.common.verrari.model;
+
+import java.util.Map;
+
+/**
+ * MapModel.
+ *
+ * IModel implementation by map.
+ *
+ * @author ChangHyun Lee{@literal <changhyun1.lee@samsung.com>} (S-Core)
+ */
+public class MapModel implements IModel {
+
+ protected Map<Object, Object> model;
+
+ public MapModel(Map<Object, Object> map) {
+ this.model = map;
+ }
+
+ @Override
+ public Object get(Object key) {
+ return model.get(key);
+ }
+
+ @Override
+ public Object getContainer() {
+ return model;
+ }
+
+ @Override
+ public void put(Object key, Object value) {
+ model.put(key, value);
+ }
+
+ public Object remove(Object key) {
+ return model.remove(key);
+ }
+
+ public boolean isEmpty() {
+ return model.isEmpty();
+ }
+
+}
diff --git a/org.tizen.common.verrari/src/org/tizen/common/verrari/model/StaticModelProvider.java b/org.tizen.common.verrari/src/org/tizen/common/verrari/model/StaticModelProvider.java
new file mode 100644
index 000000000..1932fb1cd
--- /dev/null
+++ b/org.tizen.common.verrari/src/org/tizen/common/verrari/model/StaticModelProvider.java
@@ -0,0 +1,74 @@
+/*
+ * Verrari - TemplateEngine
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * Changhyun Lee <changhyun1.lee@samsung.com>
+ * Hyeongseok Heo <hyeongseok.heo@samsung.com>
+ * Kangho Kim <kh5325.kim@samsung.com>
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+
+package org.tizen.common.verrari.model;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * StaticModelProvider.
+ *
+ * Manage the models.
+ *
+ * @author ChangHyun Lee{@literal <changhyun1.lee@samsung.com>} (S-Core)
+ */
+public class StaticModelProvider implements IModelProvider {
+
+ protected Map<String, IModel> models;
+
+ public StaticModelProvider() {
+ models = new HashMap<String, IModel>();
+ }
+
+ @Override
+ public void addModel(String key, IModel model) {
+ models.put(key, model);
+ }
+
+ @Override
+ public IModel getModel(String key) {
+ return models.get(key);
+ }
+
+ @Override
+ public IModel removeModel(String key) {
+ return models.remove(key);
+ }
+
+ @Override
+ public Map<String, IModel> getModels() {
+ return models;
+ }
+
+ @Override
+ public boolean isEmpty() {
+ return models.isEmpty();
+ }
+
+}
diff --git a/org.tizen.common.verrari/src/org/tizen/common/verrari/target/TargetGroup.java b/org.tizen.common.verrari/src/org/tizen/common/verrari/target/TargetGroup.java
new file mode 100644
index 000000000..3135c746a
--- /dev/null
+++ b/org.tizen.common.verrari/src/org/tizen/common/verrari/target/TargetGroup.java
@@ -0,0 +1,71 @@
+/*
+ * Verrari - TemplateEngine
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * Changhyun Lee <changhyun1.lee@samsung.com>
+ * Hyeongseok Heo <hyeongseok.heo@samsung.com>
+ * Kangho Kim <kh5325.kim@samsung.com>
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+
+package org.tizen.common.verrari.target;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * TargetGroup
+ *
+ * Targetunits management.
+ *
+ * @author ChangHyun Lee{@literal <changhyun1.lee@samsung.com>} (S-Core)
+ */
+public class TargetGroup {
+
+ protected List<TargetUnit> units;
+
+ public TargetGroup() {
+ units = new ArrayList<TargetUnit>();
+ }
+
+ public List<TargetUnit> getTargetUnits() {
+ return units;
+ }
+
+ public boolean addTargetUnit(TargetUnit unit) {
+ if (unit != null) {
+ return units.add(unit);
+ }
+ return false;
+ }
+
+ public boolean removeTargetunit(TargetUnit unit) {
+ if (unit != null) {
+ return units.remove(unit);
+ }
+ return false;
+ }
+
+ public boolean isEmpty() {
+ return units.isEmpty();
+ }
+
+}
diff --git a/org.tizen.common.verrari/src/org/tizen/common/verrari/target/TargetUnit.java b/org.tizen.common.verrari/src/org/tizen/common/verrari/target/TargetUnit.java
new file mode 100644
index 000000000..961aed1a7
--- /dev/null
+++ b/org.tizen.common.verrari/src/org/tizen/common/verrari/target/TargetUnit.java
@@ -0,0 +1,102 @@
+/*
+ * Verrari - TemplateEngine
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * Changhyun Lee <changhyun1.lee@samsung.com>
+ * Hyeongseok Heo <hyeongseok.heo@samsung.com>
+ * Kangho Kim <kh5325.kim@samsung.com>
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+
+package org.tizen.common.verrari.target;
+
+import java.io.Writer;
+
+/**
+ * TargetUnit.
+ *
+ * Single file management.
+ *
+ * @author ChangHyun Lee{@literal <changhyun1.lee@samsung.com>} (S-Core)
+ */
+public class TargetUnit {
+
+ private String templateKey;
+ private String modelKey;
+ private Writer out;
+ private String encoding;
+
+ public TargetUnit(String templateKey, String modelKey, Writer out, String encoding) {
+ if (templateKey == null || templateKey.isEmpty() || modelKey == null || modelKey.isEmpty() || out == null) {
+ throw new IllegalArgumentException();
+ }
+
+ if (null == encoding || encoding.isEmpty()) {
+ encoding = System.getProperty("file.encoding");
+ }
+
+ this.templateKey = templateKey;
+ this.modelKey = modelKey;
+ this.out = out;
+ this.encoding = encoding;
+ }
+
+ public void setTemplateKey(String templateKey) {
+ if (templateKey != null && !templateKey.isEmpty()) {
+ this.templateKey = templateKey;
+ }
+ }
+
+ public String getTemplateKey() {
+ return templateKey;
+ }
+
+ public void setModelKey(String modelKey) {
+ if (modelKey != null && !modelKey.isEmpty()) {
+ this.modelKey = modelKey;
+ }
+ }
+
+ public String getModelKey() {
+ return modelKey;
+ }
+
+ public void setWriter(Writer out) {
+ if (out != null) {
+ this.out = out;
+ }
+ }
+
+ public Writer getWriter() {
+ return out;
+ }
+
+ public void setEncoding(String encoding) {
+ if (encoding != null && !encoding.isEmpty()) {
+ this.encoding = encoding;
+ }
+ }
+
+ public String getEncoding() {
+ return encoding;
+ }
+
+}
diff --git a/org.tizen.common.verrari/src/org/tizen/common/verrari/template/FileTemplate.java b/org.tizen.common.verrari/src/org/tizen/common/verrari/template/FileTemplate.java
new file mode 100644
index 000000000..c30457d4b
--- /dev/null
+++ b/org.tizen.common.verrari/src/org/tizen/common/verrari/template/FileTemplate.java
@@ -0,0 +1,68 @@
+/*
+ * Verrari - TemplateEngine
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * Changhyun Lee <changhyun1.lee@samsung.com>
+ * Hyeongseok Heo <hyeongseok.heo@samsung.com>
+ * Kangho Kim <kh5325.kim@samsung.com>
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+
+package org.tizen.common.verrari.template;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+
+/**
+ * FileTemplate.
+ *
+ * ITemplate implementation by file.
+ *
+ * @author ChangHyun Lee{@literal <changhyun1.lee@samsung.com>} (S-Core)
+ */
+public class FileTemplate implements ITemplate {
+
+ protected File file;
+ protected String encoding;
+
+ public FileTemplate(File file) {
+ this.file = file;
+ this.encoding = System.getProperty("file.encoding"); //$NON-NLS-1$
+ }
+
+ @Override
+ public File getContainer() {
+ return file;
+ }
+
+ @Override
+ public String getEncoding() {
+ return encoding;
+ }
+
+ @Override
+ public InputStream open() throws IOException {
+ return new FileInputStream(file);
+ }
+
+}
diff --git a/org.tizen.common.verrari/src/org/tizen/common/verrari/template/ITemplate.java b/org.tizen.common.verrari/src/org/tizen/common/verrari/template/ITemplate.java
new file mode 100644
index 000000000..0f6f8e6f0
--- /dev/null
+++ b/org.tizen.common.verrari/src/org/tizen/common/verrari/template/ITemplate.java
@@ -0,0 +1,47 @@
+/*
+ * Verrari - TemplateEngine
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * Changhyun Lee <changhyun1.lee@samsung.com>
+ * Hyeongseok Heo <hyeongseok.heo@samsung.com>
+ * Kangho Kim <kh5325.kim@samsung.com>
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+
+package org.tizen.common.verrari.template;
+
+import java.io.IOException;
+import java.io.InputStream;
+
+/**
+ * ITemplate.
+ *
+ * Common Template Interface
+ *
+ * @author ChangHyun Lee{@literal <changhyun1.lee@samsung.com>} (S-Core)
+ */
+public interface ITemplate {
+
+ public Object getContainer();
+ public String getEncoding();
+ public InputStream open() throws IOException;
+
+}
diff --git a/org.tizen.common.verrari/src/org/tizen/common/verrari/template/ITemplateProvider.java b/org.tizen.common.verrari/src/org/tizen/common/verrari/template/ITemplateProvider.java
new file mode 100644
index 000000000..e1aba9ac4
--- /dev/null
+++ b/org.tizen.common.verrari/src/org/tizen/common/verrari/template/ITemplateProvider.java
@@ -0,0 +1,52 @@
+/*
+ * Verrari - TemplateEngine
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * Changhyun Lee <changhyun1.lee@samsung.com>
+ * Hyeongseok Heo <hyeongseok.heo@samsung.com>
+ * Kangho Kim <kh5325.kim@samsung.com>
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+
+package org.tizen.common.verrari.template;
+
+import java.io.File;
+import java.net.URI;
+import java.util.Map;
+
+/**
+ * ITemplateProvider.
+ *
+ * Management for template.
+ *
+ * @author ChangHyun Lee{@literal <changhyun1.lee@samsung.com>} (S-Core)
+ */
+public interface ITemplateProvider {
+
+ public void addTemplate(String key, ITemplate template);
+ public void addTemplate(String key, URI templateURI);
+ public void addTemplate(String key, File templateFile);
+ public ITemplate getTemplate(String key);
+ public ITemplate removeTemplate(String key);
+ public Map<String, ITemplate> getTemplates();
+ public boolean isEmpty();
+
+}
diff --git a/org.tizen.common.verrari/src/org/tizen/common/verrari/template/StaticTemplateProvider.java b/org.tizen.common.verrari/src/org/tizen/common/verrari/template/StaticTemplateProvider.java
new file mode 100644
index 000000000..8b9e57324
--- /dev/null
+++ b/org.tizen.common.verrari/src/org/tizen/common/verrari/template/StaticTemplateProvider.java
@@ -0,0 +1,88 @@
+/*
+ * Verrari - TemplateEngine
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * Changhyun Lee <changhyun1.lee@samsung.com>
+ * Hyeongseok Heo <hyeongseok.heo@samsung.com>
+ * Kangho Kim <kh5325.kim@samsung.com>
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+
+package org.tizen.common.verrari.template;
+
+import java.io.File;
+import java.net.URI;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * StaticTemplateProvider.
+ *
+ * Manage the templates.
+ *
+ * @author ChangHyun Lee{@literal <changhyun1.lee@samsung.com>} (S-Core)
+ */
+public class StaticTemplateProvider implements ITemplateProvider {
+
+ protected Map<String, ITemplate> templates;
+
+ public StaticTemplateProvider() {
+ templates = new HashMap<String, ITemplate>();
+ }
+
+ @Override
+ public void addTemplate(String key, ITemplate template) {
+ templates.put(key, template);
+ }
+
+ @Override
+ public void addTemplate(String key, URI templateURI) {
+ File file = new File(templateURI);
+ addTemplate(key, file);
+ }
+
+ @Override
+ public void addTemplate(String key, File templateFile) {
+ ITemplate fileTemplate = new FileTemplate(templateFile);
+ templates.put(key, fileTemplate);
+ }
+
+ @Override
+ public ITemplate getTemplate(String key) {
+ return templates.get(key);
+ }
+
+ @Override
+ public ITemplate removeTemplate(String key) {
+ return templates.remove(key);
+ }
+
+ @Override
+ public Map<String, ITemplate> getTemplates() {
+ return templates;
+ }
+
+ @Override
+ public boolean isEmpty() {
+ return templates.isEmpty();
+ }
+
+}
diff --git a/org.tizen.common.verrari/template/html/description.ftl b/org.tizen.common.verrari/template/html/description.ftl
new file mode 100644
index 000000000..b958b39fb
--- /dev/null
+++ b/org.tizen.common.verrari/template/html/description.ftl
@@ -0,0 +1,3 @@
+<!------------------------------------------------------------------------------------------------
+ Copyright ${description_date!"2012"} ${description_author!"author"} All rights reserved.
+-------------------------------------------------------------------------------------------------> \ No newline at end of file
diff --git a/org.tizen.common.verrari/template/html/index_html.ftl b/org.tizen.common.verrari/template/html/index_html.ftl
new file mode 100644
index 000000000..3e950db09
--- /dev/null
+++ b/org.tizen.common.verrari/template/html/index_html.ftl
@@ -0,0 +1,36 @@
+<#include "description.ftl">
+
+<!DOCTYPE html>
+<html>
+<head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0, target-densityDpi=device-dpi"/>
+ <meta name="description" content="${meta_description_content!"Tizen template generated by Tizen Web IDE"}"/>
+
+ <title>${index_html_title!'Title'}</title>
+
+<#if TizenWebUIFW_Enable?exists>
+${head_script_tizenwebuifw!""}
+
+ <!--NOTE:
+ Additional scripts and css files are to be placed here.
+ You can use jQuery namespace($) and all functionalities in jQuery
+ in your script. For example:
+
+ <script src="main.js"></script>
+ <link rel="stylesheet" href="my.css">
+
+ When you want to manipulate elements in your code, you have to
+ use domReady for your code to work properly, like this;
+
+ domReady(function(){ ... });
+ -->
+</#if>
+ <script type="text/javascript" src="./js/main.js"></script>
+ <link rel="stylesheet" type="text/css" href="./css/style.css"/>
+</head>
+
+<body>
+<#include "test_html_body.ftl">
+</body>
+</html>
diff --git a/org.tizen.common.verrari/template/html/index_html_body.ftl b/org.tizen.common.verrari/template/html/index_html_body.ftl
new file mode 100644
index 000000000..363eba556
--- /dev/null
+++ b/org.tizen.common.verrari/template/html/index_html_body.ftl
@@ -0,0 +1,77 @@
+<#if TizenWebUIFW_Enable?exists>
+ <#if test_html_body_tizenwebuifw_single?exists>
+ <div data-role="page">
+ <div data-role="header" data-position="fixed">
+ <h1>Single-Page Application </h1>
+ </div><!-- /header -->
+
+ <div data-role="content">
+ <p>This is a single page boilerplate template that you can copy to build your first Tizen Web UI Framework page.</p>
+ </div><!-- /content -->
+
+ <div data-role="footer" data-position="fixed">
+ <h4>Footer content</h4>
+ </div><!-- /footer -->
+ </div><!-- /page -->
+ <#elseif test_html_body_tizenwebuifw_multi?exists>
+ <!-- Start of first page: #one -->
+ <div data-role="page" id="one">
+ <div data-role="header" data-position="fixed">
+ <h1>Multi-Page Application</h1>
+ </div><!-- /header -->
+
+ <div data-role="content">
+ <h2>One</h2>
+ <p>
+ This is a multi-page boilerplate template that you can copy to build
+ your first Tizen Web UI Framework page. This template contains multiple "page"
+ containers inside.
+ </p>
+ <p>
+ You link to internal pages by referring to the ID of the page you
+ want to show. For example, to <a href="#two">link</a> to the page
+ with an ID of "two", my link would have a
+ <code>href="#two"</code>
+ in the code.
+ </p>
+ <h3>Show internal pages:</h3>
+ <p><a href="#two" data-role="button">Show page "two"</a></p>
+ <p><a href="#popup" data-role="button" aria-haspopup="true" data-rel="popupwindow">Show page "popup" (as a dialog)</a></p>
+
+ <div id="popup" data-role="popupwindow" data-style="center_title_1btn">
+ <p data-role="title">Popup</p>
+ <p data-role="text">Pop-up dialog box, a child window that blocks user interact to the parent windows</p>
+ <div data-role="button-bg"><a href="#" data-role="button" onclick="javascript:$('#popup').popupwindow('close');">Close</a></div>
+ </div>
+ </div><!-- /content -->
+
+ <div data-role="footer" data-position="fixed">
+ <h4>Page Footer</h4>
+ </div><!-- /footer -->
+ </div><!-- /page one -->
+
+ <!-- Start of second page: #two -->
+ <div data-role="page" id="two">
+ <div data-role="header" data-position="fixed">
+ <h1>Two</h1>
+ </div><!-- /header -->
+
+ <div data-role="content">
+ <h2>Two</h2>
+ <p>I have an id of "two" on my page container. I'm the second
+ page container in this multi-page template.</p>
+ <p><a href="#one" data-direction="reverse" data-role="button">Back to page "one"</a></p>
+ </div><!-- /content -->
+
+ <div data-role="footer" data-position="fixed">
+ <h4>Page Footer</h4>
+ </div><!-- /footer -->
+ </div><!-- /page two -->
+ </#if>
+<#else>
+ <header>
+ </header>
+
+ <footer>
+ </footer>
+</#if>
diff --git a/org.tizen.common.verrari/template/html/test.xml b/org.tizen.common.verrari/template/html/test.xml
new file mode 100644
index 000000000..c34813c03
--- /dev/null
+++ b/org.tizen.common.verrari/template/html/test.xml
@@ -0,0 +1,3 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<index_html_title>Title</index_html_title>
diff --git a/org.tizen.common.verrari/template/js/description.ftl b/org.tizen.common.verrari/template/js/description.ftl
new file mode 100644
index 000000000..c314648ac
--- /dev/null
+++ b/org.tizen.common.verrari/template/js/description.ftl
@@ -0,0 +1,3 @@
+/**
+ * Copyright ${description_date!"2012"} ${description_author!"author"} All rights reserved.
+ */
diff --git a/org.tizen.common.verrari/template/js/main_js.ftl b/org.tizen.common.verrari/template/js/main_js.ftl
new file mode 100644
index 000000000..3c8cdc807
--- /dev/null
+++ b/org.tizen.common.verrari/template/js/main_js.ftl
@@ -0,0 +1,10 @@
+<#if jsDescription?exists>
+<#include "template/js/description.ftl">
+</#if>
+//Initialize function
+var init = function () {
+ // TODO:: Do your initialization job
+ console.log("init() called");
+};
+// window.onload can work without <body onload="">
+window.onload = init;
diff --git a/org.tizen.common.verrari/test/src/org/tizen/common/verrari/engine/TemplateEngineFactoryTest.java b/org.tizen.common.verrari/test/src/org/tizen/common/verrari/engine/TemplateEngineFactoryTest.java
new file mode 100644
index 000000000..016f00bdd
--- /dev/null
+++ b/org.tizen.common.verrari/test/src/org/tizen/common/verrari/engine/TemplateEngineFactoryTest.java
@@ -0,0 +1,91 @@
+/*
+ * Verrari - TemplateEngine
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * Changhyun Lee <changhyun1.lee@samsung.com>
+ * Hyeongseok Heo <hyeongseok.heo@samsung.com>
+ * Kangho Kim <kh5325.kim@samsung.com>
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common.verrari.engine;
+
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+
+import org.junit.Test;
+import org.tizen.common.Factory;
+import org.tizen.common.verrari.engine.freemarker.FreemarkerTemplateEngine;
+import org.tizen.common.verrari.engine.jsoup.JsoupTemplateEngine;
+
+/**
+ * TemplateEngineFactoryTest.
+ *
+ * Test case for {@link TemplateEngineFactory}
+ *
+ * @author Changhyun Lee{@literal <changhyun1.lee@samsung.com>} (S-Core)
+ *
+ * @see TemplateEngineFactory
+ *
+ */
+public class TemplateEngineFactoryTest {
+
+ /**
+ * Test {@link TemplateEngineFactory#getInstance()}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see TemplateEngineFactory#getInstance()
+ */
+ @Test
+ public void test_getInstance() throws Exception {
+ Factory<ITemplateEngine> engineFactory = TemplateEngineFactory.getInstance();
+ assertNotNull(engineFactory);
+ }
+
+ /**
+ * Test {@link TemplateEngineFactory#create()}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see TemplateEngineFactory#create()
+ */
+ @Test
+ public void test_create() throws Exception {
+ ITemplateEngine engine = TemplateEngineFactory.getInstance().create();
+ assertNotNull(engine);
+ }
+
+ /**
+ * Test {@link TemplateEngineFactory#create(Class)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see TemplateEngineFactory#create(Class)
+ */
+ @Test
+ public void test_create2() throws Exception {
+ TemplateEngineFactory factory = new TemplateEngineFactory();
+ assertNull(factory.create(null));
+ assertNotNull(factory.create(FreemarkerTemplateEngine.class));
+ assertNotNull(factory.create(JsoupTemplateEngine.class));
+ }
+
+}
diff --git a/org.tizen.common.verrari/test/src/org/tizen/common/verrari/engine/freemarker/FreemarkerTemplateEngineTest.java b/org.tizen.common.verrari/test/src/org/tizen/common/verrari/engine/freemarker/FreemarkerTemplateEngineTest.java
new file mode 100644
index 000000000..0dbf9dce8
--- /dev/null
+++ b/org.tizen.common.verrari/test/src/org/tizen/common/verrari/engine/freemarker/FreemarkerTemplateEngineTest.java
@@ -0,0 +1,128 @@
+/*
+ * Verrari - TemplateEngine
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * Changhyun Lee <changhyun1.lee@samsung.com>
+ * Hyeongseok Heo <hyeongseok.heo@samsung.com>
+ * Kangho Kim <kh5325.kim@samsung.com>
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common.verrari.engine.freemarker;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.OutputStreamWriter;
+import java.util.HashMap;
+
+import org.junit.Test;
+import org.tizen.common.verrari.model.MapModel;
+import org.tizen.common.verrari.target.TargetGroup;
+import org.tizen.common.verrari.target.TargetUnit;
+import org.tizen.common.verrari.template.FileTemplate;
+import org.tizen.common.verrari.template.ITemplate;
+
+/**
+ * FreemarkerTemplateEngineTest.
+ *
+ * Test case for {@link FreemarkerTemplateEngine}
+ *
+ * @author Changhyun Lee{@literal <changhyun1.lee@samsung.com>} (S-Core)
+ *
+ * @see FreemarkerTemplateEngine
+ *
+ */
+public class FreemarkerTemplateEngineTest {
+
+ public String head =
+ "<#if TizenWebUIFW_Default?exists>" + "\n" +
+ " <script src=\"tizen-web-ui-fw/latest/js/jquery.js\"></script>" + "\n" +
+ " <script src=\"tizen-web-ui-fw/latest/js/tizen-web-ui-fw-libs.js\"></script>" + "\n" +
+ " <script src=\"tizen-web-ui-fw/latest/js/tizen-web-ui-fw.js\" data-framework-theme=\"tizen-gray\" data-framework-viewport-scale=\"false\"></script>" + "\n" +
+ "<#elseif TizenWebUIFW_PATH?exists>" + "\n" +
+ " <script src=\"${TizenWebUIFW_JQuery?default(\"/usr/share/tizen-web-ui-fw/latest/js/jquery.js\")}\"></script>" + "\n" +
+ " <script src=\"${TizenWebUIFW_Libs?default(\"/usr/share/tizen-web-ui-fw/latest/js/tizen-web-ui-fw-libs.js\")}\"></script>" + "\n" +
+ " <script src=\"${TizenWebUIFW_JS?default(\"/usr/share/tizen-web-ui-fw/latest/js/tizen-web-ui-fw.js\")}\" data-framework-theme=\"${theme?default(\"tizen-gray\")}\" data-framework-viewport-scale=\"${scale?default(\"false\")}\"></script>" + "\n" +
+ "</#if>";
+
+ /**
+ * Test {@link FreemarkerTemplateEngine#generate(TargetUnit unit)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see FreemarkerTemplateEngine#generate(TargetUnit unit)
+ */
+ @Test
+ public void test_generate() throws Exception {
+ FreemarkerTemplateEngine engine = new FreemarkerTemplateEngine();
+ engine.setSharedVariable("description_date", "2012");
+ engine.setSharedVariable("description_author", "changhyun1.lee@samsung.com");
+
+ ITemplate template = new FileTemplate(new File("./test/src/org/tizen/common/verrari/engine/freemarker/test_html.ftl"));
+ engine.getTemplateProvider().addTemplate("testHtmlTemplate", template);
+
+ MapModel mapModel = new MapModel(new HashMap<Object, Object>());
+ mapModel.put("index_html_title", "Tizen Empty");
+ engine.getModelProvider().addModel("testEmptyModel", mapModel);
+
+ MapModel mapModel2 = new MapModel(new HashMap<Object, Object>());
+ mapModel2.put("index_html_title", "Tizen Web UI FW - Single");
+ mapModel2.put("TizenWebUIFW_Enable", "");
+ mapModel2.put("head_script_tizenwebuifw", head);
+ mapModel2.put("test_html_body_tizenwebuifw_single", "");
+ engine.getModelProvider().addModel("testTizenSingleModel", mapModel2);
+
+ MapModel mapModel3 = new MapModel(new HashMap<Object, Object>());
+ mapModel3.put("index_html_title", "Tizen Web UI FW - Multi");
+ mapModel3.put("TizenWebUIFW_Enable", "");
+ mapModel3.put("head_script_tizenwebuifw", head);
+ mapModel3.put("test_html_body_tizenwebuifw_multi", "");
+ engine.getModelProvider().addModel("testTizenMultiModel", mapModel3);
+
+ File destinationEmptyFile = new File("./test/src/org/tizen/common/verrari/engine/freemarker/test.html");
+ File destinationTizenSingleFile = new File("./test/src/org/tizen/common/verrari/engine/freemarker/testTizenSingle.html");
+ File destinationTizenMultiFile = new File("./test/src/org/tizen/common/verrari/engine/freemarker/testTizenMulti.html");
+
+ TargetGroup group = new TargetGroup();
+ group.addTargetUnit(new TargetUnit("testHtmlTemplate", "testEmptyModel", new OutputStreamWriter(new FileOutputStream(destinationEmptyFile)), "UTF-8"));
+ group.addTargetUnit(new TargetUnit("testHtmlTemplate", "testTizenSingleModel", new OutputStreamWriter(new FileOutputStream(destinationTizenSingleFile)), "UTF-8"));
+ group.addTargetUnit(new TargetUnit("testHtmlTemplate", "testTizenMultiModel", new OutputStreamWriter(new FileOutputStream(destinationTizenMultiFile)), "UTF-8"));
+
+ engine.genearteGroup(group);
+ //TargetUnit unit = new TargetUnit("testHtmlTemplate", "testHtmlModel", new OutputStreamWriter(System.out), "UTF-8");
+
+ ITemplate regenTemplate = new FileTemplate(new File("./test/src/org/tizen/common/verrari/engine/freemarker/testTizenSingle.html"));
+ engine.getTemplateProvider().addTemplate("regenHtmlTemplate", regenTemplate);
+ MapModel finalMapModel = new MapModel(new HashMap<Object, Object>());
+ finalMapModel.put("TizenWebUIFW_PATH", "");
+ engine.getModelProvider().addModel("testFinalMapModel", finalMapModel);
+ File finalTizenSingleFile = new File("./test/src/org/tizen/common/verrari/engine/freemarker/testTizenSingle2.html");
+ TargetUnit unit = new TargetUnit("regenHtmlTemplate", "testFinalMapModel", new OutputStreamWriter(new FileOutputStream(finalTizenSingleFile)), "UTF-8");
+ engine.generate(unit);
+
+// description_date
+// description_author
+// head_script_tizen-web-ui-fw
+// TizenWebUIFW_Enable
+// test_html_body_tizenwebuifw_single
+// test_html_body_tizenwebuifw_multi
+
+ }
+}
diff --git a/org.tizen.common.verrari/test/src/org/tizen/common/verrari/engine/freemarker/description.ftl b/org.tizen.common.verrari/test/src/org/tizen/common/verrari/engine/freemarker/description.ftl
new file mode 100644
index 000000000..b958b39fb
--- /dev/null
+++ b/org.tizen.common.verrari/test/src/org/tizen/common/verrari/engine/freemarker/description.ftl
@@ -0,0 +1,3 @@
+<!------------------------------------------------------------------------------------------------
+ Copyright ${description_date!"2012"} ${description_author!"author"} All rights reserved.
+-------------------------------------------------------------------------------------------------> \ No newline at end of file
diff --git a/org.tizen.common.verrari/test/src/org/tizen/common/verrari/engine/freemarker/test.html b/org.tizen.common.verrari/test/src/org/tizen/common/verrari/engine/freemarker/test.html
new file mode 100644
index 000000000..bfce1b08b
--- /dev/null
+++ b/org.tizen.common.verrari/test/src/org/tizen/common/verrari/engine/freemarker/test.html
@@ -0,0 +1,24 @@
+<!------------------------------------------------------------------------------------------------
+ Copyright 2012 changhyun1.lee@samsung.com All rights reserved.
+------------------------------------------------------------------------------------------------->
+<!DOCTYPE html>
+<html>
+<head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0, target-densityDpi=device-dpi"/>
+ <meta name="description" content="Tizen template generated by Tizen Web IDE"/>
+
+ <title>Tizen Empty</title>
+
+ <script type="text/javascript" src="./js/main.js"></script>
+ <link rel="stylesheet" type="text/css" href="./css/style.css"/>
+</head>
+
+<body>
+ <header>
+ </header>
+
+ <footer>
+ </footer>
+</body>
+</html>
diff --git a/org.tizen.common.verrari/test/src/org/tizen/common/verrari/engine/freemarker/testTizenMulti.html b/org.tizen.common.verrari/test/src/org/tizen/common/verrari/engine/freemarker/testTizenMulti.html
new file mode 100644
index 000000000..787866970
--- /dev/null
+++ b/org.tizen.common.verrari/test/src/org/tizen/common/verrari/engine/freemarker/testTizenMulti.html
@@ -0,0 +1,95 @@
+<!------------------------------------------------------------------------------------------------
+ Copyright 2012 changhyun1.lee@samsung.com All rights reserved.
+------------------------------------------------------------------------------------------------->
+<!DOCTYPE html>
+<html>
+<head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0, target-densityDpi=device-dpi"/>
+ <meta name="description" content="Tizen template generated by Tizen Web IDE"/>
+
+ <title>Tizen Web UI FW - Multi</title>
+
+<#if TizenWebUIFW_Default?exists>
+ <script src="tizen-web-ui-fw/latest/js/jquery.js"></script>
+ <script src="tizen-web-ui-fw/latest/js/tizen-web-ui-fw-libs.js"></script>
+ <script src="tizen-web-ui-fw/latest/js/tizen-web-ui-fw.js" data-framework-theme="tizen-gray" data-framework-viewport-scale="false"></script>
+<#elseif TizenWebUIFW_PATH?exists>
+ <script src="${TizenWebUIFW_JQuery?default("/usr/share/tizen-web-ui-fw/latest/js/jquery.js")}"></script>
+ <script src="${TizenWebUIFW_Libs?default("/usr/share/tizen-web-ui-fw/latest/js/tizen-web-ui-fw-libs.js")}"></script>
+ <script src="${TizenWebUIFW_JS?default("/usr/share/tizen-web-ui-fw/latest/js/tizen-web-ui-fw.js")}" data-framework-theme="${theme?default("tizen-gray")}" data-framework-viewport-scale="${scale?default("false")}"></script>
+</#if>
+
+ <!--NOTE:
+ Additional scripts and css files are to be placed here.
+ You can use jQuery namespace($) and all functionalities in jQuery
+ in your script. For example:
+
+ <script src="main.js"></script>
+ <link rel="stylesheet" href="my.css">
+
+ When you want to manipulate elements in your code, you have to
+ use domReady for your code to work properly, like this;
+
+ domReady(function(){ ... });
+ -->
+ <script type="text/javascript" src="./js/main.js"></script>
+ <link rel="stylesheet" type="text/css" href="./css/style.css"/>
+</head>
+
+<body>
+ <!-- Start of first page: #one -->
+ <div data-role="page" id="one">
+ <div data-role="header" data-position="fixed">
+ <h1>Multi-Page Application</h1>
+ </div><!-- /header -->
+
+ <div data-role="content">
+ <h2>One</h2>
+ <p>
+ This is a multi-page boilerplate template that you can copy to build
+ your first Tizen Web UI Framework page. This template contains multiple "page"
+ containers inside.
+ </p>
+ <p>
+ You link to internal pages by referring to the ID of the page you
+ want to show. For example, to <a href="#two">link</a> to the page
+ with an ID of "two", my link would have a
+ <code>href="#two"</code>
+ in the code.
+ </p>
+ <h3>Show internal pages:</h3>
+ <p><a href="#two" data-role="button">Show page "two"</a></p>
+ <p><a href="#popup" data-role="button" aria-haspopup="true" data-rel="popupwindow">Show page "popup" (as a dialog)</a></p>
+
+ <div id="popup" data-role="popupwindow" data-style="center_title_1btn">
+ <p data-role="title">Popup</p>
+ <p data-role="text">Pop-up dialog box, a child window that blocks user interact to the parent windows</p>
+ <div data-role="button-bg"><a href="#" data-role="button" onclick="javascript:$('#popup').popupwindow('close');">Close</a></div>
+ </div>
+ </div><!-- /content -->
+
+ <div data-role="footer" data-position="fixed">
+ <h4>Page Footer</h4>
+ </div><!-- /footer -->
+ </div><!-- /page one -->
+
+ <!-- Start of second page: #two -->
+ <div data-role="page" id="two">
+ <div data-role="header" data-position="fixed">
+ <h1>Two</h1>
+ </div><!-- /header -->
+
+ <div data-role="content">
+ <h2>Two</h2>
+ <p>I have an id of "two" on my page container. I'm the second
+ page container in this multi-page template.</p>
+ <p><a href="#one" data-direction="reverse" data-role="button">Back to page "one"</a></p>
+ </div><!-- /content -->
+
+ <div data-role="footer" data-position="fixed">
+ <h4>Page Footer</h4>
+ </div><!-- /footer -->
+ </div><!-- /page two -->
+</body>
+</html>
diff --git a/org.tizen.common.verrari/test/src/org/tizen/common/verrari/engine/freemarker/testTizenSingle.html b/org.tizen.common.verrari/test/src/org/tizen/common/verrari/engine/freemarker/testTizenSingle.html
new file mode 100644
index 000000000..8a6159fbc
--- /dev/null
+++ b/org.tizen.common.verrari/test/src/org/tizen/common/verrari/engine/freemarker/testTizenSingle.html
@@ -0,0 +1,55 @@
+<!------------------------------------------------------------------------------------------------
+ Copyright 2012 changhyun1.lee@samsung.com All rights reserved.
+------------------------------------------------------------------------------------------------->
+<!DOCTYPE html>
+<html>
+<head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0, target-densityDpi=device-dpi"/>
+ <meta name="description" content="Tizen template generated by Tizen Web IDE"/>
+
+ <title>Tizen Web UI FW - Single</title>
+
+<#if TizenWebUIFW_Default?exists>
+ <script src="tizen-web-ui-fw/latest/js/jquery.js"></script>
+ <script src="tizen-web-ui-fw/latest/js/tizen-web-ui-fw-libs.js"></script>
+ <script src="tizen-web-ui-fw/latest/js/tizen-web-ui-fw.js" data-framework-theme="tizen-gray" data-framework-viewport-scale="false"></script>
+<#elseif TizenWebUIFW_PATH?exists>
+ <script src="${TizenWebUIFW_JQuery?default("/usr/share/tizen-web-ui-fw/latest/js/jquery.js")}"></script>
+ <script src="${TizenWebUIFW_Libs?default("/usr/share/tizen-web-ui-fw/latest/js/tizen-web-ui-fw-libs.js")}"></script>
+ <script src="${TizenWebUIFW_JS?default("/usr/share/tizen-web-ui-fw/latest/js/tizen-web-ui-fw.js")}" data-framework-theme="${theme?default("tizen-gray")}" data-framework-viewport-scale="${scale?default("false")}"></script>
+</#if>
+
+ <!--NOTE:
+ Additional scripts and css files are to be placed here.
+ You can use jQuery namespace($) and all functionalities in jQuery
+ in your script. For example:
+
+ <script src="main.js"></script>
+ <link rel="stylesheet" href="my.css">
+
+ When you want to manipulate elements in your code, you have to
+ use domReady for your code to work properly, like this;
+
+ domReady(function(){ ... });
+ -->
+ <script type="text/javascript" src="./js/main.js"></script>
+ <link rel="stylesheet" type="text/css" href="./css/style.css"/>
+</head>
+
+<body>
+ <div data-role="page">
+ <div data-role="header" data-position="fixed">
+ <h1>Single-Page Application </h1>
+ </div><!-- /header -->
+
+ <div data-role="content">
+ <p>This is a single page boilerplate template that you can copy to build your first Tizen Web UI Framework page.</p>
+ </div><!-- /content -->
+
+ <div data-role="footer" data-position="fixed">
+ <h4>Footer content</h4>
+ </div><!-- /footer -->
+ </div><!-- /page -->
+</body>
+</html>
diff --git a/org.tizen.common.verrari/test/src/org/tizen/common/verrari/engine/freemarker/testTizenSingle2.html b/org.tizen.common.verrari/test/src/org/tizen/common/verrari/engine/freemarker/testTizenSingle2.html
new file mode 100644
index 000000000..f3dd7fef7
--- /dev/null
+++ b/org.tizen.common.verrari/test/src/org/tizen/common/verrari/engine/freemarker/testTizenSingle2.html
@@ -0,0 +1,49 @@
+<!------------------------------------------------------------------------------------------------
+ Copyright 2012 changhyun1.lee@samsung.com All rights reserved.
+------------------------------------------------------------------------------------------------->
+<!DOCTYPE html>
+<html>
+<head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0, target-densityDpi=device-dpi"/>
+ <meta name="description" content="Tizen template generated by Tizen Web IDE"/>
+
+ <title>Tizen Web UI FW - Single</title>
+
+ <script src="/usr/share/tizen-web-ui-fw/latest/js/jquery.js"></script>
+ <script src="/usr/share/tizen-web-ui-fw/latest/js/tizen-web-ui-fw-libs.js"></script>
+ <script src="/usr/share/tizen-web-ui-fw/latest/js/tizen-web-ui-fw.js" data-framework-theme="tizen-gray" data-framework-viewport-scale="false"></script>
+
+ <!--NOTE:
+ Additional scripts and css files are to be placed here.
+ You can use jQuery namespace($) and all functionalities in jQuery
+ in your script. For example:
+
+ <script src="main.js"></script>
+ <link rel="stylesheet" href="my.css">
+
+ When you want to manipulate elements in your code, you have to
+ use domReady for your code to work properly, like this;
+
+ domReady(function(){ ... });
+ -->
+ <script type="text/javascript" src="./js/main.js"></script>
+ <link rel="stylesheet" type="text/css" href="./css/style.css"/>
+</head>
+
+<body>
+ <div data-role="page">
+ <div data-role="header" data-position="fixed">
+ <h1>Single-Page Application </h1>
+ </div><!-- /header -->
+
+ <div data-role="content">
+ <p>This is a single page boilerplate template that you can copy to build your first Tizen Web UI Framework page.</p>
+ </div><!-- /content -->
+
+ <div data-role="footer" data-position="fixed">
+ <h4>Footer content</h4>
+ </div><!-- /footer -->
+ </div><!-- /page -->
+</body>
+</html>
diff --git a/org.tizen.common.verrari/test/src/org/tizen/common/verrari/engine/freemarker/test_html.ftl b/org.tizen.common.verrari/test/src/org/tizen/common/verrari/engine/freemarker/test_html.ftl
new file mode 100644
index 000000000..3e950db09
--- /dev/null
+++ b/org.tizen.common.verrari/test/src/org/tizen/common/verrari/engine/freemarker/test_html.ftl
@@ -0,0 +1,36 @@
+<#include "description.ftl">
+
+<!DOCTYPE html>
+<html>
+<head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0, target-densityDpi=device-dpi"/>
+ <meta name="description" content="${meta_description_content!"Tizen template generated by Tizen Web IDE"}"/>
+
+ <title>${index_html_title!'Title'}</title>
+
+<#if TizenWebUIFW_Enable?exists>
+${head_script_tizenwebuifw!""}
+
+ <!--NOTE:
+ Additional scripts and css files are to be placed here.
+ You can use jQuery namespace($) and all functionalities in jQuery
+ in your script. For example:
+
+ <script src="main.js"></script>
+ <link rel="stylesheet" href="my.css">
+
+ When you want to manipulate elements in your code, you have to
+ use domReady for your code to work properly, like this;
+
+ domReady(function(){ ... });
+ -->
+</#if>
+ <script type="text/javascript" src="./js/main.js"></script>
+ <link rel="stylesheet" type="text/css" href="./css/style.css"/>
+</head>
+
+<body>
+<#include "test_html_body.ftl">
+</body>
+</html>
diff --git a/org.tizen.common.verrari/test/src/org/tizen/common/verrari/engine/freemarker/test_html_body.ftl b/org.tizen.common.verrari/test/src/org/tizen/common/verrari/engine/freemarker/test_html_body.ftl
new file mode 100644
index 000000000..363eba556
--- /dev/null
+++ b/org.tizen.common.verrari/test/src/org/tizen/common/verrari/engine/freemarker/test_html_body.ftl
@@ -0,0 +1,77 @@
+<#if TizenWebUIFW_Enable?exists>
+ <#if test_html_body_tizenwebuifw_single?exists>
+ <div data-role="page">
+ <div data-role="header" data-position="fixed">
+ <h1>Single-Page Application </h1>
+ </div><!-- /header -->
+
+ <div data-role="content">
+ <p>This is a single page boilerplate template that you can copy to build your first Tizen Web UI Framework page.</p>
+ </div><!-- /content -->
+
+ <div data-role="footer" data-position="fixed">
+ <h4>Footer content</h4>
+ </div><!-- /footer -->
+ </div><!-- /page -->
+ <#elseif test_html_body_tizenwebuifw_multi?exists>
+ <!-- Start of first page: #one -->
+ <div data-role="page" id="one">
+ <div data-role="header" data-position="fixed">
+ <h1>Multi-Page Application</h1>
+ </div><!-- /header -->
+
+ <div data-role="content">
+ <h2>One</h2>
+ <p>
+ This is a multi-page boilerplate template that you can copy to build
+ your first Tizen Web UI Framework page. This template contains multiple "page"
+ containers inside.
+ </p>
+ <p>
+ You link to internal pages by referring to the ID of the page you
+ want to show. For example, to <a href="#two">link</a> to the page
+ with an ID of "two", my link would have a
+ <code>href="#two"</code>
+ in the code.
+ </p>
+ <h3>Show internal pages:</h3>
+ <p><a href="#two" data-role="button">Show page "two"</a></p>
+ <p><a href="#popup" data-role="button" aria-haspopup="true" data-rel="popupwindow">Show page "popup" (as a dialog)</a></p>
+
+ <div id="popup" data-role="popupwindow" data-style="center_title_1btn">
+ <p data-role="title">Popup</p>
+ <p data-role="text">Pop-up dialog box, a child window that blocks user interact to the parent windows</p>
+ <div data-role="button-bg"><a href="#" data-role="button" onclick="javascript:$('#popup').popupwindow('close');">Close</a></div>
+ </div>
+ </div><!-- /content -->
+
+ <div data-role="footer" data-position="fixed">
+ <h4>Page Footer</h4>
+ </div><!-- /footer -->
+ </div><!-- /page one -->
+
+ <!-- Start of second page: #two -->
+ <div data-role="page" id="two">
+ <div data-role="header" data-position="fixed">
+ <h1>Two</h1>
+ </div><!-- /header -->
+
+ <div data-role="content">
+ <h2>Two</h2>
+ <p>I have an id of "two" on my page container. I'm the second
+ page container in this multi-page template.</p>
+ <p><a href="#one" data-direction="reverse" data-role="button">Back to page "one"</a></p>
+ </div><!-- /content -->
+
+ <div data-role="footer" data-position="fixed">
+ <h4>Page Footer</h4>
+ </div><!-- /footer -->
+ </div><!-- /page two -->
+ </#if>
+<#else>
+ <header>
+ </header>
+
+ <footer>
+ </footer>
+</#if>
diff --git a/org.tizen.common.verrari/test/src/org/tizen/common/verrari/engine/jsoup/JsoupTemplateEngineTest.java b/org.tizen.common.verrari/test/src/org/tizen/common/verrari/engine/jsoup/JsoupTemplateEngineTest.java
new file mode 100644
index 000000000..b395047b9
--- /dev/null
+++ b/org.tizen.common.verrari/test/src/org/tizen/common/verrari/engine/jsoup/JsoupTemplateEngineTest.java
@@ -0,0 +1,54 @@
+package org.tizen.common.verrari.engine.jsoup;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.OutputStreamWriter;
+import java.util.HashMap;
+
+import org.jsoup.nodes.Attribute;
+import org.jsoup.nodes.Attributes;
+import org.junit.Test;
+import org.tizen.common.verrari.model.MapModel;
+import org.tizen.common.verrari.target.TargetUnit;
+import org.tizen.common.verrari.template.FileTemplate;
+import org.tizen.common.verrari.template.ITemplate;
+
+public class JsoupTemplateEngineTest {
+
+ /**
+ * Test {@link JsoupTemplateEngine#generate(TargetUnit unit)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see JsoupTemplateEngine#generate(TargetUnit unit)
+ */
+ @Test
+ public void test_generate() throws Exception {
+ JsoupTemplateEngine engine = new JsoupTemplateEngine();
+ ITemplate template = new FileTemplate(new File("./test/src/org/tizen/common/verrari/engine/jsoup/TizenSingle.html"));
+ engine.getTemplateProvider().addTemplate("jsoupTemplate", template);
+
+ // selector - http://jsoup.org/apidocs/org/jsoup/select/Selector.html
+ MapModel mapModel = new MapModel(new HashMap<Object, Object>());
+ Attribute jquery = new Attribute("src", "/usr/share/tizen-web-ui-fw/latest/js/jquery.js");
+ mapModel.put("script[src$=tizen-web-ui-fw/latest/js/jquery.js]", jquery);
+
+ Attribute tizenwebuifwlibs = new Attribute("src", "/usr/share/tizen-web-ui-fw/latest/js/tizen-web-ui-fw-libs.js");
+ mapModel.put("script[src$=tizen-web-ui-fw/latest/js/tizen-web-ui-fw-libs.js]", tizenwebuifwlibs);
+
+ Attributes tizenwebuifw = new Attributes();
+ tizenwebuifw.put("src", "/usr/share/tizen-web-ui-fw/latest/js/tizen-web-ui-fw.js");
+ tizenwebuifw.put("data-framework-theme", "tizen-white");
+ tizenwebuifw.put("data-framework-viewport-scale", "true");
+ mapModel.put("script[src$=tizen-web-ui-fw/latest/js/tizen-web-ui-fw.js]", tizenwebuifw);
+
+ engine.getModelProvider().addModel("jsoupModel", mapModel);
+
+ File genTizenSingleFile = new File("./test/src/org/tizen/common/verrari/engine/jsoup/genTizenSingle.html");
+ TargetUnit unit = new TargetUnit("jsoupTemplate", "jsoupModel", new OutputStreamWriter(new FileOutputStream(genTizenSingleFile.getPath())), "UTF-8");
+ //TargetUnit unit = new TargetUnit("jsonTemplate", "jsonModel", new OutputStreamWriter(System.out), "UTF-8");
+ engine.generate(unit);
+
+ }
+
+}
diff --git a/org.tizen.common.verrari/test/src/org/tizen/common/verrari/engine/jsoup/TizenSingle.html b/org.tizen.common.verrari/test/src/org/tizen/common/verrari/engine/jsoup/TizenSingle.html
new file mode 100644
index 000000000..587dae8ca
--- /dev/null
+++ b/org.tizen.common.verrari/test/src/org/tizen/common/verrari/engine/jsoup/TizenSingle.html
@@ -0,0 +1,46 @@
+<!--
+ Copyright 2012 changhyun1.lee@samsung.com All rights reserved.
+-------------------------------------------------------------------------------------------------><!DOCTYPE html>
+<html>
+ <head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0, target-densityDpi=device-dpi" />
+ <meta name="description" content="Tizen template generated by Tizen Web IDE" />
+ <title>Tizen Web UI FW - Single</title>
+ <script src="./tizen-web-ui-fw/latest/js/jquery.js"></script>
+ <script src="./tizen-web-ui-fw/latest/js/tizen-web-ui-fw-libs.js"></script>
+ <script src="./tizen-web-ui-fw/latest/js/tizen-web-ui-fw.js" data-framework-theme="tizen-gray" data-framework-viewport-scale="false"></script>
+ <!--NOTE:
+ Additional scripts and css files are to be placed here.
+ You can use jQuery namespace($) and all functionalities in jQuery
+ in your script. For example:
+
+ <script src="main.js"></script>
+ <link rel="stylesheet" href="my.css">
+
+ When you want to manipulate elements in your code, you have to
+ use domReady for your code to work properly, like this;
+
+ domReady(function(){ ... });
+ -->
+ <script type="text/javascript" src="./js/main.js"></script>
+ <link rel="stylesheet" type="text/css" href="./css/style.css" />
+ </head>
+ <body>
+ <div data-role="page">
+ <div data-role="header" data-position="fixed">
+ <h1>Single-Page Application </h1>
+ </div>
+ <!-- /header -->
+ <div data-role="content">
+ <p>This is a single page boilerplate template that you can copy to build your first Tizen Web UI Framework page.</p>
+ </div>
+ <!-- /content -->
+ <div data-role="footer" data-position="fixed">
+ <h4>Footer content</h4>
+ </div>
+ <!-- /footer -->
+ </div>
+ <!-- /page -->
+ </body>
+</html> \ No newline at end of file
diff --git a/org.tizen.common.verrari/test/src/org/tizen/common/verrari/engine/jsoup/genTizenSingle.html b/org.tizen.common.verrari/test/src/org/tizen/common/verrari/engine/jsoup/genTizenSingle.html
new file mode 100644
index 000000000..79f5d74b1
--- /dev/null
+++ b/org.tizen.common.verrari/test/src/org/tizen/common/verrari/engine/jsoup/genTizenSingle.html
@@ -0,0 +1,46 @@
+<!--
+ Copyright 2012 changhyun1.lee@samsung.com All rights reserved.
+-------------------------------------------------------------------------------------------------><!DOCTYPE html>
+<html>
+ <head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0, target-densityDpi=device-dpi" />
+ <meta name="description" content="Tizen template generated by Tizen Web IDE" />
+ <title>Tizen Web UI FW - Single</title>
+ <script src="/usr/share/tizen-web-ui-fw/latest/js/jquery.js"></script>
+ <script src="/usr/share/tizen-web-ui-fw/latest/js/tizen-web-ui-fw-libs.js"></script>
+ <script src="/usr/share/tizen-web-ui-fw/latest/js/tizen-web-ui-fw.js" data-framework-theme="tizen-white" data-framework-viewport-scale="true"></script>
+ <!--NOTE:
+ Additional scripts and css files are to be placed here.
+ You can use jQuery namespace($) and all functionalities in jQuery
+ in your script. For example:
+
+ <script src="main.js"></script>
+ <link rel="stylesheet" href="my.css">
+
+ When you want to manipulate elements in your code, you have to
+ use domReady for your code to work properly, like this;
+
+ domReady(function(){ ... });
+ -->
+ <script type="text/javascript" src="./js/main.js"></script>
+ <link rel="stylesheet" type="text/css" href="./css/style.css" />
+ </head>
+ <body>
+ <div data-role="page">
+ <div data-role="header" data-position="fixed">
+ <h1>Single-Page Application </h1>
+ </div>
+ <!-- /header -->
+ <div data-role="content">
+ <p>This is a single page boilerplate template that you can copy to build your first Tizen Web UI Framework page.</p>
+ </div>
+ <!-- /content -->
+ <div data-role="footer" data-position="fixed">
+ <h4>Footer content</h4>
+ </div>
+ <!-- /footer -->
+ </div>
+ <!-- /page -->
+ </body>
+</html> \ No newline at end of file
diff --git a/org.tizen.common.verrari/test/src/org/tizen/common/verrari/target/TargetGruopTest.java b/org.tizen.common.verrari/test/src/org/tizen/common/verrari/target/TargetGruopTest.java
new file mode 100644
index 000000000..73472c546
--- /dev/null
+++ b/org.tizen.common.verrari/test/src/org/tizen/common/verrari/target/TargetGruopTest.java
@@ -0,0 +1,165 @@
+/*
+ * Verrari - TemplateEngine
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * Changhyun Lee <changhyun1.lee@samsung.com>
+ * Hyeongseok Heo <hyeongseok.heo@samsung.com>
+ * Kangho Kim <kh5325.kim@samsung.com>
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common.verrari.target;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+import java.io.IOException;
+import java.io.OutputStreamWriter;
+import java.io.Writer;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+/**
+ * TargetGruopTest.
+ *
+ * Test case for {@link TargetGroup}
+ *
+ * @author Changhyun Lee{@literal <changhyun1.lee@samsung.com>} (S-Core)
+ *
+ * @see TargetGroup
+ *
+ */
+public class TargetGruopTest {
+
+ protected TargetGroup group;
+
+ @Before
+ public void setUp() {
+ group = new TargetGroup();
+ }
+
+ @After
+ public void tearDown() throws IOException {
+ }
+
+ /**
+ * Test {@link TargetGroup#TargetGroup()}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see TargetGroup#TargetGroup()
+ */
+ @Test
+ public void test_TargetGroup() throws Exception {
+ assertNotNull(group.getTargetUnits());
+ }
+
+ /**
+ * Test {@link TargetGroup#getTargetUnits()}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see TargetGroup#getTargetUnits()
+ */
+ @Test
+ public void test_getTargetUnits() throws Exception {
+ assertNotNull(group.getTargetUnits());
+ }
+
+ /**
+ * Test {@link TargetGroup#addTargetUnit(TargetUnit)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see TargetGroup#addTargetUnit(TargetUnit)
+ */
+ @Test
+ public void test_addTargetUnit() throws Exception {
+ assertFalse(group.addTargetUnit(null));
+
+ Writer writer = null;
+ try {
+ writer = new OutputStreamWriter(System.out);
+ TargetUnit unit = new TargetUnit("templatekey", "modelkey", writer, null);
+ assertTrue(group.addTargetUnit(unit));
+ } catch (Exception e) {
+ throw e;
+ } finally {
+ if (writer != null) {
+ writer.close();
+ }
+ }
+ }
+
+ /**
+ * Test {@link TargetGroup#removeTargetunit(TargetUnit)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see TargetGroup#removeTargetunit(TargetUnit)
+ */
+ @Test
+ public void test_removeTargetunit() throws Exception {
+ assertFalse(group.removeTargetunit(null));
+
+ Writer writer = null;
+ try {
+ writer = new OutputStreamWriter(System.out);
+ TargetUnit unit = new TargetUnit("templatekey", "modelkey", writer, null);
+ assertTrue(group.addTargetUnit(unit));
+ assertTrue(group.removeTargetunit(unit));
+ } catch (Exception e) {
+ throw e;
+ } finally {
+ if (writer != null) {
+ writer.close();
+ }
+ }
+ }
+
+ /**
+ * Test {@link TargetGroup#isEmpty()}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see TargetGroup#isEmpty()
+ */
+ @Test
+ public void test_isEmpty() throws Exception {
+ assertTrue(group.isEmpty());
+
+ Writer writer = null;
+ try {
+ writer = new OutputStreamWriter(System.out);
+ TargetUnit unit = new TargetUnit("templatekey", "modelkey", writer, null);
+ assertTrue(group.addTargetUnit(unit));
+ assertFalse(group.isEmpty());
+ } catch (Exception e) {
+ throw e;
+ } finally {
+ if (writer != null) {
+ writer.close();
+ }
+ }
+ }
+}
diff --git a/org.tizen.common.verrari/test/src/org/tizen/common/verrari/target/TargetUnitTest.java b/org.tizen.common.verrari/test/src/org/tizen/common/verrari/target/TargetUnitTest.java
new file mode 100644
index 000000000..75f2d178f
--- /dev/null
+++ b/org.tizen.common.verrari/test/src/org/tizen/common/verrari/target/TargetUnitTest.java
@@ -0,0 +1,230 @@
+/*
+ * Verrari - TemplateEngine
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * Changhyun Lee <changhyun1.lee@samsung.com>
+ * Hyeongseok Heo <hyeongseok.heo@samsung.com>
+ * Kangho Kim <kh5325.kim@samsung.com>
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common.verrari.target;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.fail;
+
+import java.io.IOException;
+import java.io.OutputStreamWriter;
+import java.io.Writer;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+/**
+ * TargetUnitTest.
+ *
+ * Test case for {@link TargetUnit}
+ *
+ * @author Changhyun Lee{@literal <changhyun1.lee@samsung.com>} (S-Core)
+ *
+ * @see TargetUnit
+ *
+ */
+public class TargetUnitTest {
+
+ protected TargetUnit unit;
+ protected Writer writer;
+
+ @Before
+ public void setUp() {
+ writer = new OutputStreamWriter(System.out);
+ unit = new TargetUnit("templateKey", "modelKey", writer, "UTF-8");
+ }
+
+ @After
+ public void tearDown() throws IOException {
+ if (writer != null) {
+ writer.close();
+ }
+ }
+
+ /**
+ * Test {@link TargetUnit#TargetUnit(String, String, Writer, String)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see TargetUnit#TargetUnit(String, String, Writer, String)
+ */
+ @Test
+ public void test_TargetUnit() throws Exception {
+ @SuppressWarnings("unused")
+ TargetUnit tempUnit;
+
+ try {
+ tempUnit = new TargetUnit("templateKey", "modelKey", writer, null);
+ } catch (Exception e) {
+ throw e;
+ }
+
+ try {
+ tempUnit = new TargetUnit(null, null, null, null);
+ fail( "TargetUnit must throw exception" );
+ } catch (Exception e) {
+ }
+
+ try {
+ tempUnit = new TargetUnit("templateKey", "modelKey", null, null);
+ fail( "TargetUnit must throw exception" );
+ } catch (Exception e) {
+ }
+
+ try {
+ tempUnit = new TargetUnit("templateKey", null, writer, null);
+ fail( "TargetUnit must throw exception" );
+ } catch (Exception e) {
+ }
+
+ try {
+ tempUnit = new TargetUnit(null, "modelKey", writer, null);
+ fail( "TargetUnit must throw exception" );
+ } catch (Exception e) {
+ }
+ }
+
+ /**
+ * Test {@link TargetUnit#setTemplateKey(String)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see TargetUnit#setTemplateKey(String)
+ */
+ @Test
+ public void test_setTemplateKey() throws Exception {
+ unit.setTemplateKey(null);
+ assertNotNull(unit.getTemplateKey());
+
+ unit.setTemplateKey("template");
+ assertEquals(unit.getTemplateKey(), "template");
+ }
+
+ /**
+ * Test {@link TargetUnit#getTemplateKey()}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see TargetUnit#getTemplateKey()
+ */
+ @Test
+ public void test_getTemplateKey() throws Exception {
+ assertEquals(unit.getTemplateKey(), "templateKey");
+ }
+
+ /**
+ * Test {@link TargetUnit#setModelKey(String)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see TargetUnit#setModelKey(String)
+ */
+ @Test
+ public void test_setModelKey() throws Exception {
+ unit.setModelKey(null);
+ assertNotNull(unit.getModelKey());
+
+ unit.setModelKey("model");
+ assertEquals(unit.getModelKey(), "model");
+ }
+
+ /**
+ * Test {@link TargetUnit#getModelKey()}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see TargetUnit#getModelKey()
+ */
+ @Test
+ public void test_getModelKey() throws Exception {
+ assertEquals(unit.getModelKey(), "modelKey");
+ }
+
+ /**
+ * Test {@link TargetUnit#setWriter(Writer)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see TargetUnit#setWriter(Writer)
+ */
+ @Test
+ public void test_setWriter() throws Exception {
+ Writer tempWriter = null;
+ unit.setWriter(null);
+ assertNotNull(unit.getWriter());
+
+ try {
+ tempWriter = new OutputStreamWriter(System.out);
+ unit.setWriter(tempWriter);
+ assertEquals(unit.getWriter(), tempWriter);
+ } catch (Exception e) {
+ throw e;
+ }
+ }
+
+ /**
+ * Test {@link TargetUnit#getWriter()}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see TargetUnit#getWriter()
+ */
+ @Test
+ public void test_getWriter() throws Exception {
+ assertEquals(writer, unit.getWriter());
+ }
+
+ /**
+ * Test {@link TargetUnit#setEncoding(String)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see TargetUnit#setEncoding(String)
+ */
+ @Test
+ public void test_setEncoding() throws Exception {
+ unit.setEncoding(null);
+ assertNotNull(unit.getEncoding());
+
+ unit.setEncoding("UTF-8");
+ assertEquals(unit.getEncoding(), "UTF-8");
+ }
+
+ /**
+ * Test {@link TargetUnit#getEncoding()}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see TargetUnit#getEncoding()
+ */
+ @Test
+ public void test_getEncoding() throws Exception {
+ assertEquals(unit.getEncoding(), "UTF-8");
+ }
+}
diff --git a/org.tizen.common.verrari/test/src/org/tizen/common/verrari/template/FileTemplateTest.java b/org.tizen.common.verrari/test/src/org/tizen/common/verrari/template/FileTemplateTest.java
new file mode 100644
index 000000000..cfa964432
--- /dev/null
+++ b/org.tizen.common.verrari/test/src/org/tizen/common/verrari/template/FileTemplateTest.java
@@ -0,0 +1,144 @@
+/*
+ * Verrari - TemplateEngine
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * Changhyun Lee <changhyun1.lee@samsung.com>
+ * Hyeongseok Heo <hyeongseok.heo@samsung.com>
+ * Kangho Kim <kh5325.kim@samsung.com>
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common.verrari.template;
+
+import static org.junit.Assert.assertEquals;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.InputStreamReader;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+/**
+ * FileTemplateTest.
+ *
+ * Test case for {@link FileTemplate}
+ *
+ * @author Changhyun Lee{@literal <changhyun1.lee@samsung.com>} (S-Core)
+ *
+ * @see FileTemplate
+ *
+ */
+public class FileTemplateTest {
+
+ protected File file;
+ protected FileTemplate fileTemplate;
+
+ @Before
+ public void setUp() {
+ file = new File("./test/src/org/tizen/common/verrari/template/test_html.ftl");
+ fileTemplate = new FileTemplate(file);
+ }
+
+ @After
+ public void tearDown() {
+ }
+
+ /**
+ * Test {@link FileTemplate#getContainer()}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see FileTemplate#getContainer()
+ */
+ @Test
+ public void test_getContainer() throws Exception {
+ assertEquals(file, fileTemplate.getContainer());
+ }
+
+ /**
+ * Test {@link FileTemplate#getEncoding()}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see FileTemplate#getEncoding()
+ */
+ @Test
+ public void test_getEncoding() throws Exception {
+ assertEquals(System.getProperty("file.encoding"), fileTemplate.getEncoding());
+ }
+
+ /**
+ * Test {@link FileTemplate#open()}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see FileTemplate#open()
+ */
+ @Test
+ public void test_open() throws Exception {
+ //assertTrue(fileTemplate.open().);
+ String templateContents;
+ String fileConents;
+
+ BufferedReader bufferedReader = null;
+ InputStreamReader streamReader = null;
+ // get FileTemplate contents.
+ try {
+ streamReader = new InputStreamReader(fileTemplate.open(), fileTemplate.getEncoding());
+ bufferedReader = new BufferedReader(streamReader, 8192);
+ StringBuilder text = new StringBuilder();
+ final char[] buffer = new char[8192];
+ int nRead = 0;
+ while (0 < (nRead = bufferedReader.read(buffer))) {
+ text.append( buffer, 0, nRead );
+ }
+ templateContents = text.toString();
+ } catch (Exception e) {
+ throw e;
+ } finally {
+ if (streamReader != null) { streamReader.close(); }
+ if (bufferedReader != null) { bufferedReader.close(); }
+ }
+
+ // get File contents.
+ try {
+ streamReader = new InputStreamReader(new FileInputStream(file), System.getProperty("file.encoding"));
+ bufferedReader = new BufferedReader(streamReader, 8192);
+ StringBuilder text = new StringBuilder();
+ final char[] buffer = new char[8192];
+ int nRead = 0;
+ while (0 < (nRead = bufferedReader.read(buffer))) {
+ text.append( buffer, 0, nRead );
+ }
+ fileConents = text.toString();
+ } catch (Exception e) {
+ throw e;
+ } finally {
+ if (streamReader != null) { streamReader.close(); }
+ if (bufferedReader != null) { bufferedReader.close(); }
+ }
+
+ assertEquals(templateContents, fileConents);
+ }
+
+}
diff --git a/org.tizen.common.verrari/test/src/org/tizen/common/verrari/template/StaticTemplateProviderTest.java b/org.tizen.common.verrari/test/src/org/tizen/common/verrari/template/StaticTemplateProviderTest.java
new file mode 100644
index 000000000..7f4268f35
--- /dev/null
+++ b/org.tizen.common.verrari/test/src/org/tizen/common/verrari/template/StaticTemplateProviderTest.java
@@ -0,0 +1,180 @@
+/*
+ * Verrari - TemplateEngine
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * Changhyun Lee <changhyun1.lee@samsung.com>
+ * Hyeongseok Heo <hyeongseok.heo@samsung.com>
+ * Kangho Kim <kh5325.kim@samsung.com>
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common.verrari.template;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+import java.io.File;
+import java.net.URI;
+import java.util.Map;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+/**
+ * StaticTemplateProviderTest.
+ *
+ * Test case for {@link StaticTemplateProvider}
+ *
+ * @author Changhyun Lee{@literal <changhyun1.lee@samsung.com>} (S-Core)
+ *
+ * @see StaticTemplateProvider
+ *
+ */
+public class StaticTemplateProviderTest {
+
+ protected StaticTemplateProvider stp;
+
+ @Before
+ public void setUp() {
+ stp = new StaticTemplateProvider();
+ }
+
+ @After
+ public void tearDown() {
+ }
+
+ /**
+ * Test {@link StaticTemplateProvider#addTemplate(String, ITemplate)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see StaticTemplateProvider#addTemplate(String, ITemplate)
+ */
+ @Test
+ public void test_addTemplate() throws Exception {
+ assertTrue(stp.isEmpty());
+ FileTemplate fileTemplate = new FileTemplate(new File("./test/src/org/tizen/common/verrari/template/test_html.ftl"));
+ stp.addTemplate("testhtml", fileTemplate);
+ assertFalse(stp.isEmpty());
+ assertNotNull(stp.getTemplate("testhtml"));
+ }
+
+ /**
+ * Test {@link StaticTemplateProvider#addTemplate(String, URI)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see StaticTemplateProvider#addTemplate(String, URI)
+ */
+ @Test
+ public void test_addTemplate2() throws Exception {
+ assertTrue(stp.isEmpty());
+ File file = new File("./test/src/org/tizen/common/verrari/template/test_html.ftl");
+ URI uri = file.toURI();
+ stp.addTemplate("testhtml", uri);
+ assertFalse(stp.isEmpty());
+ assertNotNull(stp.getTemplate("testhtml"));
+ }
+
+ /**
+ * Test {@link StaticTemplateProvider#addTemplate(String, File)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see StaticTemplateProvider#addTemplate(String, File)
+ */
+ @Test
+ public void test_addTemplate3() throws Exception {
+ assertTrue(stp.isEmpty());
+ stp.addTemplate("testhtml", new File("./test/src/org/tizen/common/verrari/template/test_html.ftl"));
+ assertFalse(stp.isEmpty());
+ assertNotNull(stp.getTemplate("testhtml"));
+ }
+
+ /**
+ * Test {@link StaticTemplateProvider#getTemplate()}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see StaticTemplateProvider#getTemplate()
+ */
+ @Test
+ public void test_getTemplate() throws Exception {
+ assertTrue(stp.isEmpty());
+ stp.addTemplate("testhtml", new File("./test/src/org/tizen/common/verrari/template/test_html.ftl"));
+ assertNotNull(stp.getTemplate("testhtml"));
+ }
+
+ /**
+ * Test {@link StaticTemplateProvider#removeTemplate(String)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see StaticTemplateProvider#removeTemplate(String)
+ */
+ @Test
+ public void test_removeTemplate() throws Exception {
+ assertTrue(stp.isEmpty());
+ stp.addTemplate("testhtml", new File("./test/src/org/tizen/common/verrari/template/test_html.ftl"));
+ assertFalse(stp.isEmpty());
+ stp.removeTemplate(null);
+ assertFalse(stp.isEmpty());
+ stp.removeTemplate("testhtml");
+ assertTrue(stp.isEmpty());
+ }
+
+ /**
+ * Test {@link StaticTemplateProvider#getTemplates()}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see StaticTemplateProvider#getTemplates()
+ */
+ @Test
+ public void test_getTemplates() throws Exception {
+ assertTrue(stp.isEmpty());
+ stp.addTemplate("testhtml", new File("./test/src/org/tizen/common/verrari/template/test_html.ftl"));
+ assertFalse(stp.isEmpty());
+
+ Map<String, ITemplate> templates = stp.getTemplates();
+ assertFalse(templates.isEmpty());
+ assertEquals(stp.getTemplate("testhtml"), templates.get("testhtml"));
+ }
+
+ /**
+ * Test {@link StaticTemplateProvider#isEmpty()}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see StaticTemplateProvider#isEmpty()
+ */
+ @Test
+ public void test_isEmpty() throws Exception {
+ assertTrue(stp.isEmpty());
+ stp.addTemplate("testhtml", new File("./test/src/org/tizen/common/verrari/template/test_html.ftl"));
+ assertFalse(stp.isEmpty());
+ stp.removeTemplate("testhtml");
+ assertTrue(stp.isEmpty());
+ }
+
+}
diff --git a/org.tizen.common.verrari/test/src/org/tizen/common/verrari/template/test_html.ftl b/org.tizen.common.verrari/test/src/org/tizen/common/verrari/template/test_html.ftl
new file mode 100644
index 000000000..00ed03048
--- /dev/null
+++ b/org.tizen.common.verrari/test/src/org/tizen/common/verrari/template/test_html.ftl
@@ -0,0 +1,9 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <title> ${test_html!'defaultName'} </title>
+</head>
+
+<body>
+</body>
+</html>
diff --git a/org.tizen.common/.classpath b/org.tizen.common/.classpath
index c619f68c7..8e01f7b73 100644..100755
--- a/org.tizen.common/.classpath
+++ b/org.tizen.common/.classpath
@@ -1,8 +1,22 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<classpath>
- <classpathentry exported="true" kind="lib" path="sdblib.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>
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+ <classpathentry exported="true" kind="lib" path="lib/commons-logging-1.1.1.jar"/>
+ <classpathentry exported="true" kind="lib" path="lib/commons-collections-3.2.1.jar"/>
+ <classpathentry exported="true" kind="lib" path="lib/commons-pool-1.6.jar"/>
+ <classpathentry exported="true" kind="lib" path="lib/commons-lang3-3.1.jar"/>
+ <classpathentry exported="true" kind="lib" path="lib/commons-io-2.4.jar"/>
+ <classpathentry exported="true" kind="lib" path="lib/freemarker.jar"/>
+ <classpathentry exported="true" kind="lib" path="lib/log4j-1.2.17.jar"/>
+ <classpathentry exported="true" kind="lib" path="lib/sdblib.jar"/>
+ <classpathentry exported="true" kind="lib" path="lib/slf4j-api-1.6.4.jar"/>
+ <classpathentry exported="true" kind="lib" path="lib/slf4j-log4j12-1.6.4.jar"/>
+ <classpathentry exported="true" kind="lib" path="test/lib/junit-4.10.jar" sourcepath="test/lib/junit-4.10-src.jar"/>
+ <classpathentry exported="true" kind="lib" path="test/lib/mockito-all-1.9.0.jar"/>
+ <classpathentry kind="lib" path="test/lib/asm-4.0.jar"/>
+ <classpathentry kind="lib" path="test/lib/asm-tree-4.0.jar"/>
+ <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="src" path="test/src"/>
+ <classpathentry kind="output" path="bin"/>
+</classpath>
diff --git a/org.tizen.common/.settings/org.eclipse.core.resources.prefs b/org.tizen.common/.settings/org.eclipse.core.resources.prefs
new file mode 100644
index 000000000..05557bad8
--- /dev/null
+++ b/org.tizen.common/.settings/org.eclipse.core.resources.prefs
@@ -0,0 +1,3 @@
+#Tue Jun 05 12:49:09 KST 2012
+eclipse.preferences.version=1
+encoding/<project>=utf-8
diff --git a/org.tizen.common/META-INF/MANIFEST.MF b/org.tizen.common/META-INF/MANIFEST.MF
index 70adb4a31..39657a904 100644..100755
--- a/org.tizen.common/META-INF/MANIFEST.MF
+++ b/org.tizen.common/META-INF/MANIFEST.MF
@@ -1,30 +1,148 @@
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
-Bundle-Name: Tizen Common
+Bundle-Name: %Bundle-Name
Bundle-SymbolicName: org.tizen.common;singleton:=true
Bundle-Version: 1.0.0.qualifier
-Bundle-Vendor: Samsung
+Bundle-Vendor: %Bundle-Vendor
Require-Bundle: org.eclipse.ui,
org.eclipse.core.runtime,
org.eclipse.ui.ide,
org.eclipse.core.resources,
org.eclipse.core.filesystem
Export-Package:
- org.tizen.sdblib,
- org.tizen.common.cache,
- org.tizen.common.console,
- org.tizen.common.control,
- org.tizen.common.log,
- org.tizen.common.manager,
- org.tizen.common.model,
- org.tizen.common.properties,
- org.tizen.common.swt,
- org.tizen.common.util
+ freemarker.ext.dom,
+ freemarker.template,
+ org.apache.commons.lang3,
+ org.apache.commons.lang3.builder,
+ org.apache.commons.lang3.concurrent,
+ org.apache.commons.lang3.event,
+ org.apache.commons.lang3.exception,
+ org.apache.commons.lang3.math,
+ org.apache.commons.lang3.mutable,
+ org.apache.commons.lang3.reflect,
+ org.apache.commons.lang3.text,
+ org.apache.commons.lang3.text.translate,
+ org.apache.commons.lang3.time,
+ org.apache.commons.lang3.tuple,
+ org.apache.commons.logging,
+ org.junit,
+ org.junit.experimental,
+ org.junit.experimental.categories,
+ org.junit.experimental.max,
+ org.junit.experimental.results,
+ org.junit.experimental.runners,
+ org.junit.experimental.theories,
+ org.junit.experimental.theories.internal,
+ org.junit.experimental.theories.suppliers,
+ org.junit.internal,
+ org.junit.internal.builders,
+ org.junit.internal.matchers,
+ org.junit.internal.requests,
+ org.junit.internal.runners,
+ org.junit.internal.runners.model,
+ org.junit.internal.runners.rules,
+ org.junit.internal.runners.statements,
+ org.junit.matchers,
+ org.junit.rules,
+ org.junit.runner,
+ org.junit.runner.manipulation,
+ org.junit.runner.notification,
+ org.junit.runners,
+ org.junit.runners.model,
+ org.mockito,
+ org.mockito.asm,
+ org.mockito.asm.signature,
+ org.mockito.asm.tree,
+ org.mockito.asm.tree.analysis,
+ org.mockito.asm.util,
+ org.mockito.cglib.beans,
+ org.mockito.cglib.core,
+ org.mockito.cglib.proxy,
+ org.mockito.cglib.reflect,
+ org.mockito.cglib.transform,
+ org.mockito.cglib.transform.impl,
+ org.mockito.cglib.util,
+ org.mockito.configuration,
+ org.mockito.exceptions,
+ org.mockito.exceptions.base,
+ org.mockito.exceptions.misusing,
+ org.mockito.exceptions.verification,
+ org.mockito.exceptions.verification.junit,
+ org.mockito.internal,
+ org.mockito.internal.configuration,
+ org.mockito.internal.configuration.injection,
+ org.mockito.internal.configuration.injection.filter,
+ org.mockito.internal.creation,
+ org.mockito.internal.creation.cglib,
+ org.mockito.internal.creation.jmock,
+ org.mockito.internal.debugging,
+ org.mockito.internal.exceptions,
+ org.mockito.internal.exceptions.base,
+ org.mockito.internal.exceptions.util,
+ org.mockito.internal.invocation,
+ org.mockito.internal.invocation.finder,
+ org.mockito.internal.invocation.realmethod,
+ org.mockito.internal.listeners,
+ org.mockito.internal.matchers,
+ org.mockito.internal.matchers.apachecommons,
+ org.mockito.internal.progress,
+ org.mockito.internal.reporting,
+ org.mockito.internal.runners,
+ org.mockito.internal.runners.util,
+ org.mockito.internal.stubbing,
+ org.mockito.internal.stubbing.answers,
+ org.mockito.internal.stubbing.defaultanswers,
+ org.mockito.internal.util,
+ org.mockito.internal.util.junit,
+ org.mockito.internal.util.reflection,
+ org.mockito.internal.verification,
+ org.mockito.internal.verification.api,
+ org.mockito.internal.verification.argumentmatching,
+ org.mockito.internal.verification.checkers,
+ org.mockito.invocation,
+ org.mockito.listeners,
+ org.mockito.runners,
+ org.mockito.stubbing,
+ org.mockito.stubbing.answers,
+ org.mockito.verification,
+ org.slf4j,
+ org.tizen.common,
+ org.tizen.common.core.application,
+ org.tizen.common.core.command,
+ org.tizen.common.core.command.file,
+ org.tizen.common.core.command.policy,
+ org.tizen.common.core.command.prompter,
+ org.tizen.common.core.command.sdb,
+ org.tizen.common.core.command.zip,
+ org.tizen.common.file,
+ org.tizen.common.file.filter,
+ org.tizen.common.ui,
+ org.tizen.common.ui.dialog,
+ org.tizen.common.ui.page.preference,
+ org.tizen.common.ui.page.wizard,
+ org.tizen.common.ui.view.console,
+ org.tizen.common.ui.widget,
+ org.tizen.common.util,
+ org.tizen.common.util.cache,
+ org.tizen.common.util.log,
+ org.tizen.common.util.url.classpath,
+ org.tizen.common.util.url.cp,
+ org.tizen.common.util.url.vf,
+ org.tizen.sdblib
Bundle-RequiredExecutionEnvironment: JavaSE-1.6
Import-Package:
org.eclipse.jface.text,
org.eclipse.ui.console
Bundle-Activator: org.tizen.common.CommonPlugin
Bundle-ActivationPolicy: lazy
-Bundle-ClassPath: sdblib.jar,
- .
+Bundle-ClassPath: .,
+ lib/log4j-1.2.17.jar,
+ lib/sdblib.jar,
+ lib/slf4j-api-1.6.4.jar,
+ lib/slf4j-log4j12-1.6.4.jar,
+ lib/freemarker.jar,
+ lib/commons-io-2.4.jar,
+ lib/commons-lang3-3.1.jar,
+ lib/commons-collections-3.2.1.jar,
+ lib/commons-pool-1.6.jar,
+ lib/commons-logging-1.1.1.jar
diff --git a/org.tizen.common/OSGI-INF/l10n/bundle.properties b/org.tizen.common/OSGI-INF/l10n/bundle.properties
index 99ec9ad7c..c4bd08c3c 100644
--- a/org.tizen.common/OSGI-INF/l10n/bundle.properties
+++ b/org.tizen.common/OSGI-INF/l10n/bundle.properties
@@ -1,3 +1,26 @@
+Bundle-Vendor = Samsung Electronics
+
activity.name = newXsdDisabler
activity.name.0 = newDtdDisabler
-activity.name.1 = ValidateMenuItemDisabler \ No newline at end of file
+activity.name.1 = ValidateMenuItemDisabler
+
+category.name = Tizen
+page.name = Tizen SDK
+activity.description = Popup UI
+activity.name.2 = Popup UI
+category.description = Disable CDT launch UI when Native App Perspective is activated.
+category.name.0 = CDT launch UI
+activity.description.0 = Launch UI elements from CDT
+activity.name.3 = CDT Launch UI Elements
+category.description.0 = Disable CDT Toolchain Editor Page when Tizen Perspective is activated.
+category.name.1 = CDT ToolChain Editor Page
+activity.description.1 = ToolChain Editor Property Page
+activity.name.4 = CDT ToolChain Editor Page Elements
+activity.description.2 = Wizard UI
+activity.name.5 = Wizard UI
+activity.description.3 = PopupMenus
+activity.name.6 = PopupMenus
+category.name.2 = Tizen
+category.name.3 = Tizen
+extension-point.name = Prompter
+Bundle-Name = Tizen Common \ No newline at end of file
diff --git a/org.tizen.common/about.html b/org.tizen.common/about.html
index 95bb5ff8f..d71322765 100644
--- a/org.tizen.common/about.html
+++ b/org.tizen.common/about.html
@@ -37,5 +37,17 @@ A copy of the license is included in <a href="about_files/epl-v10.html">about_fi
</ul>
</p>
+<h4>FreeMarker</h4>
+<p>
+FreeMarker is a "template engine"; a generic tool to generate text output (anything from HTML to autogenerated source code) based on templates. It's a Java package, a class library for Java programmers. It's not an application for end-users in itself, but something that programmers can embed into their products.
+</p>
+
+<p>
+A copy of the license is included in <a href="about_files/freemarker-LICENSE.txt">about_files/freemarker-LICENSE.txt</a>. The home page is located at:
+<ul>
+<a href="http://freemarker.sourceforge.net/">http://freemarker.sourceforge.net/</a>
+</ul>
+</p>
+
</body>
</html> \ No newline at end of file
diff --git a/org.tizen.common/about_files/freemarker-LICENSE.txt b/org.tizen.common/about_files/freemarker-LICENSE.txt
new file mode 100644
index 000000000..4c5f08621
--- /dev/null
+++ b/org.tizen.common/about_files/freemarker-LICENSE.txt
@@ -0,0 +1,69 @@
+FreeMarker 1.x was released under the LGPL license. Later, by community
+consensus, we have switched over to a BSD-style license. As of FreeMarker
+2.2pre1, the original author, Benjamin Geer, has relinquished the copyright in
+behalf of Visigoth Software Society. The current copyright holder is the
+Visigoth Software Society.
+
+------------------------------------------------------------------------------
+Copyright (c) 2003 The Visigoth Software Society. All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+1. Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimer.
+
+2. The end-user documentation included with the redistribution, if any, must
+ include the following acknowlegement:
+ "This product includes software developed by the
+ Visigoth Software Society (http://www.visigoths.org/)."
+ Alternately, this acknowlegement may appear in the software itself, if and
+ wherever such third-party acknowlegements normally appear.
+
+3. Neither the name "FreeMarker", "Visigoth", nor any of the names of the
+ project contributors may be used to endorse or promote products derived
+ from this software without prior written permission. For written
+ permission, please contact visigoths@visigoths.org.
+
+4. Products derived from this software may not be called "FreeMarker" or
+ "Visigoth" nor may "FreeMarker" or "Visigoth" appear in their names
+ without prior written permission of the Visigoth Software Society.
+
+THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
+INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
+FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+VISIGOTH SOFTWARE SOCIETY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 OF THIS SOFTWARE,
+EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+------------------------------------------------------------------------------
+
+This software consists of voluntary contributions made by many individuals on
+behalf of the Visigoth Software Society. For more information on the Visigoth
+Software Society, please see http://www.visigoths.org/
+
+------------------------------------------------------------------------------
+
+FREEMARKER SUBCOMPONENTS UNDER DIFFERENT LICENSE:
+
+FreeMarker includes a number of subcomponents that are licensed by the Apache
+Software Foundation under the Apache License, Version 2.0. Your use of these
+subcomponents is subject to the terms and conditions of the Apache License,
+Version 2.0. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+The subcomponents under this licence are the following files, which are
+included both in freemarker.jar and in the source code:
+
+ freemarker/ext/jsp/web-app_2_2.dtd
+ freemarker/ext/jsp/web-app_2_3.dtd
+ freemarker/ext/jsp/web-app_2_4.xsd
+ freemarker/ext/jsp/web-app_2_5.xsd
+ freemarker/ext/jsp/web-jsptaglibrary_1_1.dtd
+ freemarker/ext/jsp/web-jsptaglibrary_1_2.dtd
+ freemarker/ext/jsp/web-jsptaglibrary_2_0.xsd
+ freemarker/ext/jsp/web-jsptaglibrary_2_1.xsd
diff --git a/org.tizen.common/build.properties b/org.tizen.common/build.properties
index 889acffc9..49d1a304d 100644..100755
--- a/org.tizen.common/build.properties
+++ b/org.tizen.common/build.properties
@@ -3,9 +3,16 @@ output.. = bin/
bin.includes = META-INF/,\
.,\
icons/,\
- sdblib.jar,\
about.html,\
about_files/,\
- plugin.xml
+ plugin.xml,\
+ lib/,\
+ lib/commons-io-2.4.jar,\
+ lib/commons-lang3-3.1.jar,\
+ lib/commons-collections-3.2.1.jar,\
+ lib/commons-pool-1.6.jar,\
+ OSGI-INF/,\
+ OSGI-INF/l10n/bundle.properties,\
+ lib/commons-logging-1.1.1.jar
javacSource = 1.6
javacTarget = 1.6
diff --git a/org.tizen.common/icons/back.gif b/org.tizen.common/icons/back.gif
new file mode 100644
index 000000000..4fb415010
--- /dev/null
+++ b/org.tizen.common/icons/back.gif
Binary files differ
diff --git a/org.tizen.common/icons/forward.gif b/org.tizen.common/icons/forward.gif
new file mode 100644
index 000000000..e2f8c3e1f
--- /dev/null
+++ b/org.tizen.common/icons/forward.gif
Binary files differ
diff --git a/org.tizen.common/lib/commons-collections-3.2.1.jar b/org.tizen.common/lib/commons-collections-3.2.1.jar
new file mode 100644
index 000000000..c35fa1fee
--- /dev/null
+++ b/org.tizen.common/lib/commons-collections-3.2.1.jar
Binary files differ
diff --git a/org.tizen.common/lib/commons-io-2.4.jar b/org.tizen.common/lib/commons-io-2.4.jar
new file mode 100644
index 000000000..90035a4fe
--- /dev/null
+++ b/org.tizen.common/lib/commons-io-2.4.jar
Binary files differ
diff --git a/org.tizen.common/lib/commons-lang3-3.1.jar b/org.tizen.common/lib/commons-lang3-3.1.jar
new file mode 100644
index 000000000..a85e539b1
--- /dev/null
+++ b/org.tizen.common/lib/commons-lang3-3.1.jar
Binary files differ
diff --git a/org.tizen.common/lib/commons-logging-1.1.1.jar b/org.tizen.common/lib/commons-logging-1.1.1.jar
new file mode 100644
index 000000000..1deef144c
--- /dev/null
+++ b/org.tizen.common/lib/commons-logging-1.1.1.jar
Binary files differ
diff --git a/org.tizen.common/lib/commons-pool-1.6.jar b/org.tizen.common/lib/commons-pool-1.6.jar
new file mode 100644
index 000000000..72ca75a3e
--- /dev/null
+++ b/org.tizen.common/lib/commons-pool-1.6.jar
Binary files differ
diff --git a/org.tizen.common/lib/freemarker.jar b/org.tizen.common/lib/freemarker.jar
new file mode 100644
index 000000000..b3673e229
--- /dev/null
+++ b/org.tizen.common/lib/freemarker.jar
Binary files differ
diff --git a/org.tizen.common/lib/log4j-1.2.17.jar b/org.tizen.common/lib/log4j-1.2.17.jar
new file mode 100644
index 000000000..068867ebf
--- /dev/null
+++ b/org.tizen.common/lib/log4j-1.2.17.jar
Binary files differ
diff --git a/org.tizen.common/lib/sdblib.jar b/org.tizen.common/lib/sdblib.jar
new file mode 100644
index 000000000..dc3036939
--- /dev/null
+++ b/org.tizen.common/lib/sdblib.jar
Binary files differ
diff --git a/org.tizen.common/lib/slf4j-api-1.6.4.jar b/org.tizen.common/lib/slf4j-api-1.6.4.jar
new file mode 100644
index 000000000..4d23f41d3
--- /dev/null
+++ b/org.tizen.common/lib/slf4j-api-1.6.4.jar
Binary files differ
diff --git a/org.tizen.common/lib/slf4j-log4j12-1.6.4.jar b/org.tizen.common/lib/slf4j-log4j12-1.6.4.jar
new file mode 100644
index 000000000..daa3aa163
--- /dev/null
+++ b/org.tizen.common/lib/slf4j-log4j12-1.6.4.jar
Binary files differ
diff --git a/org.tizen.common/plugin.xml b/org.tizen.common/plugin.xml
index 8deffd8f4..1f584bf04 100644
--- a/org.tizen.common/plugin.xml
+++ b/org.tizen.common/plugin.xml
@@ -1,25 +1,41 @@
<?xml version="1.0" encoding="UTF-8"?>
<?eclipse version="3.4"?>
<plugin>
+ <extension-point id="org.tizen.common.prompter" name="%extension-point.name" schema="schema/org.tizen.common.prompter.exsd"/>
+ <extension
+ point="org.eclipse.ui.bindings">
+ <key
+ commandId="org.eclipse.ui.project.buildProject"
+ contextId="org.eclipse.ui.contexts.window"
+ schemeId="org.eclipse.ui.defaultAcceleratorConfiguration"
+ sequence="F10">
+ </key>
+ <key
+ commandId="org.eclipse.ui.project.buildProject"
+ contextId="org.eclipse.ui.contexts.window"
+ schemeId="org.eclipse.ui.defaultAcceleratorConfiguration"
+ sequence="M1+M2+F10">
+ </key>
+ </extension>
<extension
point="org.eclipse.ui.newWizards">
<category
id="org.tizen.nativeapp.newCategory"
- name="Tizen">
+ name="%category.name">
</category>
</extension>
<extension
point="org.eclipse.ui.preferencePages">
<page
- class="org.tizen.common.preferences.TizenBasePreferencePage"
+ class="org.tizen.common.ui.page.preference.TizenBasePreferencePage"
id="org.tizen.common.preferences.tizencommon"
- name="Tizen SDK">
+ name="%page.name">
</page>
</extension>
<extension
point="org.eclipse.ui.startup">
<startup
- class="org.tizen.common.update.UpdateManager">
+ class="org.tizen.common.core.application.UpdateManager">
</startup>
</extension>
<!-- activities start -->
@@ -27,18 +43,21 @@
point="org.eclipse.ui.activities">
<!-- disable rhino lauch shortcuts & wst launch shortcut -->
<activity
- name="Popup UI"
- description="Popup UI"
+ name="%activity.name.2"
+ description="%activity.description"
id="org.tizen.web.launch.DisablePopupMenu">
<enabledWhen>
<with variable="activeWorkbenchWindow.activePerspective">
<and>
<not>
- <equals value="org.tizen.web.ui.perspective.WACwidget"/>
+ <equals value="org.tizen.web.ui.perspective.WebWidget"/>
</not>
<not>
<equals value="org.tizen.nativeapp.perspective"/>
</not>
+ <not>
+ <equals value="org.tizen.webguibuilder.BuilderPerspective"/>
+ </not>
</and>
</with>
</enabledWhen>
@@ -57,25 +76,28 @@
point="org.eclipse.ui.activities">
<!-- disable CDT launch ui -->
<category
- name="CDT launch UI"
- description="Disable CDT launch UI when Native App Perspective is activated."
+ name="%category.name.0"
+ description="%category.description"
id="org.tizen.nativeapp.CDTLaunchUICategory">
</category>
<activity
- name="CDT Launch UI Elements"
- description="Launch UI elements from CDT"
+ name="%activity.name.3"
+ description="%activity.description.0"
id="org.tizen.nativeapp.DisableCDTLaunchUIActivity">
<enabledWhen>
<with variable="activeWorkbenchWindow.activePerspective">
<and>
<not>
- <equals value="org.tizen.web.ui.perspective.WACwidget"/>
+ <equals value="org.tizen.web.ui.perspective.WebWidget"/>
</not>
<not>
<equals value="org.tizen.nativeapp.perspective"/>
</not>
+ <not>
+ <equals value="org.tizen.webguibuilder.BuilderPerspective"/>
+ </not>
</and>
</with>
</enabledWhen>
@@ -103,23 +125,26 @@
<!-- disable CDT toolchain editor page -->
<category
- description="Disable CDT Toolchain Editor Page when Tizen Perspective is activated."
+ description="%category.description.0"
id="org.tizen.nativeapp.CDTToolChainEditorPageCategory"
- name="CDT ToolChain Editor Page">
+ name="%category.name.1">
</category>
<activity
- description="ToolChain Editor Property Page"
+ description="%activity.description.1"
id="org.tizen.nativeapp.DisableCDTToolChainEditorPageActivity"
- name="CDT ToolChain Editor Page Elements">
+ name="%activity.name.4">
<enabledWhen>
<with variable="activeWorkbenchWindow.activePerspective">
<and>
<not>
- <equals value="org.tizen.web.ui.perspective.WACwidget"/>
+ <equals value="org.tizen.web.ui.perspective.WebWidget"/>
</not>
<not>
<equals value="org.tizen.nativeapp.perspective"/>
</not>
+ <not>
+ <equals value="org.tizen.webguibuilder.BuilderPerspective"/>
+ </not>
</and>
</with>
</enabledWhen>
@@ -166,28 +191,27 @@
<activity
- name="Wizard UI"
- description="Wizard UI"
+ name="%activity.name.5"
+ description="%activity.description.2"
id="org.tizen.web.DisableWizardsActivity">
<enabledWhen>
<with variable="activeWorkbenchWindow.activePerspective">
<and>
<not>
- <equals value="org.tizen.web.ui.perspective.WACwidget"/>
+ <equals value="org.tizen.web.ui.perspective.WebWidget"/>
</not>
<not>
<equals value="org.tizen.nativeapp.perspective"/>
</not>
+ <not>
+ <equals value="org.tizen.webguibuilder.BuilderPerspective"/>
+ </not>
</and>
</with>
</enabledWhen>
</activity>
<activityPatternBinding
activityId="org.tizen.web.DisableWizardsActivity"
- pattern="com\.samsung\.tizen\.guibuilder/com\.samsung\.tizen\.guibuilder\.wizard\.newSgmWizard">
- </activityPatternBinding>
- <activityPatternBinding
- activityId="org.tizen.web.DisableWizardsActivity"
pattern="org\.eclipse\.jdt\.ui/org\.eclipse\.jdt\.ui\.wizards\.JavaProjectWizard">
</activityPatternBinding>
<activityPatternBinding
@@ -270,10 +294,11 @@
activityId="org.tizen.web.DisableWizardsActivity"
pattern="org\.eclipse\.wst\.dtd\.ui/org\.eclipse\.wst\.dtd\.ui\.internal\.wizard\.NewDTDWizard">
</activityPatternBinding>
- <activityPatternBinding
+ <!-- JSON File Wizard -->
+ <!-- activityPatternBinding
activityId="org.tizen.web.DisableWizardsActivity"
pattern="json\.editor\.plugin/Json\.newFileWizard">
- </activityPatternBinding>
+ </activityPatternBinding-->
<activityPatternBinding
activityId="org.tizen.web.DisableWizardsActivity"
pattern="org\.eclipse\.wst\.xml\.ui/org\.eclipse\.wst\.xml\.ui\.internal\.wizards\.NewXMLWizard">
@@ -288,18 +313,26 @@
point="org.eclipse.ui.activities">
<!-- PopupMenus Enabled when tizen Web IDE perspective -->
<activity
- description="PopupMenus"
+ description="%activity.description.3"
id="org.tizen.web.PopupMenusActivity"
- name="PopupMenus">
+ name="%activity.name.6">
<enabledWhen>
+ <and>
<with
variable="activeWorkbenchWindow.activePerspective">
<and>
<equals
- value="org.tizen.web.ui.perspective.WACwidget">
+ value="org.tizen.web.ui.perspective.WebWidget">
</equals>
</and>
</with>
+ <with variable="selection">
+ <iterate ifEmpty="false">
+ <test property="org.eclipse.core.resources.projectNature"
+ value="org.tizen.web.project.builder.WebNature" />
+ </iterate>
+ </with>
+ </and>
</enabledWhen>
</activity>
<activityPatternBinding
@@ -311,5 +344,19 @@
pattern="org.tizen.web.localization/org.tizen.web.localization.menus.popup.localizationMenu">
</activityPatternBinding>
</extension>
+ <extension
+ point="org.eclipse.ui.importWizards">
+ <category
+ id="org.tizen.nativeapp.importCategory"
+ name="%category.name.2">
+ </category>
+ </extension>
+ <extension
+ point="org.eclipse.ui.exportWizards">
+ <category
+ id="org.tizen.nativeapp.exportCategory"
+ name="%category.name.3">
+ </category>
+ </extension>
<!-- activities end -->
</plugin>
diff --git a/org.tizen.common/schema/org.tizen.common.prompter.exsd b/org.tizen.common/schema/org.tizen.common.prompter.exsd
new file mode 100644
index 000000000..cb67108a1
--- /dev/null
+++ b/org.tizen.common/schema/org.tizen.common.prompter.exsd
@@ -0,0 +1,109 @@
+<?xml version='1.0' encoding='UTF-8'?>
+<!-- Schema file written by PDE -->
+<schema targetNamespace="org.tizen.common" xmlns="http://www.w3.org/2001/XMLSchema">
+<annotation>
+ <appinfo>
+ <meta.schema plugin="org.tizen.common" id="org.tizen.common.prompter" name="Prompter"/>
+ </appinfo>
+ <documentation>
+ [Enter description of this extension point.]
+ </documentation>
+ </annotation>
+
+ <element name="extension">
+ <annotation>
+ <appinfo>
+ <meta.element />
+ </appinfo>
+ </annotation>
+ <complexType>
+ <choice minOccurs="1" maxOccurs="unbounded">
+ <element ref="prompter"/>
+ </choice>
+ <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>
+
+ <element name="prompter">
+ <complexType>
+ <attribute name="scope" type="string">
+ <annotation>
+ <documentation>
+
+ </documentation>
+ </annotation>
+ </attribute>
+ <attribute name="class" type="string" use="required">
+ <annotation>
+ <documentation>
+
+ </documentation>
+ <appinfo>
+ <meta.attribute kind="java" basedOn=":org.tizen.common.core.command.Prompter"/>
+ </appinfo>
+ </annotation>
+ </attribute>
+ </complexType>
+ </element>
+
+ <annotation>
+ <appinfo>
+ <meta.section type="since"/>
+ </appinfo>
+ <documentation>
+ [Enter the first release in which this extension point appears.]
+ </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>
+ [Enter API information here.]
+ </documentation>
+ </annotation>
+
+ <annotation>
+ <appinfo>
+ <meta.section type="implementation"/>
+ </appinfo>
+ <documentation>
+ [Enter information about supplied implementation of this extension point.]
+ </documentation>
+ </annotation>
+
+
+</schema>
diff --git a/org.tizen.common/sdblib.jar b/org.tizen.common/sdblib.jar
deleted file mode 100644
index 28a8a0434..000000000
--- a/org.tizen.common/sdblib.jar
+++ /dev/null
Binary files differ
diff --git a/org.tizen.common/src/org/tizen/common/Adaptable.java b/org.tizen.common/src/org/tizen/common/Adaptable.java
new file mode 100644
index 000000000..8fb893549
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/Adaptable.java
@@ -0,0 +1,49 @@
+/*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common;
+
+/**
+ * <p>
+ * Adaptable.
+ *
+ * Class for adapter pattern
+ *
+ * </p>
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ */
+public interface
+Adaptable
+{
+ /**
+ * Adapt to new type interface or class
+ *
+ * @param <T> new type
+ * @param clazz new type class
+ *
+ * @return object to adapt to
+ */
+ public <T> T adapt( Class<T> clazz );
+}
diff --git a/org.tizen.common/src/org/tizen/common/AppIdGenerator.java b/org.tizen.common/src/org/tizen/common/AppIdGenerator.java
new file mode 100644
index 000000000..1712b04e9
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/AppIdGenerator.java
@@ -0,0 +1,127 @@
+/*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * Changhyun Lee <changhyun1.lee@samsung.com>
+ * Hyeongseok Heo <hyeongseok.heo@samsung.com>
+ * BonYong Lee <bonyong.lee@samsung.com>
+ * Kangho Kim <kh5325.kim@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+
+package org.tizen.common;
+
+import java.math.BigInteger;
+import java.security.SecureRandom;
+
+import javax.crypto.Cipher;
+import javax.crypto.KeyGenerator;
+import javax.crypto.SecretKey;
+import javax.crypto.spec.SecretKeySpec;
+
+/**
+ * Appid generator.
+ * It is consist of 0-9, a-z
+ */
+public class AppIdGenerator {
+ final char[] PSEUDO_CHARS = { '0', '1', '2', '3', '4', '5', '6', '7',
+ '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
+ 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
+ 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
+ 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
+ 'y', 'z' };
+
+ final BigInteger PSEUDO_CHAR_SIZE = new BigInteger("62");
+
+ // Reserved AppID (or prefix)
+ static final String RESERVED_APPID [] = {
+ "TIZEN",
+ "PRIVT",
+ "WIDGT"
+ };
+ // Number of reserved AppID
+ static final int RESERVED_APPID_NUMBER = 3;
+
+ private String convertBytesToAlphaNumeric(byte in[], int size) {
+ BigInteger randomBigInt = new BigInteger(in).abs();
+ StringBuffer out = new StringBuffer(size + 1);
+
+ for (int i = 0; i < size; ++i) {
+ BigInteger[] dividedAndremainder = randomBigInt.divideAndRemainder(PSEUDO_CHAR_SIZE);
+ randomBigInt = dividedAndremainder[0];
+ out.append(PSEUDO_CHARS[dividedAndremainder[1].intValue()]);
+ }
+
+ String ret = new String(out);
+ return ret;
+ }
+
+ private byte[] generateRandomBytes(int size) throws Exception {
+ SecureRandom random = new SecureRandom();
+ KeyGenerator keyGen = KeyGenerator.getInstance("AES");
+ keyGen.init(128);
+
+ byte[] bytes = new byte[size];
+ random.nextBytes(bytes);
+
+ SecretKey secretkey = keyGen.generateKey();
+ byte[] key = secretkey.getEncoded();
+ SecretKeySpec secretkeySpec = new SecretKeySpec(key, "AES");
+
+ Cipher cipher = Cipher.getInstance("AES");
+ cipher.init(Cipher.ENCRYPT_MODE, secretkeySpec);
+
+ return cipher.doFinal(bytes);
+ }
+
+ private boolean check(String appId) {
+ for (int i = 0; i < RESERVED_APPID_NUMBER; ++ i) {
+ if (appId.indexOf(RESERVED_APPID[i]) == 0) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Generate an id of length n.
+ *
+ * @param size id length
+ * @return id
+ */
+ public String generate(int size) throws Exception {
+ String appId = "";
+ do {
+ appId = convertBytesToAlphaNumeric(generateRandomBytes(size), size);
+ } while (!check(appId));
+
+ return appId;
+ }
+
+ /**
+ * Generate an id of length 10.
+ *
+ * @return id
+ */
+ public String generate() throws Exception {
+ return generate(10);
+ }
+
+}
diff --git a/org.tizen.common/src/org/tizen/common/Cabinet.java b/org.tizen.common/src/org/tizen/common/Cabinet.java
new file mode 100755
index 000000000..5ed46d02c
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/Cabinet.java
@@ -0,0 +1,10 @@
+package org.tizen.common;
+
+public interface
+Cabinet<T>
+extends Runnable
+{
+ public T getData();
+
+ public void setData( T data );
+}
diff --git a/org.tizen.common/src/org/tizen/common/CommonPlugin.java b/org.tizen.common/src/org/tizen/common/CommonPlugin.java
index b337172d8..736d1d7d5 100644
--- a/org.tizen.common/src/org/tizen/common/CommonPlugin.java
+++ b/org.tizen.common/src/org/tizen/common/CommonPlugin.java
@@ -3,10 +3,10 @@
*
* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
*
-* Contact:
+* Contact:
* Changhyun Lee <changhyun1.lee@samsung.com>
* Kangho Kim <kh5325.kim@samsung.com>
-*
+*
* 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
@@ -25,16 +25,21 @@
*/
package org.tizen.common;
-import java.io.File;
-
+import org.apache.log4j.spi.RepositorySelector;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;
-import org.tizen.common.preferences.TizenBasePreferencePage;
-import org.tizen.common.properties.InstallPathConfig;
+import org.tizen.common.core.application.InstallPathConfig;
+import org.tizen.common.core.command.EclipseExecutor;
+import org.tizen.common.core.command.Executor;
+import org.tizen.common.core.command.Prompter;
+import org.tizen.common.core.command.prompter.EclipsePrompter;
+import org.tizen.common.core.command.prompter.SWTPrompter;
+import org.tizen.common.ui.page.preference.TizenBasePreferencePage;
+import org.tizen.common.util.DialogUtil;
import org.tizen.common.util.HostUtil;
import org.tizen.common.util.OSChecker;
-
+import org.tizen.common.util.log.Logger;
import org.tizen.sdblib.SmartDevelopmentBridge;
/**
@@ -45,36 +50,69 @@ public class CommonPlugin extends AbstractUIPlugin {
// The plug-in ID
public static final String PLUGIN_ID = "org.tizen.common"; //$NON-NLS-1$
- private final static String SDKSUFFIX = File.separatorChar+".TizenSDK"+File.separatorChar+"tizensdkpath";
// The shared instance
private static CommonPlugin plugin;
-
+
/**
- * The constructor
+ * {@link Prompter} using swt dialog
*/
- public CommonPlugin() {
- SmartDevelopmentBridge.init();
- String sdbPath = InstallPathConfig.getSDKPath() + File.separator + "SDK" + File.separator +"sdb" + File.separator + "sdb";
- SmartDevelopmentBridge.createBridge(sdbPath, true);
- }
+ protected EclipsePrompter prompter = null;
+
+ /**
+ * {@link Executor} with {@link SWTPrompter}
+ */
+ protected Executor executor = null;
+
+ protected RepositorySelector selector = null;
/*
* (non-Javadoc)
* @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
*/
+ @Override
public void start(BundleContext context) throws Exception {
- super.start(context);
+ super.start( context );
plugin = this;
+ initializeExecutor();
+
+ String sdbPath = InstallPathConfig.getSDBPath();
+ if (!HostUtil.exists(sdbPath)) {
+ DialogUtil.openMessageDialog("There is no " + sdbPath + ".");
+ }
+ else {
+ try {
+ SmartDevelopmentBridge.init();
+ SmartDevelopmentBridge.createBridge(sdbPath, true);
+ } catch (Throwable t) {
+ Logger.error("Problem occurred while initializing sdb", t.getMessage(), t);
+ DialogUtil.openErrorDialog("Failed to start sdb");
+ }
+ }
+
+ if (OSChecker.isWindows()) {
+ String dllPath = InstallPathConfig.getSdbWinUsbApiPath();
+ if (!HostUtil.exists(dllPath))
+ DialogUtil.openMessageDialog("There is no " + dllPath + ".\n" +
+ "It's not mandatory but you may have problem in using sdb through USB.");
+ }
}
/*
* (non-Javadoc)
* @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
*/
+ @Override
public void stop(BundleContext context) throws Exception {
+ finalizeExecutor();
plugin = null;
super.stop(context);
}
+
+
+ public static void setDefault( CommonPlugin plugin )
+ {
+ CommonPlugin.plugin = plugin;
+ }
/**
* Returns the shared instance
@@ -84,39 +122,56 @@ public class CommonPlugin extends AbstractUIPlugin {
public static CommonPlugin getDefault() {
return plugin;
}
-
- @Override
- protected void initializeDefaultPreferences(IPreferenceStore store) {
- if (loadSdkPath() != null)
- store.setDefault(TizenBasePreferencePage.KEY_SDKLOCATION,loadSdkPath());
- store.setDefault(TizenBasePreferencePage.KEY_SDKUPDATE,TizenBasePreferencePage.VALUE_SDKUPDATE_DEFAULT);
+ /* (non-Javadoc)
+ * @see org.eclipse.ui.plugin.AbstractUIPlugin#initializeDefaultPreferences(org.eclipse.jface.preference.IPreferenceStore)
+ */
+ @Override
+ protected void initializeDefaultPreferences( final IPreferenceStore store ) {
+ if (InstallPathConfig.getSDKPath() != null)
+ store.setDefault(TizenBasePreferencePage.KEY_SDKLOCATION, InstallPathConfig.getSDKPath());
+ store.setDefault(TizenBasePreferencePage.KEY_SDKUPDATE, TizenBasePreferencePage.VALUE_SDKUPDATE_DEFAULT);
+ }
- }
+ /**
+ * Set {@link Executor} in eclipse plugin environment
+ *
+ * @param executor {@link Executor}
+ */
+ public void setExecutor( final Executor executor )
+ {
+ this.executor = executor;
+ }
+
+ /**
+ * Return {@link Executor} in eclipse plugin environment
+ * @return
+ */
+ public Executor getExecutor()
+ {
+ return this.executor;
+ }
+
+ /**
+ * Return {@link Prompter} in eclipse plugin environment
+ *
+ * @return {@link Prompter}
+ */
+ public Prompter getPrompter()
+ {
+ return this.prompter;
+ }
-
- /**
- * get sdk path
- */
- private String loadSdkPath() {
- String sdkConfig;
- String sdkPath = null;;
- if (OSChecker.isWindows())
- sdkConfig = System.getenv("localappdata") + File.separatorChar + SDKSUFFIX;
- else
- sdkConfig= System.getProperty("user.home") + File.separatorChar + SDKSUFFIX;
+ protected void initializeExecutor()
+ {
+ this.prompter = new EclipsePrompter( new SWTPrompter() );
+
+ this.executor = new EclipseExecutor( prompter );
+ }
- if (HostUtil.exists(sdkConfig)) {
- String contents = HostUtil.getContents(sdkConfig);
- if (contents != null) {
- String[] fileContent = contents.split("=");
- if (fileContent.length == 2) {
- if (HostUtil.exists(fileContent[1]))
- sdkPath = fileContent[1];
- }
- }
- }
- return sdkPath;
- }
+ protected void finalizeExecutor()
+ {
+
+ }
}
diff --git a/org.tizen.common/src/org/tizen/common/model/DefaultTableModel.java b/org.tizen.common/src/org/tizen/common/Factory.java
index d50073748..b5dcc5784 100644
--- a/org.tizen.common/src/org/tizen/common/model/DefaultTableModel.java
+++ b/org.tizen.common/src/org/tizen/common/Factory.java
@@ -1,43 +1,45 @@
-/*
-* Common
-*
-* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
-*
-* Contact:
-* Kangho Kim <kh5325.kim@samsung.com>
-*
-* 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.
-*
-* Contributors:
-* - S-Core Co., Ltd
-*
-*/
-
-package org.tizen.common.model;
-
-
-public class DefaultTableModel extends AbstractTableModel {
-
- public DefaultTableModel(AbstractTableVO source) {
- super(source);
- }
-
- public String getSourceName() {
- String str = this.source.getClass().getSimpleName();
- if(str.endsWith("VO")) //$NON-NLS-1$
- str = str.substring(0,str.length()-2);
- return str;
- }
-}
-
-
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* Kangho Kim <kh5325.kim@samsung.com>
+* Hyeongseok Heo <hyeongseok.heo@samsung.com>
+* BonYong Lee <bonyong.lee@samsung.com>
+* Gyeongseok Seo <gyeongseok.seo@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+
+package org.tizen.common;
+
+/**
+ * Factory Interface that are using when create new object by Factory pattern
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ * @author Gyeongseok Seo <gyeongseok.seo@samsung.com>
+ */
+public interface Factory<T>
+{
+ /**
+ * create object
+ *
+ * @return created <code>T</code> object
+ */
+ T create();
+}
diff --git a/org.tizen.common/src/org/tizen/common/control/TableViewContentProvider.java b/org.tizen.common/src/org/tizen/common/FactoryWithArgument.java
index 2d9038cac..864e92ff2 100644
--- a/org.tizen.common/src/org/tizen/common/control/TableViewContentProvider.java
+++ b/org.tizen.common/src/org/tizen/common/FactoryWithArgument.java
@@ -1,50 +1,45 @@
-/*
-* Common
-*
-* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
-*
-* Contact:
-* Kangho Kim <kh5325.kim@samsung.com>
-*
-* 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.
-*
-* Contributors:
-* - S-Core Co., Ltd
-*
-*/
-
-package org.tizen.common.control;
-
-import org.eclipse.jface.viewers.IStructuredContentProvider;
-import org.eclipse.jface.viewers.Viewer;
-import org.tizen.common.model.ITableModel;
-
-
-public class TableViewContentProvider implements IStructuredContentProvider {
-
- public TableViewContentProvider() {
- }
-
- public Object[] getElements(Object model) {
- return ((ITableModel)model).getDatas();
- }
-
- public void dispose() {
-
- }
-
- public void inputChanged(Viewer viewer, Object obj, Object obj1) {
-
- }
-
-}
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* Kangho Kim <kh5325.kim@samsung.com>
+* Hyeongseok Heo <hyeongseok.heo@samsung.com>
+* BonYong Lee <bonyong.lee@samsung.com>
+* Gyeongseok Seo <gyeongseok.seo@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+
+package org.tizen.common;
+
+/**
+ * Factory Interface that are using when create new object with argument by Factory pattern
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ * @author Gyeongseok Seo <gyeongseok.seo@samsung.com>
+ */
+public interface FactoryWithArgument<T, A> {
+ /**
+ * create object
+ *
+ * @param arg argument of an object to be created
+ * @return created <code>T</code> object
+ */
+ T create( A arg );
+}
diff --git a/org.tizen.common/src/org/tizen/common/IApplicationConfiguration.java b/org.tizen.common/src/org/tizen/common/IApplicationConfiguration.java
new file mode 100755
index 000000000..325223de2
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/IApplicationConfiguration.java
@@ -0,0 +1,39 @@
+/*
+ * Common
+ *
+ * Copyright (C) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * Jihoon Song <jihoon80.song@samsung.com>
+ * Kangho Kim <kh5325.kim@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common;
+
+/**
+ * IApplicationConfiguration Interface that is used when getting project's build configurations.
+ *
+ * @author Kangho Kim{@literal <kh5325.kim@samsung.com>} (S-Core)
+ * @author Yoonki Park <yoonki.park@samsung.com>
+ */
+public interface IApplicationConfiguration {
+ public String getDefaultConfiguration();
+ public String getBinaryName();
+ public String generateAppId();
+ public TizenProjectType getTizenProjectType();
+}
diff --git a/org.tizen.common/src/org/tizen/common/Surrogate.java b/org.tizen.common/src/org/tizen/common/Surrogate.java
new file mode 100644
index 000000000..c752d78e6
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/Surrogate.java
@@ -0,0 +1,44 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* Kangho Kim <kh5325.kim@samsung.com>
+* Hyeongseok Heo <hyeongseok.heo@samsung.com>
+* BonYong Lee <bonyong.lee@samsung.com>
+* Gyeongseok Seo <gyeongseok.seo@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+
+package org.tizen.common;
+
+/**
+ * Surrogate Interface that are using when dependency object is injected by surrogate pattern
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ * @author Gyeongseok Seo <gyeongseok.seo@samsung.com>
+ */
+public interface Surrogate<T> {
+ /**
+ * pass adapted object
+ *
+ * @return adapted <code>T</code> object
+ */
+ T getAdapter();
+}
diff --git a/org.tizen.common/src/org/tizen/common/control/TreeViewLabelProvider.java b/org.tizen.common/src/org/tizen/common/SurrogateWithArgument.java
index 77bb41387..d6b704db5 100644
--- a/org.tizen.common/src/org/tizen/common/control/TreeViewLabelProvider.java
+++ b/org.tizen.common/src/org/tizen/common/SurrogateWithArgument.java
@@ -1,32 +1,42 @@
-/*
-* Common
-*
-* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
-*
-* Contact:
-* Kangho Kim <kh5325.kim@samsung.com>
-*
-* 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.
-*
-* Contributors:
-* - S-Core Co., Ltd
-*
-*/
-
-package org.tizen.common.control;
-
-import org.eclipse.jface.viewers.LabelProvider;
-
-public class TreeViewLabelProvider extends LabelProvider {
-
-}
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* BonYong Lee <bonyong.lee@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+package org.tizen.common;
+
+/**
+ * Surrogate Interface that are using when dependency object is injected by surrogate pattern
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ */
+public interface SurrogateWithArgument<T, A>
+{
+ /**
+ * pass adapted object using argument
+ *
+ * @param arg argument of an object to be created
+ *
+ * @return adapted <code>T</code> object
+ */
+ T getAdapter( A arg );
+}
diff --git a/org.tizen.common/src/org/tizen/common/TizenHelpContextIds.java b/org.tizen.common/src/org/tizen/common/TizenHelpContextIds.java
new file mode 100644
index 000000000..c543ddcc8
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/TizenHelpContextIds.java
@@ -0,0 +1,49 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* Changhyun Lee <changhyun1.lee@samsung.com>
+* Kangho Kim <kh5325.kim@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+package org.tizen.common;
+
+public class TizenHelpContextIds
+{
+ public static final String HELP_COMMON_CONNECTION_EXPLORER_CONTEXT = "org.tizen.ide.common.connection_explorer_context";
+ public static final String HELP_COMMON_LOG_CONTEXT = "org.tizen.ide.common.log_context";
+
+ public static final String HELP_NATIVE_CODECOVERAGE_CONTEXT = "org.tizen.ide.native.codecoverage_context";
+ public static final String HELP_NATIVE_UNITTEST_CONTEXT = "org.tizen.ide.native.unittest_context";
+ public static final String HELP_NATIVE_MANIFEST_CONTEXT = "org.tizen.ide.native.manifest_context";
+ public static final String HELP_NATIVE_PROJECT_WIZARD_CONTEXT = "org.tizen.ide.native.project_wizard_context";
+
+ public static final String HELP_WEB_WIDGET_CONFIGURATION_EDITOR_CONTEXT = "org.tizen.ide.web.widget_configuration_editor_context";
+ public static final String HELP_WEB_HTML_EDITOR_CONTEXT = "org.tizen.ide.web.html_editor_context";
+ public static final String HELP_WEB_JAVASCRIPT_EDITOR_CONTEXT = "org.tizen.ide.web.javascript_editor_context";
+ public static final String HELP_WEB_CSS_EDITOR_CONTEXT = "org.tizen.ide.web.css_editor_context";
+ public static final String HELP_WEB_HTML_PREVIEW_CONTEXT = "org.tizen.ide.web.html_preview_context";
+ public static final String HELP_WEB_CSS_PREVIEW_CONTEXT = "org.tizen.ide.web.css_preview_context";
+ public static final String HELP_WEB_PREFERENCES_CONTEXT = "org.tizen.ide.web.preferences_context";
+ public static final String HELP_WEB_SIMULATOR_PREFERENCES_CONTEXT = "org.tizen.ide.web.simulator_preferences_context";
+ public static final String HELP_WEB_NEW_PROJECT_WIZARD_CONTEXT = "org.tizen.ide.web.new_project_wizard_context";
+ public static final String HELP_WEB_USER_TEMPLATE_CONTEXT = "org.tizen.ide.web.user_template_context";
+
+}
diff --git a/org.tizen.common/src/org/tizen/common/TizenPlatformConstants.java b/org.tizen.common/src/org/tizen/common/TizenPlatformConstants.java
new file mode 100644
index 000000000..2463a9822
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/TizenPlatformConstants.java
@@ -0,0 +1,80 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* Kangho Kim <kh5325.kim@samsung.com>
+* Hyunsik Noh <hyunsik.noh@samsung.com>
+* Yoonki Park <yoonki.park@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+package org.tizen.common;
+
+import org.tizen.common.util.OSChecker;
+
+/**
+ * All constant definitions related Tizen Platform such as Emulator or Device.
+ * @author Kangho Kim {@literal <kh5325.kim@samsung.com>} (S-Core)
+ */
+public class TizenPlatformConstants {
+ // Definitions for common
+ public static final String LOCALHOST = "127.0.0.1";
+ public static final String ENVIRONMENT_SETTING_CMD = "export ";
+ public static final String CMD_RESULT_CHECK = "; echo $?;";
+ public static final String CMD_RESULT_PREFIX = "cmd_ret:";
+ public static final String CMD_SUFFIX = "; echo "+CMD_RESULT_PREFIX+"$?;";
+ public static final String CMD_SUCCESS = CMD_RESULT_PREFIX+"0";
+ public static final String CMD_FAILURE = CMD_RESULT_PREFIX+"1";
+
+ public static final int OS = OSChecker.LINUX;
+
+ // Definitions for building
+
+ // Definitions for packaging
+ public static final String PACKAGENAME_PREFIX = "org.tizen";
+ public static final String DEBIAN_INSTALL_PATH = "opt/*";
+
+ // Definitions for debugging
+ public static final String PUBICL_PLATFORM_CORE_PATH = "/opt/bs/core";
+ public static final String PRIVATE_PLATFORM_CORE_PATH = "/opt/share/hidden_storage/SLP_debug";
+ public static final String GDBSERVER_CMD = TizenPlatformConstants.TOOLS_TARGET_PATH + "/gdbserver/gdbserver";
+ public static final String GDBSERVER_PLATFORM_CMD = TizenPlatformConstants.TOOLS_TARGET_PATH + "/gdbserver-platform/gdbserver";
+ public static final String ATTACH_OPTION = " --attach ";
+
+ // Definitions for installing
+ public static final String APP_INSTALL_PATH = "/opt/apps";
+ public static final String TEMPORARY_PKG_PATH = "/opt/apps/PKGS/";
+ public static final String PKG_TOOL_LIST_COMMAND = "pkgcmd -l | grep %s";
+ public static final String PKG_TOOL_REMOVE_COMMAND = "pkgcmd -q -u -t %s -n %s";
+ public static final String PKG_TOOL_INSTALL_COMMAND = "pkgcmd -q -i -t %s -p %s";
+
+ // Definitions for launching
+ public static final String LAUNCH_CMD = "launch_app %s";
+ public static final String LAUNCH_CMD_SUCCESS = "... successfully launched";
+ public static final String LAUNCH_CMD_FAILURE = "... launch failed";
+ public static final String ELM_SCALE_GETTER = "/home/developer/sdk_tools/elm_scale_getter/get_elm_scale ";//FIXME : have to be removed
+
+ // Definitions for ondemand install
+ public static final String CONTROL_EXTENSION = ".control";
+ public static final String TOOLS_TARGET_PATH = "/home/developer/sdk_tools";
+
+ // Definitions for others
+ public static final String CODE_COVERAGE_BUILD_OPTION = "-fprofile-arcs -ftest-coverage";
+ public static final String CODE_COVERAGE_LAUNCH_OPTION = " __AUL_SDK__ CODE_COVERAGE";
+}
diff --git a/org.tizen.common/src/org/tizen/common/TizenProjectType.java b/org.tizen.common/src/org/tizen/common/TizenProjectType.java
new file mode 100644
index 000000000..126151ba8
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/TizenProjectType.java
@@ -0,0 +1,41 @@
+/*
+* TizenProjectType.java
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* Kangho Kim <kh5225.kim@samsung.com>
+* Gun Kim <gune.kim@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+package org.tizen.common;
+
+/**
+ * Represents that TIZEN supports the given project types.
+ */
+public enum TizenProjectType {
+ TIZEN_C_UI_APPLICATION,
+ TIZEN_C_SERVICE_APPLICATION,
+ TIZEN_C_SHAREDLIBRARY,
+ TIZEN_C_STATICLIBRARY,
+ TIZEN_CPP_UI_APPLICATION,
+ TIZEN_CPP_SERVICE_APPLICATION,
+ TIZEN_CPP_SHAREDLIBRARY,
+ TIZEN_CPP_STATICLIBRARY,
+ TIZEN_PLATFORM_PROJECT;
+}
diff --git a/org.tizen.common/src/org/tizen/common/cache/ImageCache.java b/org.tizen.common/src/org/tizen/common/cache/ImageCache.java
deleted file mode 100644
index 639a79723..000000000
--- a/org.tizen.common/src/org/tizen/common/cache/ImageCache.java
+++ /dev/null
@@ -1,105 +0,0 @@
-/*
-* Common
-*
-* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
-*
-* Contact:
-* Changhyun Lee <changhyun1.lee@samsung.com>
-* Kangho Kim <kh5325.kim@samsung.com>
-*
-* 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.
-*
-* Contributors:
-* - S-Core Co., Ltd
-*
-*/
-package org.tizen.common.cache;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.HashMap;
-import java.util.Iterator;
-
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.widgets.Display;
-
-/**
- * Class for caching images
- *
- * @author Emil
- */
-public class ImageCache {
-
- private static HashMap<String, Image> _ImageMap;
-
- // what path to get to the "icons" directory without actually including it
- private static final String ICON_ROOT_PATH = "icons/";
-
- static {
- _ImageMap = new HashMap<String, Image>();
- }
-
- /**
- * Returns an image that is also cached if it has to be created and does not already exist in the cache.
- *
- * @param fileName Filename of image to fetch
- * @return Image null if it could not be found
- */
- public static Image getImage(String fileName) {
- fileName = ICON_ROOT_PATH + fileName;
- Image image = _ImageMap.get(fileName);
- if (image == null) {
- image = createImage(fileName);
- _ImageMap.put(fileName, image);
- }
- return image;
- }
-
- // creates the image, and tries really hard to do so
- private static Image createImage(String fileName) {
- ClassLoader classLoader = ImageCache.class.getClassLoader();
- InputStream is = classLoader.getResourceAsStream(fileName);
- if (is == null) {
- // the old way didn't have leading slash, so if we can't find the image stream,
- // let's see if the old way works.
- is = classLoader.getResourceAsStream(fileName.substring(1));
-
- if (is == null) {
- is = classLoader.getResourceAsStream(fileName);
- if (is == null) {
- is = classLoader.getResourceAsStream(fileName.substring(1));
- if (is == null) { return null; }
- }
- }
- }
-
- Image img = new Image(Display.getDefault(), is);
- try {
- is.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
-
- return img;
- }
-
- /**
- * Disposes ALL images that have been cached.
- */
- public static void dispose() {
- Iterator<Image> e = _ImageMap.values().iterator();
- while (e.hasNext())
- e.next().dispose();
-
- }
-}
diff --git a/org.tizen.common/src/org/tizen/common/control/TableViewCellModifier.java b/org.tizen.common/src/org/tizen/common/control/TableViewCellModifier.java
deleted file mode 100644
index 6bbc54ede..000000000
--- a/org.tizen.common/src/org/tizen/common/control/TableViewCellModifier.java
+++ /dev/null
@@ -1,136 +0,0 @@
-/*
-* Common
-*
-* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
-*
-* Contact:
-* Kangho Kim <kh5325.kim@samsung.com>
-*
-* 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.
-*
-* Contributors:
-* - S-Core Co., Ltd
-*
-*/
-
-package org.tizen.common.control;
-import org.eclipse.jface.viewers.CellEditor;
-import org.eclipse.jface.viewers.ComboBoxCellEditor;
-import org.eclipse.jface.viewers.ICellModifier;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.viewers.TextCellEditor;
-import org.eclipse.swt.widgets.TableColumn;
-import org.eclipse.swt.widgets.TableItem;
-import org.tizen.common.model.ITableVO;
-
-
-/**
- * This class implements an ICellModifier
- * An ICellModifier is called when the user modifes a cell in the
- * tableViewer
- */
-
-public class TableViewCellModifier implements ICellModifier {
- private TableViewer viewer;
- private String[] columnNames;
- CellEditor[] cellEditors;
- /**
- * Constructor
- * @param TableViewerExample an instance of a TableViewerExample
- */
- public TableViewCellModifier(TableViewer viewer) {
- super();
- this.viewer = viewer;
- this.columnNames = getColumnNames();
- this.viewer.setColumnProperties(columnNames);
- }
-
- private String[] getColumnNames() {
- TableColumn[] columns = viewer.getTable().getColumns();
- String[] columnNames = new String[columns.length];
- for(int i=0;i<columnNames.length;i++){
- columnNames[i] = columns[i].getText();
- }
-
- return columnNames;
- }
-
- /**
- * @see org.eclipse.jface.viewers.ICellModifier#canModify(java.lang.Object, java.lang.String)
- */
- public boolean canModify(Object element, String property) {
- return true;
- }
-
- /**
- * @see org.eclipse.jface.viewers.ICellModifier#getValue(java.lang.Object, java.lang.String)
- */
- public Object getValue(Object element, String property) {
-
- Object result = null;
- int idx = getColumnIndex(property);
- ITableVO vo = (ITableVO)element;
-
- CellEditor ce = getCellEditor(idx);
-
- if(ce instanceof ComboBoxCellEditor){
- result = vo.getColumnValue(idx);
- }else if(ce instanceof TextCellEditor){
- result = vo.getColumnValue(idx);
- }else{
- result = ""; //$NON-NLS-1$
- }
- return result;
- }
-
- private CellEditor getCellEditor(int idx) {
- if(this.cellEditors==null)
- this.cellEditors = viewer.getCellEditors();
- return this.cellEditors[idx];
- }
-
- private int getColumnIndex(String property) {
- for(int i=0;i<columnNames.length;i++){
- if(columnNames[i].equals(property))
- return i;
- }
- return 0;
- }
-
- private int getComboIndex(String[] items, Object str) {
- for(int i=0;i<items.length;i++){
- if(items[i].equals(str))
- return i;
- }
- return 0;
- }
-
- /**
- * @see org.eclipse.jface.viewers.ICellModifier#modify(java.lang.Object, java.lang.String, java.lang.Object)
- */
- public void modify(Object element, String property, Object value) {
- int idx = getColumnIndex(property);
- ITableVO vo = (ITableVO)((TableItem) element).getData();
-
- if(cellEditors[idx] instanceof ComboBoxCellEditor){
- if((Integer)value < 0)
- return;
- else
- vo.setColumnValue(idx, value);
- }else if(cellEditors[idx] instanceof TextCellEditor){
- vo.setColumnValue(idx, value);
- }
-
- viewer.update(vo, null);
- }
-}
diff --git a/org.tizen.common/src/org/tizen/common/control/TableViewColumnSorter.java b/org.tizen.common/src/org/tizen/common/control/TableViewColumnSorter.java
deleted file mode 100644
index 1456f8928..000000000
--- a/org.tizen.common/src/org/tizen/common/control/TableViewColumnSorter.java
+++ /dev/null
@@ -1,160 +0,0 @@
-/*
-* Common
-*
-* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
-*
-* Contact:
-* Kangho Kim <kh5325.kim@samsung.com>
-*
-* 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.
-*
-* Contributors:
-* - S-Core Co., Ltd
-*
-*/
-
-package org.tizen.common.control;
-
-import java.util.Comparator;
-
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerSorter;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.graphics.Cursor;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.swt.widgets.TableColumn;
-import org.tizen.common.model.ITableVO;
-
-
-
-
-/**
- * A viewer sorter is used by a structured viewer to reorder the elements
- * provided by its content provider. In addition, the TableViewColumnSorter
- * listens for mouse clicks in the column headers and resorts the table content
- * based on the column that was selected. Clicking on a column a second time
- * toggles the sort order.
- */
-public class TableViewColumnSorter extends ViewerSorter {
- private static final String COLUMN_INDEX_KEY = "COLUMN_INDEX"; //$NON-NLS-1$
- private static final String HEADER_TEXT_KEY = "HEADER_TEXT"; //$NON-NLS-1$
- private static final String TAG_DESCENDING = "\u25b2"; // up-pointing triangle
- private static final String TAG_ASCENDING = "\u25bc"; // down-pointing triangle
-
- private TableViewer viewer;
- private Table table;
- private TableColumn[] columns;
- Cursor waitCursor;
-
- private Comparator<String> stringComparator = new Comparator<String>(){
- @Override
- public int compare(String str1, String str2) {
- str1=str1==null?"":str1; //$NON-NLS-1$
- str2=str2==null?"":str2; //$NON-NLS-1$
- return str1.compareTo(str2);
- }
- };
-
- private Comparator<Integer> numberComparator = new Comparator<Integer>(){
- @Override
- public int compare(Integer num1, Integer num2) {
- return num1>num2?1:(num1==num2?0:-1);
- }
- };
-
- public TableViewColumnSorter(TableViewer viewer) {
- this.viewer = viewer;
- this.table = viewer.getTable();
- this.columns = viewer.getTable().getColumns();
-
- createCursor();
- createSelectionListener(columns);
- }
-
- private void createCursor(){
- waitCursor = Display.getCurrent().getSystemCursor(SWT.CURSOR_WAIT);
- }
-
- public int compare(Viewer viewer, Object object1, Object object2) {
- TableColumn column = table.getSortColumn();
-
- int index = -1;
- if(column==null){
- return 0;
- }else{
- index = (Integer)column.getData(COLUMN_INDEX_KEY);
- }
-
- Object target1 = ((ITableVO)object1).getColumnValue(index);
- Object target2 = ((ITableVO)object2).getColumnValue(index);
-
- int result = compare(target1, target2);
-
- if(table.getSortDirection()==SWT.UP)
- return result;
- else
- return -result;
- }
-
- public int compare(Object object1, Object object2){
- if(object1 instanceof Integer){
- return numberComparator.compare((Integer)object1, (Integer)object2);
- }else{
- return stringComparator.compare(object1.toString(), object2.toString());
- }
- }
-
- private void createSelectionListener(TableColumn[] columns) {
- for (int i = 0; i < columns.length; i++) {
- columns[i].setData(COLUMN_INDEX_KEY,i);
- columns[i].setData(HEADER_TEXT_KEY,columns[i].getText());
- columns[i].addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- TableColumn column = (TableColumn)e.getSource();
- clearColumnHeader(column);
- renderColumnHeader(column);
-
- table.setCursor(waitCursor);
- viewer.refresh();
- table.setCursor(null);
- }
- });
- }
- }
-
- private void renderColumnHeader(TableColumn column){
- int direction = table.getSortDirection()==SWT.UP?SWT.DOWN:SWT.UP;
- table.setSortDirection(direction);
- table.setSortColumn(column);
-
- String title = (String)column.getData(HEADER_TEXT_KEY);
- String directionShape = direction==SWT.UP?TAG_DESCENDING:TAG_ASCENDING;
- column.setText(title+" "+directionShape); //$NON-NLS-1$
- }
-
- private void clearColumnHeader(TableColumn column){
- TableColumn prevColumn = table.getSortColumn();
-
- if(prevColumn==null){
- return;
- }else{
- prevColumn.setText((String)prevColumn.getData(HEADER_TEXT_KEY));
- }
- }
-
-} \ No newline at end of file
diff --git a/org.tizen.common/src/org/tizen/common/control/TableViewLabelProvider.java b/org.tizen.common/src/org/tizen/common/control/TableViewLabelProvider.java
deleted file mode 100644
index 12bfa05cb..000000000
--- a/org.tizen.common/src/org/tizen/common/control/TableViewLabelProvider.java
+++ /dev/null
@@ -1,121 +0,0 @@
-/*
-* Common
-*
-* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
-*
-* Contact:
-* Kangho Kim <kh5325.kim@samsung.com>
-*
-* 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.
-*
-* Contributors:
-* - S-Core Co., Ltd
-*
-*/
-
-package org.tizen.common.control;
-
-import java.lang.reflect.Field;
-import java.lang.reflect.Method;
-
-import org.eclipse.jface.viewers.CellEditor;
-import org.eclipse.jface.viewers.ColumnLabelProvider;
-import org.eclipse.jface.viewers.ComboBoxCellEditor;
-import org.eclipse.jface.viewers.ITableLabelProvider;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.swt.graphics.Image;
-import org.tizen.common.model.ITableVO;
-
-
-
-
-
-public class TableViewLabelProvider extends ColumnLabelProvider implements ITableLabelProvider {
-
- public TableViewLabelProvider() {
- }
-
- private TableViewer viewer;
- CellEditor[] cellEditors;
-
- public TableViewLabelProvider(TableViewer viewer) {
- this.viewer = viewer;
- this.cellEditors = viewer.getCellEditors();
- }
-
- private Field[] fields;
-
- private int getColumnIndex(int columnIndex){
- return fields.length>columnIndex?columnIndex:fields.length;
- }
-
- public Image getColumnImage(Object element, int columnIndex) {
- return null;
- }
-
-// private void hasCellEditor(){
-// if(this.cellEditors==null)
-// this.cellEditors = viewer.getCellEditors();
-// }
-
- private CellEditor getCellEditor(int idx) {
- if(this.cellEditors==null)
- return null;
- else
- return this.cellEditors[idx];
- }
-
- public String getColumnText(Object element, int columnIndex) {
- Object obj = null;
-
- if(element instanceof ITableVO){
- ITableVO data = (ITableVO)element;
- if(this.cellEditors != null){
- CellEditor ce = getCellEditor(columnIndex);
- if(ce instanceof ComboBoxCellEditor){
- ComboBoxCellEditor editor = (ComboBoxCellEditor)ce;
- String items[] = editor.getItems();
- int idx = (Integer) data.getColumnValue(columnIndex);
- if(idx<0)
- obj = null;
- else if(idx>items.length)
- obj = items[0];
- else
- obj = items[idx];
- }else{
- obj = data.getColumnValue(columnIndex);
- }
- }else{
- obj = data.getColumnValue(columnIndex);
- }
- }else{
- if(fields==null)
- fields = element.getClass().getDeclaredFields();
-
- int idx = getColumnIndex(columnIndex);
- String fieldName = fields[idx].getName().substring(0, 1).toUpperCase()
- + fields[idx].getName().substring(1,fields[idx].getName().length());
-
- try{
- Method method = element.getClass().getMethod("get" + fieldName, new Class[] {}); //$NON-NLS-1$
- obj = method.invoke(element, new Object[] {});
- }catch(Exception e){
- return ""; //$NON-NLS-1$
- }
- }
-
- return obj==null?"":String.valueOf(obj); //$NON-NLS-1$
- }
-
-
-}
diff --git a/org.tizen.common/src/org/tizen/common/control/TreeViewContentProvider.java b/org.tizen.common/src/org/tizen/common/control/TreeViewContentProvider.java
deleted file mode 100644
index 726fb9390..000000000
--- a/org.tizen.common/src/org/tizen/common/control/TreeViewContentProvider.java
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
-* Common
-*
-* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
-*
-* Contact:
-* Kangho Kim <kh5325.kim@samsung.com>
-*
-* 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.
-*
-* Contributors:
-* - S-Core Co., Ltd
-*
-*/
-
-package org.tizen.common.control;
-
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.Viewer;
-import org.tizen.common.model.ITreeModel;
-import org.tizen.common.model.ITreeVO;
-
-
-public class TreeViewContentProvider implements ITreeContentProvider {
-
- public Object[] getChildren(Object element) {
- if(element instanceof ITreeModel)
- return ((ITreeModel)element).getDatas();
- else
- return ((ITreeVO)element).getChildren();
- }
-
- public Object getParent(Object element) {
- if(element instanceof ITreeModel)
- return null;
- else
- return ((ITreeVO)element).getParent();
-
- }
-
- public boolean hasChildren(Object element) {
- if(element instanceof ITreeModel)
- return ((ITreeModel)element).size()>0;
- else
- return ((ITreeVO)element).hasChildren();
- }
-
- public Object[] getElements(Object inputElement) {
- return getChildren(inputElement);
- }
-
- public void dispose() {
- }
-
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- }
-
-
-}
diff --git a/org.tizen.common/src/org/tizen/common/core/application/InstallPathConfig.java b/org.tizen.common/src/org/tizen/common/core/application/InstallPathConfig.java
new file mode 100644
index 000000000..d0d268e50
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/core/application/InstallPathConfig.java
@@ -0,0 +1,212 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* Kangho Kim <kh5325.kim@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+
+package org.tizen.common.core.application;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStreamReader;
+
+import org.tizen.common.util.DialogUtil;
+import org.tizen.common.util.HostUtil;
+import org.tizen.common.util.OSChecker;
+
+
+
+final public class InstallPathConfig {
+
+ private static String defaultHomePath;
+ private static String sdkInstallPath;
+
+ private static final String DIR_PLATFORMS = "platforms";
+ private static final String DIR_PLATFORMS_VER = "tizen2.0";
+ private static final String DIR_SAMPLES = "samples";
+ private static final String DIR_SNIPPETS = "snippets";
+ private static final String DIR_ON_DEMAND = "on-demand";
+ private static final String DIR_EMULATOR = "emulator";
+ private static final String DIR_INSTALLER = "install-manager";
+ private static final String DIR_TOOLS = "tools";
+ private static final String DIR_LIBRARY = "library";
+ private static final String DIR_SDK_DATA = "tizen-sdk-data";
+
+ private final static String SDKSUFFIX = DIR_SDK_DATA + File.separatorChar + "tizensdkpath";
+
+ // Registry Key
+ private static final String REGISTRY_PATH_OF_SHELL_FOLDER = "HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders";
+ // public static final String REGISTRY_APP_DATA_OF_SHELL_FOLDER = "AppData";
+ private static final String REGISTRY_LOCAL_APP_DATA_OF_SHELL_FOLDER = "\"Local AppData\"";
+ // Value Column
+ private static final String REG_SZ = "REG_SZ";
+
+ static {
+ // FIXME : don't need the following lines if using environment variable
+ if (OSChecker.isWindows()) {
+ defaultHomePath = getRegistryValue(REGISTRY_PATH_OF_SHELL_FOLDER,REGISTRY_LOCAL_APP_DATA_OF_SHELL_FOLDER) ;
+ } else if (OSChecker.isLinux() == true || OSChecker.isUnix() == true || OSChecker.isMAC() == true) {
+ defaultHomePath = System.getProperty("user.home");
+ } else {
+ DialogUtil.openMessageDialog(System.getProperty("os.name") + " is not supported currently.");
+ System.exit(0);
+ }
+
+ loadSdkPath(defaultHomePath + File.separatorChar + SDKSUFFIX);
+ }
+
+ /**
+ * @deprecated Use {@link #getSDKPath()} instead.
+ */
+ @Deprecated
+ public static String getIDEPath() {
+ // FIXME : can't help but putting the code due to the Web IDE path , It has to be removed soon.
+ return System.getProperty("user.dir");
+ }
+
+ public static String getSDKPath() {
+ return sdkInstallPath;
+ }
+
+ //This is temporary code to get platform version path(only for one).
+ //TODO: Should change to return string array type for various platform version paths.
+ public static String getPlatformVersionPath()
+ {
+ String path = null;
+ String platformPath = getSDKPath() + File.separator + DIR_PLATFORMS;
+ File platforms = new File(platformPath);
+ if(platforms.isDirectory())
+ {
+ // platforms.listFiles[0] can cause undetermined result like platforms/tmp.ini/sample
+ path = platformPath + File.separator + DIR_PLATFORMS_VER;
+ }
+ return path;
+ }
+
+ //TODO: Should change to get string array type for various platform version paths.
+ public static String getSamplesPath()
+ {
+ return getPlatformVersionPath() + File.separator + DIR_SAMPLES;
+ }
+
+ //TODO: Should change to get string array type for various platform version paths.
+ public static String getSnippetsPath()
+ {
+ return getPlatformVersionPath() + File.separator + DIR_SNIPPETS;
+ }
+
+ //TODO: Should change to get string array type for various platform version paths.
+ public static String getOnDemandPath()
+ {
+ return getPlatformVersionPath() + File.separator + DIR_ON_DEMAND;
+ }
+
+ public static String getLibraryPath() {
+ return getSDKPath() + File.separator + DIR_LIBRARY;
+ }
+
+ private static String getToolsPath() {
+ return getSDKPath() + File.separator + DIR_TOOLS;
+ }
+
+ public static String getSDBPath() {
+ String toolsPath = getToolsPath();
+ if (OSChecker.isWindows())
+ return toolsPath + File.separator + "sdb.exe";
+ else
+ return toolsPath + File.separator + "sdb";
+ }
+
+ public static String getSdbWinUsbApiPath() {
+ return getToolsPath() + File.separator + "SdbWinUsbApi.dll";
+ }
+
+ public static String getInstallManagerPath() {
+ return getSDKPath() + File.separator + DIR_INSTALLER;
+ }
+
+ public static String getEmulatorPath() {
+ return getToolsPath() + File.separator + DIR_EMULATOR;
+ }
+
+ public static String getUserHomePath() {
+ return defaultHomePath;
+ }
+
+ public static String getUserDataPath() {
+ return getUserHomePath() + File.separator + DIR_SDK_DATA;
+ }
+
+ private static void loadSdkPath(String sdkPath) {
+ boolean status = true;
+ if (HostUtil.exists(sdkPath)) {
+ String[] fileContent = HostUtil.getContents(sdkPath).split("=");
+ if (HostUtil.exists(fileContent[1]))
+ sdkInstallPath = fileContent[1];
+ else {
+ status = false;
+ }
+ } else {
+ status = false;
+ }
+
+ if (!status) {
+ DialogUtil.openMessageDialog("Tizen SDK is not installed properly.");
+ System.exit(0);
+ }
+ }
+ private static String getRegistryValue(String node, String key) {
+ if (!OSChecker.isWindows())
+ return null;
+
+ BufferedReader br = null;
+ String value = "";
+
+ String query = "reg query " + "\"" + node + "\" /v " + key;
+ try {
+ Process process = Runtime.getRuntime().exec(query);
+ String encoding = System.getProperty("sun.jnu.encoding");
+ br = new BufferedReader(new InputStreamReader(process.getInputStream(), encoding));
+
+ String line = null;
+ while ((line = br.readLine()) != null) {
+ int index = line.indexOf(REG_SZ);
+ if (index >= 0) {
+ value = line.substring(index + REG_SZ.length()).trim();
+ }
+ }
+ } catch (IOException e) {
+ e.printStackTrace();
+ } finally {
+ if (br != null) {
+ try {
+ br.close();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+
+ return value;
+ }
+} \ No newline at end of file
diff --git a/org.tizen.common/src/org/tizen/common/core/application/Messages.java b/org.tizen.common/src/org/tizen/common/core/application/Messages.java
new file mode 100644
index 000000000..d0ec4ae2f
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/core/application/Messages.java
@@ -0,0 +1,19 @@
+package org.tizen.common.core.application;
+
+import org.eclipse.osgi.util.NLS;
+
+public class Messages extends NLS
+{
+ private static final String BUNDLE_NAME = Messages.class.getName(); //$NON-NLS-1$
+ public static String DIALOG_TITLE;
+ public static String ASK_FOR_UPDATE;
+
+ public static String FileExistDialogTitle;
+ public static String FileExistMsg;
+
+ static {
+ // initialize resource bundle
+ NLS.initializeMessages( BUNDLE_NAME, Messages.class );
+ }
+
+}
diff --git a/org.tizen.common/src/org/tizen/common/core/application/Messages.properties b/org.tizen.common/src/org/tizen/common/core/application/Messages.properties
new file mode 100644
index 000000000..d3158eb98
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/core/application/Messages.properties
@@ -0,0 +1,5 @@
+DIALOG_TITLE = Tizen SDK
+ASK_FOR_UPDATE = Tizen SDK updates are available. Do you want to install them now?
+
+FileExistDialogTitle=Existing resource
+FileExistMsg="{0}" already exists. Do you want to overwrite it?
diff --git a/org.tizen.common/src/org/tizen/common/core/application/StatusLineMessageManager.java b/org.tizen.common/src/org/tizen/common/core/application/StatusLineMessageManager.java
new file mode 100644
index 000000000..7d4fa259a
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/core/application/StatusLineMessageManager.java
@@ -0,0 +1,80 @@
+/*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * Kangho Kim <kh5325.kim@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common.core.application;
+
+import org.eclipse.jface.action.IStatusLineManager;
+import org.eclipse.ui.IViewPart;
+
+public class StatusLineMessageManager
+{
+
+ protected final IStatusLineManager manager;
+
+ /**
+ * Contructor with {@link IViewPart}
+ *
+ * @param part {@link IViewPart} to provide {@link IStatusLineManager}
+ */
+ public StatusLineMessageManager( final IViewPart part )
+ {
+ this( part.getViewSite().getActionBars().getStatusLineManager() );
+ }
+
+ /**
+ * Constructor with {@link IStatusLineManager}
+ *
+ * @param manager {@link IStatusLineManager} to manage status bar
+ */
+ public StatusLineMessageManager(
+ final IStatusLineManager manager
+ )
+ {
+ if ( null == manager )
+ { // Fast Fail
+ throw new NullPointerException();
+ }
+ this.manager = manager;
+ }
+
+ /**
+ * Add error message at status bar
+ *
+ * @param message message to print out
+ */
+ public void setErrorMessage( final String message )
+ {
+ manager.setErrorMessage( message );
+ }
+
+ /**
+ * Add message at status bar
+ *
+ * @param message message to print out
+ */
+ public void setMessage( final String message )
+ {
+ manager.setMessage( message );
+ }
+}
diff --git a/org.tizen.common/src/org/tizen/common/update/UpdateManager.java b/org.tizen.common/src/org/tizen/common/core/application/UpdateManager.java
index 1a171792a..0213b2790 100644..100755
--- a/org.tizen.common/src/org/tizen/common/update/UpdateManager.java
+++ b/org.tizen.common/src/org/tizen/common/core/application/UpdateManager.java
@@ -23,24 +23,24 @@
* - S-Core Co., Ltd
*
*/
-package org.tizen.common.update;
+package org.tizen.common.core.application;
+
+import static org.tizen.common.util.SWTUtil.syncExec;
import java.io.File;
-import java.util.ResourceBundle;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.swt.SWT;
-import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IStartup;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.PlatformUI;
import org.tizen.common.CommonPlugin;
-import org.tizen.common.preferences.TizenBasePreferencePage;
-import org.tizen.common.properties.InstallPathConfig;
+import org.tizen.common.ui.page.preference.TizenBasePreferencePage;
import org.tizen.common.util.HostUtil;
import org.tizen.common.util.OSChecker;
+import org.tizen.common.util.SWTUtil;
public class UpdateManager implements IStartup {
@@ -48,49 +48,48 @@ public class UpdateManager implements IStartup {
private static final String EXECUTE_INSTALLER_COMMAND_FOR_WINDOWS = "InstManager.exe";
private static final String UPDATE_LIST_CHECK_COMMAND = "%s -checkPackageUpdate";
private static final String RESULT_VALUE_OF_UPDATABLE = "updatable";
- private static final String BUNDLE_NAME = UpdateManager.class.getPackage().getName() + ".UpdateMessages";//$NON-NLS-1$
-
- public static ResourceBundle resources = ResourceBundle.getBundle(BUNDLE_NAME);
final IWorkbench workbench = PlatformUI.getWorkbench();
@Override
public void earlyStartup() {
// Check installable package exist.
- IPreferenceStore prefStore = CommonPlugin.getDefault().getPreferenceStore();
+ final IPreferenceStore prefStore =
+ CommonPlugin.getDefault().getPreferenceStore();
- if(prefStore.getBoolean(TizenBasePreferencePage.KEY_SDKUPDATE))
- {
- boolean updatable = isExistUpdatablePackage();
- if(updatable) {
- if(askExecuteInstallerDlg()) {
- executeInstallManger();
- if (workbench != null) {
- final Display display = workbench.getDisplay();
- display.syncExec(new Runnable() {
- public void run() {
- if (!display.isDisposed())
- workbench.close();
- }
- });
- }
- }
- }
+ if ( !prefStore.getBoolean( TizenBasePreferencePage.KEY_SDKUPDATE ) )
+ { // User don't want to update at startup
+ return ;
}
+ if ( !isExistUpdatablePackage() )
+ { // Check updatable version
+ return ;
+ }
+ if( !askExecuteInstallerDlg() )
+ { // User don't want to update at this time
+ return ;
+ }
+
+ executeInstallManger();
+ syncExec( new Runnable() {
+ public void run() {
+ if (!workbench.getDisplay().isDisposed())
+ {
+ workbench.close();
+ }
+ }
+ });
}
- private boolean isExistUpdatablePackage() {
- String result = HostUtil.returnExecute(getUpdateCheckCmd(), InstallPathConfig.getInstallManagerPath());
- if(RESULT_VALUE_OF_UPDATABLE.equals(result))
- return true;
- return false;
+ private boolean isExistUpdatablePackage()
+ {
+ String result = HostUtil.returnExecute( getUpdateCheckCmd(), InstallPathConfig.getInstallManagerPath() );
+ return ( RESULT_VALUE_OF_UPDATABLE.equals( result ) );
}
private boolean askExecuteInstallerDlg() {
int ret = checkUpdate();
- if (ret == IDialogConstants.YES_ID)
- return true;
- return false;
+ return ( ret == IDialogConstants.YES_ID );
}
private void executeInstallManger() {
@@ -112,8 +111,11 @@ public class UpdateManager implements IStartup {
MessageDialog dialog = new MessageDialog(
PlatformUI.getWorkbench().getDisplay().getActiveShell(),
- resources.getString("message.dialogTitle"),
- null, resources.getString("message.askForUpdate"), MessageDialog.QUESTION, labels, 0);
+ Messages.DIALOG_TITLE,
+ null,
+ Messages.ASK_FOR_UPDATE,
+ MessageDialog.QUESTION,
+ labels, 0);
dialog.open();
if (dialog.getReturnCode() == SWT.DEFAULT) {
// A window close returns SWT.DEFAULT - mapped to a cancel
@@ -124,7 +126,8 @@ public class UpdateManager implements IStartup {
}
};
- PlatformUI.getWorkbench().getDisplay().syncExec(query);
+
+ SWTUtil.syncExec( query );
return result[0];
}
diff --git a/org.tizen.common/src/org/tizen/common/core/command/AbstractCommand.java b/org.tizen.common/src/org/tizen/common/core/command/AbstractCommand.java
new file mode 100644
index 000000000..a083ddc14
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/core/command/AbstractCommand.java
@@ -0,0 +1,94 @@
+/*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common.core.command;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * <p>
+ * AbstractCommand.
+ *
+ * Abstract class for {@link Command}
+ * </p>
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ */
+abstract public class
+AbstractCommand<T>
+implements Command<T> {
+
+ /**
+ * Logger for this instance ( it will be used by sub-class )
+ */
+ protected Logger logger = LoggerFactory.getLogger( getClass() );
+
+ /**
+ * Name of the cancel operation)
+ */
+ public static final String COMMAND_CANCEL = "cancel";
+
+ /**
+ * Result after execution of command
+ */
+ protected T result;
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.core.command.Command#execute(org.tizen.common.core.command.Executor, org.tizen.common.core.command.ExecutionContext)
+ */
+ @Override
+ abstract public
+ void
+ run(
+ final Executor executor,
+ final ExecutionContext context
+ )
+ throws Exception;
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.core.command.Command#undo(org.tizen.common.core.command.Executor, org.tizen.common.core.command.ExecutionContext)
+ */
+ @Override
+ public void undo(
+ final Executor executor,
+ final ExecutionContext context
+ )
+ throws Exception
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.core.command.Command#getResult()
+ */
+ @Override
+ public
+ T
+ getResult()
+ {
+ return this.result;
+ }
+
+}
diff --git a/org.tizen.common/src/org/tizen/common/core/command/Command.java b/org.tizen.common/src/org/tizen/common/core/command/Command.java
new file mode 100644
index 000000000..c1b3f198e
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/core/command/Command.java
@@ -0,0 +1,69 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* GyeongSeok Seo <gyeongseok.seo@samsung.com>
+* BonYong Lee <bonyong.lee@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+package org.tizen.common.core.command;
+
+/**
+ * <p>
+ * Command.
+ *
+ * Behavior unit for functionality independing on environment( file system, ui, ... )
+ * </p>
+ *
+ * @param <T> Execution result type
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ */
+public interface
+Command<T>
+{
+ /**
+ * Execute unit functionality
+ *
+ * @param executor execution subject
+ * @param context execution context
+ *
+ * @throws Exception If Exception occur in execution
+ */
+ void run( Executor executor, ExecutionContext context ) throws Exception;
+
+ /**
+ * Execute undoing for execution if possible
+ *
+ * @param executor execution subject
+ * @param context execution context
+ *
+ * @throws Exception If Exception occur in undo
+ */
+ void undo( Executor executor, ExecutionContext context ) throws Exception;
+
+ /**
+ * Return execution result
+ *
+ * @return Execution result
+ */
+ T getResult();
+
+}
diff --git a/org.tizen.common/src/org/tizen/common/core/command/CommandCancelException.java b/org.tizen.common/src/org/tizen/common/core/command/CommandCancelException.java
new file mode 100644
index 000000000..c4e2b5758
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/core/command/CommandCancelException.java
@@ -0,0 +1,45 @@
+/*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * Ho Namkoong <ho.namkoong@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+
+package org.tizen.common.core.command;
+
+/**
+ * <p>
+ * CommandCancelException.
+ *
+ * This exception is thrown when run method of command is canceled by user operation.
+ * </p>
+ *
+ * @param <T> Execution result type
+ *
+ * @author Ho Namkoong{@literal <ho.namkoong@samsung.com>} (S-Core)
+ * @See Command
+ */
+
+public class CommandCancelException extends RuntimeException {
+
+ private static final long serialVersionUID = 1L;
+
+}
diff --git a/org.tizen.common/src/org/tizen/common/core/command/CompositeCommand.java b/org.tizen.common/src/org/tizen/common/core/command/CompositeCommand.java
new file mode 100644
index 000000000..4fdfba554
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/core/command/CompositeCommand.java
@@ -0,0 +1,103 @@
+/*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common.core.command;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+
+/**
+ * <p>
+ * CompositeCommand.
+ *
+ * Command to execute multiple {@link Command}s
+ * </p>
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ */
+public class
+CompositeCommand
+extends AbstractCommand<Object>
+{
+
+ /**
+ * {@link Command}s to execute
+ */
+ @SuppressWarnings("rawtypes")
+ protected final ArrayList<Command> commands = new ArrayList<Command>();
+
+ /**
+ * Constructor with {@link Command}s
+ *
+ * @param commands {@link Command}s to execute
+ *
+ * @see #addCommand(Command...)
+ */
+ public
+ CompositeCommand(
+ final Command<?>... commands
+ )
+ {
+ addCommand( commands );
+ }
+
+ /**
+ * Add {@link Command} to {@link Command}s to execute
+ *
+ * @param commands
+ *
+ * @see #commands
+ */
+ public
+ void
+ addCommand(
+ final Command<?>... commands
+ )
+ {
+ if ( null != commands )
+ {
+ this.commands.addAll( Arrays.asList( commands ) );
+ }
+ }
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.core.command.Command#execute(org.tizen.common.core.command.Executor, org.tizen.common.core.command.ExecutionContext)
+ */
+ @Override
+ public
+ void
+ run(
+ final Executor executor,
+ final ExecutionContext context
+ )
+ throws Exception
+ {
+ for ( final Command<Object> command : this.commands )
+ {
+ command.run( executor, context );
+ }
+
+ }
+
+}
diff --git a/org.tizen.common/src/org/tizen/common/core/command/EclipseExecutor.java b/org.tizen.common/src/org/tizen/common/core/command/EclipseExecutor.java
new file mode 100644
index 000000000..ff02a58d3
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/core/command/EclipseExecutor.java
@@ -0,0 +1,70 @@
+package org.tizen.common.core.command;
+
+import java.text.MessageFormat;
+
+import org.tizen.common.Factory;
+import org.tizen.common.core.command.policy.PolicyRegistry;
+import org.tizen.common.file.EclipseFileHandler;
+import org.tizen.common.file.FileHandler;
+
+public class
+EclipseExecutor
+extends Executor
+{
+ /**
+ * Contructor with prompter
+ *
+ * @param prompter {@link Prompter}
+ */
+ public
+ EclipseExecutor(
+ final Prompter prompter
+ )
+ {
+ super(
+ new Factory<ExecutionContext>() {
+
+ /**
+ * {@link FileHandler} for Command Line Interface
+ */
+ protected FileHandler fileHandler = new EclipseFileHandler();
+
+
+ /**
+ * <p>
+ * {@link PolicyRegistry} for Command Line Interface
+ * </p>
+ */
+ protected Factory<PolicyRegistry> factory = new PolicyRegistryFactory();
+
+ /**
+ * Create and return {@link PolicyRegistry}
+ *
+ * @return {@link PolicyRegistry} to be created
+ */
+ protected
+ PolicyRegistry
+ getRegistry()
+ {
+ return factory.create();
+ }
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.core.command.ExecutionContextFactory#create()
+ */
+ @Override
+ public
+ ExecutionContext
+ create()
+ {
+ return new ExecutionContext(
+ getRegistry(),
+ prompter,
+ fileHandler
+ );
+ }
+
+ }
+ );
+ }
+}
diff --git a/org.tizen.common/src/org/tizen/common/core/command/ExecutionContext.java b/org.tizen.common/src/org/tizen/common/core/command/ExecutionContext.java
new file mode 100644
index 000000000..0d68c2cf4
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/core/command/ExecutionContext.java
@@ -0,0 +1,138 @@
+/*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common.core.command;
+
+import org.tizen.common.core.command.policy.PolicyRegistry;
+import org.tizen.common.file.FileHandler;
+
+/**
+ * <p>
+ * ExecutionContext.
+ *
+ * Context in execution of commands
+ *
+ * Container for objects in execution envitonment
+ *
+ * It is injected by executor
+ * </p>
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ *
+ * @see Executor
+ */
+public class
+ExecutionContext
+{
+ /**
+ * Registry for {@link Policy}
+ */
+ protected final PolicyRegistry registry;
+
+ /**
+ * {@link Prompter} for user interaction
+ */
+ protected final Prompter prompter;
+
+ /**
+ * {@link FileHandler} for file system
+ */
+ protected final FileHandler fileHandler;
+
+
+ /**
+ * Constructor with {@link PolicyRegistry}, {@link Prompter} and {@link FileHandler}
+ *
+ * @param registry {@link PolicyRegistry} to use
+ * @param prompter {@link Prompter} to use
+ * @param fileHandler {@link FileHandler} to use
+ */
+ public
+ ExecutionContext(
+ final PolicyRegistry registry,
+ final Prompter prompter,
+ final FileHandler fileHandler
+ )
+ {
+ this.registry= registry;
+ this.prompter = prompter;
+ this.fileHandler = fileHandler;
+ }
+
+
+ /**
+ * Return {@link PolicyRegistry} to be using
+ *
+ * @return {@link PolicyRegistry}
+ */
+ public
+ PolicyRegistry
+ getPolicyRegistry()
+ {
+ return this.registry;
+ }
+
+ /**
+ * Return {@link Policy} for <code>name</code>
+ *
+ * @param name policy name
+ *
+ * @return {@link Policy} matching by <code>name<code>
+ *
+ * @see PolicyRegistry#getPolicy(String);
+ */
+ public
+ Policy
+ getPolicy(
+ final String name
+ )
+ {
+ return this.registry.getPolicy( name );
+ }
+
+ /**
+ * Return {@link Prompter} to be using
+ *
+ * @return {@link Prompter}
+ */
+ public
+ Prompter
+ getPrompter()
+ {
+ return this.prompter;
+ }
+
+ /**
+ * Return {@link FileHandler} to be using
+ *
+ * @return {@link FileHandler}
+ */
+ public
+ FileHandler
+ getFileHandler()
+ {
+ return this.fileHandler;
+ }
+
+}
diff --git a/org.tizen.common/src/org/tizen/common/core/command/Executor.java b/org.tizen.common/src/org/tizen/common/core/command/Executor.java
new file mode 100644
index 000000000..6cd4e291a
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/core/command/Executor.java
@@ -0,0 +1,213 @@
+/*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common.core.command;
+
+import static org.tizen.common.core.command.Policy.EXCEPTION_UNHANDLED;
+
+import java.lang.Thread.UncaughtExceptionHandler;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.tizen.common.Factory;
+
+
+/**
+ * <p>
+ * Executor.
+ *
+ * Execute command in specific environment
+ *
+ * Environment is specified by {@link #contextFactory}
+ *
+ * </p>
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ */
+public class
+Executor
+{
+ /**
+ * Logger for this instance
+ */
+ protected Logger logger = LoggerFactory.getLogger( getClass() );
+
+ /**
+ * Factory for {@link ExecutionContext}
+ */
+ protected Factory<ExecutionContext> contextFactory;
+
+ /**
+ * Cabinet for {@link ExecutionContext}
+ *
+ * Context is sustain in execution and destroy after exection
+ *
+ * @see #contextFactory
+ */
+ protected ThreadLocal<ExecutionContext> contexts = new ThreadLocal<ExecutionContext>()
+ {
+ /* (non-Javadoc)
+ * @see java.lang.ThreadLocal#initialValue()
+ */
+ @Override
+ protected
+ ExecutionContext
+ initialValue()
+ {
+ if ( null == contextFactory )
+ {
+ return null;
+ }
+ return contextFactory.create();
+ };
+ };
+
+ /**
+ * Default constructor
+ */
+ public
+ Executor()
+ {
+ }
+
+ /**
+ * Constructor with context factory
+ *
+ * @param factory context factory to use
+ *
+ * @see #setContextFactory(Factory)
+ */
+ public
+ Executor(
+ final Factory<ExecutionContext> factory
+ )
+ {
+ setContextFactory( factory );
+ }
+
+ /**
+ * Return context factory
+ *
+ * @return context factory in use
+ */
+ public
+ Factory<ExecutionContext>
+ getContextFactory()
+ {
+ return this.contextFactory;
+ }
+
+ /**
+ * Set context factory
+ *
+ * @param factory context factory to use
+ */
+ public
+ void
+ setContextFactory(
+ final Factory<ExecutionContext> factory
+ )
+ {
+ logger.info( "ExecutionContextFactory :{}", factory );
+ this.contextFactory = factory;
+ }
+
+ /**
+ * Execute <code>commands</code>
+ *
+ * @param commands {@link Command}s
+ */
+ public
+ void
+ execute(
+ final Command<?>... commands
+ )
+ {
+ logger.trace( "Commands :{}", commands );
+ contexts.remove();
+
+ execute( contexts.get(), commands );
+
+ }
+ public
+ void
+ execute(
+ final ExecutionContext context,
+ final Command<?>... commands
+ )
+ {
+
+ try {
+ for ( final Command<?> command : commands )
+ {
+ command.run( this, context );
+ }
+ } catch ( final Exception e ) {
+ final Policy policy = context.getPolicy( EXCEPTION_UNHANDLED );
+ if ( null == policy )
+ { // No policy
+ logger.error( "Error occured", e );
+ return ;
+ }
+
+ final UncaughtExceptionHandler handler = policy.adapt( UncaughtExceptionHandler.class );
+ if ( null == handler )
+ {
+ throw new IllegalStateException( e );
+ }
+ handler.uncaughtException( Thread.currentThread(), e );
+ }
+ finally
+ {
+ contexts.remove();
+ }
+ }
+
+ /**
+ * Execute <code>command</code> in <code>context</code>
+ *
+ * @param command {@link Command} to run
+ * @param context {@link ExecutionContext} to run in
+ */
+ public void
+ run(
+ final Command<?> command,
+ final ExecutionContext context
+ )
+ throws Exception
+ {
+ command.run( this, context );
+ }
+
+ /**
+ * Return {@link ExecutionContext} in context
+ *
+ * @return {@link ExecutionContext}
+ */
+ public ExecutionContext
+ getContext()
+ {
+ return contexts.get();
+ }
+}
diff --git a/org.tizen.common/src/org/tizen/common/core/command/Policy.java b/org.tizen.common/src/org/tizen/common/core/command/Policy.java
new file mode 100644
index 000000000..479d2f344
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/core/command/Policy.java
@@ -0,0 +1,154 @@
+/*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common.core.command;
+
+import org.tizen.common.Adaptable;
+
+
+/**
+ * <p>
+ * Policy.
+ *
+ * Adapter to other class when specific situation
+ *
+ * Situation specification is defined by naming rule
+ *
+ * Situation is define hierachically and is like tree structure
+ *
+ * Situation name has qualified name separating dot( '.' ).
+ *
+ * Each name fragment means node name in tree and qualified name stands for unique path.
+ *
+ * If there is no matching policy in registry, it provide policy having least distance.
+ *
+ * <ul>
+ * <li>nonexist
+ * <ul>
+ * <li>file
+ * <ul>
+ * <li>in</li>
+ * </ul>
+ * </li>
+ * <li>dir
+ * <ul>
+ * <li>in
+ * <ul>
+ * <li>project</li>
+ * </ul>
+ * </li>
+ * </ul>
+ * </li>
+ * </ul>
+ * </li>
+ * <li>exist
+ * <ul>
+ * <li>file
+ * <ul>
+ * <li>out
+ * <ul>
+ * <li>wgt</li>
+ * </ul>
+ * </li>
+ * </ul>
+ * </ul>
+ * </li>
+ * <li>exception
+ * <ul>
+ * <li>unhandled</li>
+ * <li>file
+ * <ul>
+ * <li>out
+ * <ul>
+ * <li>wgt</li>
+ * </ul>
+ * </li>
+ * </ul>
+ * </li>
+ * </ul>
+ * </li>
+ * </ul>
+ *
+ * </p>
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ */
+public interface
+Policy
+extends Adaptable
+{
+ /**
+ * When input file doesn't exist
+ */
+ String NONEXIST_IN_FILE = "nonexist.file.in";
+
+ /**
+ * When input sign profile
+ */
+ String NONEXIST_IN_FILE_SIGN_PROFILE = "nonexist.file.in.signprofile";
+
+ /**
+ * When input directory doesn't exist
+ */
+ String NONEXIST_IN_DIRECTORY = "nonexist.dir.in";
+
+ /**
+ * When input project directory doesn't exist
+ */
+ String NONEXIST_IN_PROJECT = "nonexist.dir.in.project";
+
+ /**
+ * When output file already exists
+ */
+ String EXIST_OUT_FILE = "exist.file.out";
+ /**
+ * When output widget file already exists
+ */
+ String EXIST_OUT_WGT = "exist.file.out.wgt";
+
+ /**
+ * When target file is already exist.
+ */
+ String EXIST_FILE_WHEN_COPY = "exist.file.when.copy";
+
+ /**
+ * When unexpected exception occured
+ */
+ String EXCEPTION_UNHANDLED = "exception.unhandled";
+ /**
+ * When exception occured in handling output widget file
+ */
+ String EXCEPTION_OUT_WGT = "exception.file.out.wgt";
+
+ String PRINTOUT_RESULT_SIGNING = "printout.result.signing";
+
+ /**
+ * Return policy name
+ *
+ * policy name is unique indentifier
+ *
+ * @return policy name
+ */
+ String getName();
+}
diff --git a/org.tizen.common/src/org/tizen/common/core/command/PolicyRegistryFactory.java b/org.tizen.common/src/org/tizen/common/core/command/PolicyRegistryFactory.java
new file mode 100644
index 000000000..d055af04d
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/core/command/PolicyRegistryFactory.java
@@ -0,0 +1,240 @@
+/*
+ * Web IDE - Command Line Interface
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common.core.command;
+
+import static org.tizen.common.core.command.Policy.EXIST_OUT_FILE;
+import static org.tizen.common.core.command.Policy.NONEXIST_IN_FILE;
+import static org.tizen.common.core.command.Policy.EXIST_FILE_WHEN_COPY;
+import static org.tizen.common.core.command.Policy.EXCEPTION_UNHANDLED;
+import java.io.File;
+import org.tizen.common.Factory;
+import org.tizen.common.core.command.policy.AbstractPolicy;
+import org.tizen.common.core.command.policy.FilePolicy;
+import org.tizen.common.core.command.policy.MessagePolicy;
+import org.tizen.common.core.command.policy.OptionPolicy;
+import org.tizen.common.core.command.policy.PolicyRegistry;
+import org.tizen.common.core.command.policy.UncaughtExceptionHandlingPolicy;
+import org.tizen.common.core.command.prompter.RunableOption;
+import org.tizen.common.file.StandardFileHandler;
+
+/**
+ * <p>
+ * PolicyRegistryFactory.
+ *
+ * {@link Factory} to provide {@link PolicyRegistry} in eclipse ide
+ *
+ * </p>
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ */
+public class
+PolicyRegistryFactory
+implements Factory<PolicyRegistry>
+{
+ /**
+ * <p>
+ * CLIPolicy.
+ *
+ * {@link Policy} when command line interface
+ * </p>
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ *
+ * @see PolicyRegistry, {@link Policy}
+ */
+ class EclipsePolicy
+ extends AbstractPolicy
+ {
+ /**
+ * <p>
+ * Constructor with <code>name</code>
+ * </p>
+ *
+ * @param name policy name
+ */
+ public EclipsePolicy( final String name )
+ {
+ super( name );
+ }
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.Adaptable#adapt(java.lang.Class)
+ */
+ @Override
+ @SuppressWarnings("unchecked")
+ public <T>
+ T
+ adapt(
+ final Class<T> clazz
+ )
+ {
+ if ( clazz.isAssignableFrom( FilePolicy.class ) )
+ {
+ return (T) FilePolicy.STOP_PROCESS;
+ }
+ else if ( clazz.isAssignableFrom( MessagePolicy.class) )
+ {
+ return (T) MessagePolicy.PROMPTER;
+ }
+ else if ( clazz.isAssignableFrom(UncaughtExceptionHandlingPolicy.class))
+ {
+ return (T) UncaughtExceptionHandlingPolicy.INSTANCE;
+ }
+ return null;
+ }
+
+ }
+ /* (non-Javadoc)
+ * @see org.tizen.common.Factory#create()
+ */
+ @Override
+ public
+ PolicyRegistry
+ create()
+ {
+ final PolicyRegistry registry = new PolicyRegistry();
+
+ registry.register( new EclipsePolicy( EXIST_FILE_WHEN_COPY ) {
+ @SuppressWarnings("unchecked")
+ @Override
+ public <T> T adapt(Class<T> clazz) {
+ if(clazz.isAssignableFrom(OptionPolicy.class)) {
+
+ RunableOption overwrite = new RunableOption("overwrite") {
+
+ private StandardFileHandler handler = new StandardFileHandler();
+
+ @Override
+ public void runWithArgument(Object... args) throws Exception {
+ if(args.length != 2) {
+ throw new IllegalArgumentException("argument length is wrong");
+ }
+
+ if(!(args[0] instanceof File && args[1] instanceof File)) {
+ throw new IllegalArgumentException("argument type is wrong");
+ }
+
+ File sourceFile = ((File)args[0]);
+ File targetFile = ((File)args[1]);
+
+ handler.copyFile(sourceFile.getPath(), targetFile.getPath());
+ }
+
+ @Override
+ public boolean isDefault() {
+ return false;
+ }
+ };
+
+ RunableOption ignore = new RunableOption("ignore") {
+
+ @Override
+ public boolean isDefault() {
+ return true;
+ }
+
+ @Override
+ protected void runWithArgument(Object... args) throws Exception{
+ }
+ };
+
+ RunableOption overwriteAll = new RunableOption("overwriteAll") {
+
+ private StandardFileHandler handler = new StandardFileHandler();
+
+ @Override
+ public boolean isDefault() {
+ return false;
+ }
+
+ @Override
+ protected void runWithArgument(Object... args) throws Exception {
+ super.setAllFlag(true);
+
+ if(args.length != 2) {
+ throw new IllegalArgumentException("argument length is wrong");
+ }
+
+ if(!(args[0] instanceof File && args[1] instanceof File)) {
+ throw new IllegalArgumentException("argument type is wrong");
+ }
+
+ File sourceFile = ((File)args[0]);
+ File targetFile = ((File)args[1]);
+
+ handler.copyFile(sourceFile.getPath(), targetFile.getPath());
+ }
+ };
+
+ RunableOption ignoreAll = new RunableOption("ignoreAll") {
+
+ @Override
+ public boolean isDefault() {
+ return false;
+ }
+
+ @Override
+ protected void runWithArgument(Object... args) throws Exception{
+ super.setAllFlag(true);
+ }
+ };
+
+ RunableOption cancel = new RunableOption("cancel") {
+
+ @Override
+ public boolean isDefault() {
+ return false;
+ }
+
+ @Override
+ protected void runWithArgument(Object... args) throws Exception{
+ }
+ };
+
+ return (T)(new OptionPolicy(overwrite, ignore, overwriteAll, ignoreAll, cancel));
+ }
+ return super.adapt(clazz);
+ }
+ });
+
+ registry.register(new EclipsePolicy(EXCEPTION_UNHANDLED) {
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public <T> T adapt(Class<T> clazz) {
+ if ( clazz.isAssignableFrom(UncaughtExceptionHandlingPolicy.class))
+ {
+ return (T) UncaughtExceptionHandlingPolicy.INSTANCE;
+ }
+ return null;
+ }
+ });
+ registry.register( new EclipsePolicy(EXIST_OUT_FILE));
+ registry.register( new EclipsePolicy( NONEXIST_IN_FILE ) );
+
+ return registry;
+ }
+
+}
diff --git a/org.tizen.common/src/org/tizen/common/core/command/Prompter.java b/org.tizen.common/src/org/tizen/common/core/command/Prompter.java
new file mode 100644
index 000000000..a76752b74
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/core/command/Prompter.java
@@ -0,0 +1,94 @@
+/*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common.core.command;
+
+import org.tizen.common.core.command.prompter.Option;
+
+/**
+ * <p>
+ * Prompter.
+ *
+ * Handle user interaction
+ * <ul>
+ * <li>user input</li>
+ * <li>message output</li>
+ * <ul>
+ *
+ * </p>
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ */
+public interface
+Prompter
+{
+ /**
+ * <p>
+ * Input user selection.
+ *
+ * The selection must be in <code>options</code>
+ * </p>
+ *
+ * @param question selection message
+ * @param options options to choice
+ *
+ * @return user selection
+ */
+ Option interact( final String question, final Option... options );
+
+ /**
+ * <p>
+ * Input user input as password
+ *
+ * Password must be secured
+ * </p>
+ *
+ * @param message message for user password
+ *
+ * @return user input as password
+ */
+ char[] password( String message );
+
+ /**<p>
+ * Print out error message
+ * </p>
+ *
+ * @param message error message
+ */
+ void error( final String message );
+
+ /**
+ * Print out information message to notify
+ *
+ * @param message notification message
+ */
+ void notify( final String message );
+
+ /**
+ * User cancle work in process
+ */
+ void cancel();
+
+
+}
diff --git a/org.tizen.common/src/org/tizen/common/core/command/file/DirectoryCopyHandlingCommand.java b/org.tizen.common/src/org/tizen/common/core/command/file/DirectoryCopyHandlingCommand.java
new file mode 100644
index 000000000..d1ea1f65b
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/core/command/file/DirectoryCopyHandlingCommand.java
@@ -0,0 +1,145 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* Ho Namkoong <ho.namkoong@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+package org.tizen.common.core.command.file;
+
+import java.io.File;
+import java.util.List;
+import java.util.Stack;
+
+import org.tizen.common.core.command.AbstractCommand;
+import org.tizen.common.core.command.CommandCancelException;
+import org.tizen.common.core.command.ExecutionContext;
+import org.tizen.common.core.command.Executor;
+import org.tizen.common.core.command.Policy;
+import org.tizen.common.core.command.policy.OptionPolicy;
+import org.tizen.common.core.command.prompter.Option;
+import org.tizen.common.core.command.prompter.RunableOption;
+import org.tizen.common.file.StandardFileHandler;
+import org.tizen.common.util.log.Logger;
+
+/**
+ * <p>
+ * DirectoryCopyHandlingCommand.
+ * This class is used for copying source directory to the target directory.
+ * {@link FileHandlingCommand}
+ * </p>
+ *
+ * @author Ho Namkoong{@literal <ho.namkoong@samsung.com>} (S-Core)
+ */
+
+public class DirectoryCopyHandlingCommand extends FileHandlingCommand<Boolean> {
+
+ /**
+ * List of target path
+ */
+ protected List<String> targetPathList;
+
+ /**
+ * List of source path
+ */
+ protected List<String> sourcePathList;
+
+ public DirectoryCopyHandlingCommand(List<String> sourcePathList, List<String> targetPathList) throws IllegalArgumentException{
+ if(sourcePathList.size() != targetPathList.size()) {
+ throw new IllegalArgumentException("Lenghs of sourcePathList and target paths are not same");
+ }
+ this.sourcePathList = sourcePathList;
+ this.targetPathList = targetPathList;
+ }
+
+
+ @Override
+ public void run(Executor executor, ExecutionContext context)
+ throws Exception {
+ StandardFileHandler handler = new StandardFileHandler();
+ Policy policy = context.getPolicy(Policy.EXIST_FILE_WHEN_COPY);
+ OptionPolicy optionPolicy = policy.adapt( OptionPolicy.class );
+ Option[] options = optionPolicy.getOptions();
+
+ for(Option option: options) {
+ if(!(option instanceof RunableOption)) {
+ throw new IllegalArgumentException("Option " + option.getName() + " is not RunnableOption");
+ }
+ }
+
+ for(int i =0; i< sourcePathList.size(); i++) {
+ String sourcePath = sourcePathList.get(i);
+ String targetPath = targetPathList.get(i);
+
+ final Stack<File> sourceStack = new Stack<File>();
+ final Stack<File> targetStack = new Stack<File>();
+ sourceStack.push( new File(sourcePath ) );
+ targetStack.push( new File( targetPath ) );
+
+ while ( !sourceStack.isEmpty() )
+ {
+ final File sourceFile = sourceStack.pop();
+ final File targetFile = targetStack.pop();
+
+ if ( sourceFile.isDirectory() )
+ {
+ handler.makeDirectory(targetFile.getPath());
+ for ( final File sourceChild : sourceFile.listFiles() )
+ {
+ sourceStack.push( sourceChild );
+ targetStack.push( new File( targetFile, sourceChild.getName() ) );
+ }
+ }
+ else if(sourceFile.isFile()) {
+ if(targetFile.exists()) {
+ boolean selectionDone = false;
+ RunableOption resultOption = null;
+
+ for (Option option : options) {
+ if(((RunableOption)option).isAllFlag()) {
+ resultOption = (RunableOption)option;
+ selectionDone = true;
+ break;
+ }
+ }
+
+ if(!selectionDone) {
+ resultOption = (RunableOption)context.getPrompter().interact(targetFile.getCanonicalPath() + " already exist", options);
+ }
+ if(AbstractCommand.COMMAND_CANCEL.equals(resultOption.getName())) {
+ throw new CommandCancelException();
+ }
+
+ resultOption.setArgument(sourceFile, targetFile);
+ resultOption.run();
+ }
+ else {
+ System.out.println(targetFile);
+ targetFile.createNewFile();
+ handler.copyFile(sourceFile.getPath(), targetFile.getPath());
+ }
+ }
+ else {
+ Logger.error(sourceFile + " is not file or directory");
+ }
+ }
+ }
+ }
+}
diff --git a/org.tizen.common/src/org/tizen/common/core/command/file/FileHandlingCommand.java b/org.tizen.common/src/org/tizen/common/core/command/file/FileHandlingCommand.java
new file mode 100644
index 000000000..78f079e27
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/core/command/file/FileHandlingCommand.java
@@ -0,0 +1,192 @@
+/*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common.core.command.file;
+
+import org.tizen.common.FactoryWithArgument;
+import org.tizen.common.core.command.AbstractCommand;
+import org.tizen.common.core.command.Command;
+import org.tizen.common.core.command.ExecutionContext;
+import org.tizen.common.core.command.Executor;
+import org.tizen.common.file.Filter;
+import org.tizen.common.file.SimpleFileFilter;
+import org.tizen.common.file.filter.WildCardFilterFactory;
+
+/**
+ * FileHandlingCommand.
+ *
+ * Abstract class for file handling {@link Command}
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ */
+public class
+FileHandlingCommand<T>
+extends AbstractCommand<T>
+{
+ /**
+ * Factory to create file name pattern filter
+ */
+ protected FactoryWithArgument<Filter, String> filterFactory = new WildCardFilterFactory();
+
+ /**
+ * File name filter
+ */
+ protected SimpleFileFilter filter = new SimpleFileFilter();
+
+ /**
+ * Handling main path
+ */
+ protected String path;
+
+ /**
+ * Set filter factory
+ *
+ * @param factory {@link FactoryWithArgument<Filter, String>}
+ *
+ * @see WildCardFilterFactory
+ */
+ public
+ void
+ setFilterFactory(
+ final FactoryWithArgument<Filter, String> factory
+ )
+ {
+ this.filterFactory = factory;
+ logger.debug( "Configured filter factory :{}", factory );
+ }
+
+ /**
+ * Set filter
+ * @param filter {@link SimpleFileFilter}
+ */
+ public
+ void
+ setFilter( SimpleFileFilter filter )
+ {
+ if ( null == filter )
+ {
+ throw new NullPointerException();
+ }
+ this.filter = filter;
+ logger.debug( "Configured filter :{}", filter );
+ }
+
+ /**
+ * Set including file name patterns
+ *
+ * @param includes including file name patterns
+ */
+ public
+ void
+ setIncludes(
+ final String[] includes
+ )
+ {
+ filter.clearIncludes();
+ if ( null != includes )
+ {
+ for ( final String include : includes )
+ {
+ filter.addIncludes( filterFactory.create( include ) );
+ }
+ }
+ }
+
+ /**
+ * Set excluding file name patterns
+ *
+ * @param excludes excluding file name patterns
+ */
+ public
+ void
+ setExcludes(
+ final String[] excludes
+ )
+ {
+ filter.clearExcludes();
+ if ( null != excludes )
+ {
+ for ( final String exclude : excludes )
+ {
+ filter.addExcludes( filterFactory.create( exclude ) );
+ }
+ }
+ }
+
+ /**
+ * Return main working path
+ *
+ * @return {@link #path}
+ */
+ public
+ String
+ getPath()
+ {
+ return this.path;
+ }
+
+ /**
+ * Set main working path
+ *
+ * @param path main working path
+ */
+ public
+ void
+ setPath(
+ final String path
+ )
+ {
+ this.path = path;
+ }
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.core.command.AbstractCommand#execute(org.tizen.common.core.command.Executor, org.tizen.common.core.command.ExecutionContext)
+ */
+ @Override
+ public
+ void
+ run(
+ final Executor executor,
+ final ExecutionContext context
+ )
+ throws Exception
+ {
+ throw new UnsupportedOperationException();
+
+ }
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.core.command.AbstractCommand#undo(org.tizen.common.core.command.Executor, org.tizen.common.core.command.ExecutionContext)
+ */
+ @Override
+ public
+ void
+ undo(
+ final Executor executor,
+ final ExecutionContext context
+ )
+ throws Exception {
+ throw new UnsupportedOperationException();
+ }
+}
diff --git a/org.tizen.common/src/org/tizen/common/core/command/file/WriteFileCommand.java b/org.tizen.common/src/org/tizen/common/core/command/file/WriteFileCommand.java
new file mode 100644
index 000000000..9b60e18a5
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/core/command/file/WriteFileCommand.java
@@ -0,0 +1,40 @@
+package org.tizen.common.core.command.file;
+
+import java.io.ByteArrayInputStream;
+
+import org.tizen.common.core.command.ExecutionContext;
+import org.tizen.common.core.command.Executor;
+import org.tizen.common.util.ObjectUtil;
+
+public class
+WriteFileCommand
+extends FileHandlingCommand<Boolean>
+{
+ protected final byte[] contents;
+
+ public WriteFileCommand( final String path, final byte[] contents )
+ {
+ setPath( path );
+ this.contents = contents;
+ }
+
+ @Override
+ public
+ void
+ run(
+ final Executor executor,
+ final ExecutionContext context
+ )
+ throws Exception
+ {
+ final byte[] safeBytes = ObjectUtil.nvl( contents, new byte[0] );
+
+ logger.trace( "Trying write {} in {} bytes", path, safeBytes.length );
+
+ context.getFileHandler().write(
+ path,
+ new ByteArrayInputStream( safeBytes )
+ );
+ }
+
+}
diff --git a/org.tizen.common/src/org/tizen/common/core/command/policy/AbstractMessagePolicy.java b/org.tizen.common/src/org/tizen/common/core/command/policy/AbstractMessagePolicy.java
new file mode 100644
index 000000000..1c1ca7679
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/core/command/policy/AbstractMessagePolicy.java
@@ -0,0 +1,66 @@
+/*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common.core.command.policy;
+
+import static org.tizen.common.util.StringUtil.NULL_STRING;
+
+import java.text.MessageFormat;
+
+/**
+ * AbstractMessagePolicy.
+ *
+ * Abstract class for {@link MessagePolicy}
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ */
+abstract public class
+AbstractMessagePolicy
+implements MessagePolicy
+{
+
+ /**
+ * Provide common formatting rule
+ *
+ * @param format message format
+ * @param args message arguments
+ *
+ * @return formatted message
+ */
+ protected
+ String
+ format(
+ final String format,
+ final Object... args
+ )
+ {
+ if ( null == format )
+ {
+ return NULL_STRING;
+ }
+ return MessageFormat.format( format, args );
+
+ }
+
+}
diff --git a/org.tizen.common/src/org/tizen/common/core/command/policy/AbstractPolicy.java b/org.tizen.common/src/org/tizen/common/core/command/policy/AbstractPolicy.java
new file mode 100644
index 000000000..25b12a551
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/core/command/policy/AbstractPolicy.java
@@ -0,0 +1,73 @@
+/*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common.core.command.policy;
+
+import org.tizen.common.core.command.Policy;
+
+/**
+ * AbstractPolicy.
+ *
+ * Abstract class for {@link Policy}
+ *
+ * All policy must have name and can't change it
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ */
+abstract public class
+AbstractPolicy
+implements Policy
+{
+
+ /**
+ * Policy name
+ */
+ protected final String name;
+
+ /**
+ * Constructor with policy name
+ *
+ * @param name poclicy name
+ *
+ * @see Policy
+ */
+ public
+ AbstractPolicy(
+ final String name
+ )
+ {
+ this.name = name;
+ }
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.core.command.Policy#getName()
+ */
+ @Override
+ public
+ String
+ getName()
+ {
+ return this.name;
+ }
+}
diff --git a/org.tizen.common/src/org/tizen/common/core/command/policy/FilePolicy.java b/org.tizen.common/src/org/tizen/common/core/command/policy/FilePolicy.java
new file mode 100644
index 000000000..d70487f09
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/core/command/policy/FilePolicy.java
@@ -0,0 +1,76 @@
+/*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common.core.command.policy;
+
+
+/**
+ * FilePolicy.
+ *
+ * File handling policy
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ */
+public enum
+FilePolicy
+{
+ /**
+ * <p>
+ * Stop process.
+ *
+ * Throw exception
+ * </p>
+ */
+ STOP_PROCESS,
+
+ /**
+ * <p>
+ * Skip process.
+ *
+ * Don't throw exception
+ * </p>
+ */
+ SKIP,
+
+ /**
+ * <p>
+ * overwwrite when already exist
+ * </p>
+ */
+ OVERWRITE,
+
+ /**
+ * <p>
+ * Make directory when directory doesn't exist
+ * </p>
+ */
+ MAKE_DIR,
+
+ /**
+ * <p>
+ * Make file when file doesn't exist
+ * </p>
+ */
+ MAKE_FILE
+}
diff --git a/org.tizen.common/src/org/tizen/common/core/command/policy/MessagePolicy.java b/org.tizen.common/src/org/tizen/common/core/command/policy/MessagePolicy.java
new file mode 100644
index 000000000..379c601c5
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/core/command/policy/MessagePolicy.java
@@ -0,0 +1,146 @@
+/*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common.core.command.policy;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.tizen.common.core.command.Prompter;
+
+/**
+ * FilePolicy.
+ *
+ * File handling policy
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ */
+public interface
+MessagePolicy
+{
+ /**
+ * Print out message
+ *
+ * @param prompter {@link Prompter}
+ * @param format message format
+ * @param args message arguments
+ */
+ void
+ print(
+ final Prompter prompter,
+ final String format,
+ final Object... args
+ );
+
+ /**
+ * Print out error message
+ * @param prompter {@link Prompter}
+ * @param format message format
+ * @param args message arguments
+ */
+ void
+ error(
+ final Prompter prompter,
+ final String format,
+ final Object... args
+ );
+
+ /**
+ * {@link MessagePolicy} to print out using logger
+ *
+ * FIXME caller fqcn is constants
+ */
+ MessagePolicy LOGGING = new AbstractMessagePolicy()
+ {
+ /**
+ * Logger to use for message printing
+ */
+ protected final Logger logger =
+ LoggerFactory.getLogger( getClass() );
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.core.command.policy.MessagePolicy#print(org.tizen.common.core.command.Prompter, java.lang.String, java.lang.Object[])
+ */
+ @Override
+ public
+ void
+ print(
+ final Prompter prompter,
+ final String format,
+ final Object... args
+ )
+ {
+ logger.debug( format( format, args ) );
+ }
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.core.command.policy.MessagePolicy#error(org.tizen.common.core.command.Prompter, java.lang.String, java.lang.Object[])
+ */
+ @Override
+ public void error(
+ final Prompter prompter,
+ final String format,
+ final Object... args
+ )
+ {
+ logger.error( format( format, args ) );
+ }
+ };
+
+ /**
+ * {@link MessagePolicy} to print out using {@link Prompter}
+ */
+ MessagePolicy PROMPTER = new AbstractMessagePolicy()
+ {
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.core.command.policy.MessagePolicy#print(org.tizen.common.core.command.Prompter, java.lang.String, java.lang.Object[])
+ */
+ @Override
+ public
+ void
+ print(
+ final Prompter prompter,
+ final String format,
+ final Object... args
+ )
+ {
+ prompter.notify( format( format, args ) );
+ }
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.core.command.policy.MessagePolicy#error(org.tizen.common.core.command.Prompter, java.lang.String, java.lang.Object[])
+ */
+ @Override
+ public void error(
+ final Prompter prompter,
+ final String format,
+ final Object... args
+ )
+ {
+ prompter.error( format( format, args ) );
+
+ }
+ };
+
+}
diff --git a/org.tizen.common/src/org/tizen/common/core/command/policy/OptionPolicy.java b/org.tizen.common/src/org/tizen/common/core/command/policy/OptionPolicy.java
new file mode 100644
index 000000000..df6e4821f
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/core/command/policy/OptionPolicy.java
@@ -0,0 +1,60 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* Ho Namkoong <ho.namkoong@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+
+package org.tizen.common.core.command.policy;
+
+import org.tizen.common.core.command.prompter.Option;
+
+/**
+ * OptionPolicy
+ * This policy returns options which are needed for Prompt#interact(final String question, final Option... options).
+ * @See Command, Prompter
+ * @author Changhyun Lee {@literal <changhyun1.lee@samsung.com>} (S-Core)
+ */
+
+public class OptionPolicy {
+
+ protected Option[] options;
+
+ /**
+ * <p>
+ * Constructor with <code>options</code>
+ * </p>
+ *
+ * @param options options which this policy will return.
+ */
+ public OptionPolicy(Option... options) {
+ this.options = options;
+ }
+
+ /**
+ * Returns options this policy has.
+ *
+ * @return return options.
+ */
+ public Option[] getOptions() {
+ return options;
+ }
+}
diff --git a/org.tizen.common/src/org/tizen/common/core/command/policy/PolicyRegistry.java b/org.tizen.common/src/org/tizen/common/core/command/policy/PolicyRegistry.java
new file mode 100644
index 000000000..0308d6ac6
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/core/command/policy/PolicyRegistry.java
@@ -0,0 +1,294 @@
+/*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common.core.command.policy;
+
+import java.util.HashMap;
+
+import org.tizen.common.core.command.Policy;
+import org.tizen.common.util.StringUtil;
+
+
+/**
+ * <p>
+ * PolicyRegistry.
+ *
+ * Registry for {@link Policy}
+ *
+ * {@link Policy} is stored in tree-like structure
+ *
+ * A node has {@link Policy} or doesn't
+ *
+ * A node has multiple child nodes
+ *
+ * Policy's location is made a decision by its name
+ *
+ * name is composed of subname and separator( "<b>.</b>" )
+ *
+ * example for name is following
+ * <ul>
+ * <li>invalid.input.format.file</li>
+ * <li>nonexist.input.file</li>
+ * <li>exist.output.file</li>
+ * </ul>
+ * </p>
+ * @author bylee
+ *
+ */
+public class PolicyRegistry
+{
+ /**
+ * Node.
+ *
+ * Node for tree structure
+ *
+ * @author bylee
+ *
+ */
+ class Node
+ {
+
+ /**
+ * {@link Policy} stored in node
+ */
+ protected Policy policy;
+
+ /**
+ * Default constructor
+ */
+ public Node()
+ {
+ }
+
+ /**
+ * Constructor with {@link Policy}
+ *
+ * @param policy {@link Policy} to store
+ */
+ public Node(
+ final Policy policy
+ )
+ {
+ this.policy = policy;
+ }
+
+ protected final HashMap<String, Node> name2child =
+ new HashMap<String, PolicyRegistry.Node>();
+
+ /**
+ * Rerturn {@link Policy} to be stored
+ *
+ * @return policy to be stored
+ */
+ public Policy getPolicy()
+ {
+ return this.policy;
+ }
+
+ /**
+ * Set policy
+ *
+ * @param policy {@link Policy} to store
+ */
+ public void setPolicy(
+ final Policy policy
+ )
+ {
+ this.policy = policy;
+ }
+
+
+ /**
+ * Get child node with <code>name</code> in this node
+ *
+ * @param name node's name
+ *
+ * @return child node with <code>name</code>
+ */
+ public Node getChild(
+ final String name
+ )
+ {
+ return name2child.get( name );
+ }
+
+ /**
+ * Add <code>node</code> with <code>name</code> as child
+ *
+ * @param name node name
+ * @param node node to add
+ */
+ public void addChild( final String name, Node node )
+ {
+ name2child.put( name, node );
+ }
+ }
+
+ /**
+ * No-operation policy. Missing object pattern
+ */
+ protected Policy noOp = new AbstractPolicy( "" )
+ {
+ /* (non-Javadoc)
+ * @see org.tizen.common.Adaptable#adapt(java.lang.Class)
+ */
+ @Override
+ public <T> T adapt( final Class<T> clazz )
+ {
+ return null;
+ }
+ };
+
+ /**
+ * Root node( in tree structure)
+ */
+ protected Node root = new Node();
+
+ /**
+ * Constructor with {@link Policy}s
+ *
+ * @param policies {@link Policy}s to add
+ *
+ * @see #register(Policy)
+ */
+ public
+ PolicyRegistry(
+ final Policy... policies
+ )
+ {
+ if ( null == policies )
+ {
+ return ;
+ }
+
+ register( policies );
+ }
+
+ /**
+ * Add <code>policies</code> to registry
+ *
+ * @param policies {@link Policy}s to add
+ */
+ public void
+ register(
+ final Policy... policies
+ )
+ {
+ for ( final Policy policy : policies )
+ {
+ final String name = policy.getName();
+
+ final Node node = createNode( name );
+
+ if ( null != node.getPolicy() )
+ {
+ throw new IllegalArgumentException( "Policy is duplicated" );
+ }
+
+ node.setPolicy( policy );
+ }
+
+ }
+
+ /**
+ * Create node with <code>path</code> in tree
+ *
+ * @param path node path from root in tree
+ *
+ * @return {@link Node} to be specified with <code>path</code>
+ */
+ public Node createNode( final String path )
+ {
+ final String[] fragments = StringUtil.split( path, "." );
+
+ Node iter = root;
+
+ for ( int i = 0, n = fragments.length ; i < n ; ++i )
+ {
+ Node child = iter.getChild( fragments[i] );
+ if ( null == child )
+ {
+ child = new Node();
+ iter.addChild( fragments[i], child );
+ }
+
+ iter = child;
+ }
+
+ return iter;
+ }
+
+ /**
+ * Return {@link Policy} from tree with <code>path</code>
+ *
+ * Return ancestor node's policy unless matching exactly
+ *
+ * @param path
+ *
+ * @return {@link Policy}
+ */
+ public Policy
+ getPolicy( final String path )
+ {
+ if ( StringUtil.isEmpty( path ) )
+ {
+ return noOp;
+ }
+ final String[] fragments = StringUtil.split( path, "." );
+
+ Node iter = root;
+
+ Policy policy = null;
+
+ for ( int i = 0, n = fragments.length ; i < n ; ++i )
+ {
+ if ( null != iter.getPolicy() )
+ {
+ policy = iter.getPolicy();
+ }
+
+ Node child = iter.getChild( fragments[i] );
+ if ( null == child )
+ {
+ return policy;
+ }
+ iter = child;
+ }
+
+ if ( null == iter.getPolicy() )
+ {
+ return policy;
+ }
+ return iter.getPolicy();
+ }
+
+ /* (non-Javadoc)
+ * @see java.lang.Object#toString()
+ */
+ @Override
+ public String toString()
+ {
+ return getClass().getSimpleName() + "@" + Integer.toHexString( hashCode() ).substring( 0, 4 );
+ }
+}
diff --git a/org.tizen.common/src/org/tizen/common/core/command/policy/SimplePolicy.java b/org.tizen.common/src/org/tizen/common/core/command/policy/SimplePolicy.java
new file mode 100644
index 000000000..d0f7638cd
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/core/command/policy/SimplePolicy.java
@@ -0,0 +1,49 @@
+/*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common.core.command.policy;
+
+import org.tizen.common.core.command.Policy;
+
+public class SimplePolicy
+implements Policy {
+
+ protected String name;
+
+ public SimplePolicy( final String name )
+ {
+ this.name = name;
+ }
+ @Override
+ public <T> T adapt(Class<T> clazz) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public String getName() {
+ return name;
+ }
+
+}
diff --git a/org.tizen.common/src/org/tizen/common/core/command/policy/UncaughtExceptionHandlingPolicy.java b/org.tizen.common/src/org/tizen/common/core/command/policy/UncaughtExceptionHandlingPolicy.java
new file mode 100644
index 000000000..f16f9c712
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/core/command/policy/UncaughtExceptionHandlingPolicy.java
@@ -0,0 +1,113 @@
+/*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * Ho Namkoong <ho.namkoong@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common.core.command.policy;
+
+import java.lang.Thread.UncaughtExceptionHandler;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.tizen.common.core.command.CommandCancelException;
+import org.tizen.common.util.log.Logger;
+
+/**
+ * UncaughtExceptionHandlingPolicy.
+ *
+ * Exception handling policy
+ * Singleton class implemented using enum
+ *
+ * @author Ho Namkoong{@literal <ho.namkoong@samsung.com>} (S-Core)
+ */
+public enum UncaughtExceptionHandlingPolicy
+ implements
+ UncaughtExceptionHandler {
+
+ /**
+ * singleton instance.
+ */
+ INSTANCE();
+
+ /**
+ * map which stores handler (value) according to the throwable class name (name).
+ */
+ private final Map<String, UncaughtExceptionHandler> repository = new HashMap<String, UncaughtExceptionHandler>();
+
+ /**
+ * get handler from repository, and handle exception.
+ * If appropriate repository is not found,
+ * it searches for handler which handles superclass of target exception.
+ *
+ * @param t current thread
+ * @param e exception which should be handled
+ * @since 1.5
+ */
+ @Override
+ public void uncaughtException(Thread t, Throwable e) {
+
+ UncaughtExceptionHandler handler = null;
+ Class<? extends Object> throwableClass = e.getClass();
+
+ do {
+ handler = repository.get(throwableClass.getCanonicalName());
+ if(handler != null) {
+ handler.uncaughtException(t, e);
+ return;
+ }
+
+ throwableClass = throwableClass.getSuperclass();
+ } while (!throwableClass.getCanonicalName().equals(Object.class.getCanonicalName()));
+
+ throw new IllegalStateException(e);
+ }
+
+ private UncaughtExceptionHandlingPolicy() {
+ installUncaughtExceptionHandlers();
+ }
+
+ private void installUncaughtExceptionHandlers() {
+
+ //Install OperationCancelException Handler
+ this.putHandler(CommandCancelException.class.getCanonicalName(), new UncaughtExceptionHandler() {
+ @Override
+ public void uncaughtException(Thread t, Throwable e) {
+ if(e instanceof CommandCancelException) {
+ throw (CommandCancelException)e;
+ }
+ else {
+ throw new IllegalStateException();
+ }
+ }
+ });
+ }
+
+ private void putHandler(String throwableName, UncaughtExceptionHandler handler) {
+ if(repository.containsKey(throwableName)) {
+ if(!repository.get(throwableName).equals(handler)) {
+ Logger.error("Handlers are duplicate assigned with one key: " + throwableName);
+ }
+ return;
+ }
+ repository.put(throwableName, handler);
+ }
+}
diff --git a/org.tizen.common/src/org/tizen/common/core/command/prompter/AbstractOption.java b/org.tizen.common/src/org/tizen/common/core/command/prompter/AbstractOption.java
new file mode 100644
index 000000000..d60b177d7
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/core/command/prompter/AbstractOption.java
@@ -0,0 +1,181 @@
+/*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common.core.command.prompter;
+
+import static org.tizen.common.util.StringUtil.isEmpty;
+import static org.tizen.common.util.StringUtil.trim;
+
+import org.tizen.common.util.ObjectUtil;
+
+/**
+ * <p>
+ * AbstractOption.
+ *
+ * Abstract(common) class for option
+ * </p>
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ */
+public class
+AbstractOption
+implements Option
+{
+ /**
+ * <p>
+ * Option name
+ *
+ * It is printed out
+ * </p>
+ */
+ protected final String name;
+
+ /**
+ * Flag if user input is handled as abbreviation
+ */
+ protected final boolean bPermitAbbreviation;
+
+ /**
+ * Flag if this option is default( choice when user doesn't select option )
+ */
+ protected final boolean bDefault;
+
+ /**
+ * Constructor with choice name, default flag and abbreviation flag
+ *
+ * @param name choice name
+ * @param bDefault default flag
+ * @param bPermitAbbreviation abbreviation flag
+ */
+ public
+ AbstractOption(
+ final String name,
+ final boolean bDefault,
+ final boolean bPermitAbbreviation
+ )
+ {
+ this.name = trim( name );
+
+ this.bDefault = bDefault;
+
+ this.bPermitAbbreviation = bPermitAbbreviation;
+ }
+
+ /**
+ * Return option name
+ *
+ * @return option name
+ */
+ public String getName()
+ {
+ return this.name;
+ }
+
+ /**
+ * Return whether this choice is default {@link ChoiceOption}
+ *
+ * @return boolean value if this choice is default
+ */
+ public boolean isDefault()
+ {
+ return this.bDefault;
+ }
+
+ /**
+ * Return whether user input, <code>value</code> is match option
+ *
+ * @param value user input
+ *
+ * @return boolean value If matching
+ */
+ public
+ boolean
+ isMatch(
+ final String value
+ )
+ {
+ if ( name.equalsIgnoreCase( trim( value ) ) )
+ {
+ return true;
+ }
+
+ if ( isEmpty( value ) )
+ {
+ return false;
+ }
+ if ( bPermitAbbreviation )
+ {
+ return name.substring( 0, 1 ).equalsIgnoreCase( value.substring( 0, 1 ) );
+ }
+
+ return false;
+
+ }
+
+ /* (non-Javadoc)
+ * @see java.lang.Object#hashCode()
+ */
+ @Override
+ public
+ int
+ hashCode()
+ {
+ return name.hashCode();
+ }
+
+ /* (non-Javadoc)
+ * @see java.lang.Object#equals(java.lang.Object)
+ */
+ @Override
+ public
+ boolean
+ equals(
+ final Object obj
+ )
+ {
+ if ( !( obj instanceof ChoiceOption ) )
+ {
+ return false;
+ }
+ final ChoiceOption other = (ChoiceOption) obj;
+ return ObjectUtil.equals( this.name, other.name );
+ }
+
+ /* (non-Javadoc)
+ * @see java.lang.Object#toString()
+ */
+ @Override
+ public
+ String
+ toString()
+ {
+ if ( isDefault() )
+ {
+ return "[" + name + "]";
+ }
+ return name;
+ }
+
+
+}
diff --git a/org.tizen.common/src/org/tizen/common/core/command/prompter/AbstractPrompter.java b/org.tizen.common/src/org/tizen/common/core/command/prompter/AbstractPrompter.java
new file mode 100644
index 000000000..701a9772c
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/core/command/prompter/AbstractPrompter.java
@@ -0,0 +1,86 @@
+/*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common.core.command.prompter;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.LinkedHashSet;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.tizen.common.core.command.Prompter;
+
+/**
+ * AbstractPrompter.
+ *
+ * Abstract class for sub class for {@link Prompter}
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ */
+public class
+AbstractPrompter
+{
+
+ /**
+ * Logger for this instance
+ */
+ protected final Logger logger = LoggerFactory.getLogger( getClass() );
+
+ protected
+ void
+ checkOptions( ChoiceOption[] options )
+ {
+ if ( null == options )
+ {
+ throw new NullPointerException();
+ }
+
+ final HashSet<Option> reducedOptions = new LinkedHashSet<Option>();
+ Option defaultOption = null;
+ final ArrayList<String> optionNames = new ArrayList<String>();
+ for ( final Option option : options )
+ {
+ if ( reducedOptions.contains( option ) )
+ {
+ throw new IllegalArgumentException(
+ "Question can't have duplicated choice(s) :" + option
+ );
+ }
+ optionNames.add( option.getName() );
+ reducedOptions.add( option );
+ if ( option.isDefault() )
+ {
+ if ( null != defaultOption )
+ {
+ throw new IllegalArgumentException(
+ "Question must have only one default choice"
+ );
+ }
+
+ defaultOption = option;
+ }
+ }
+ }
+}
diff --git a/org.tizen.common/src/org/tizen/common/core/command/prompter/ChoiceOption.java b/org.tizen.common/src/org/tizen/common/core/command/prompter/ChoiceOption.java
new file mode 100644
index 000000000..267941b5f
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/core/command/prompter/ChoiceOption.java
@@ -0,0 +1,95 @@
+/*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common.core.command.prompter;
+
+import static org.tizen.common.util.StringUtil.hasText;
+
+import org.tizen.common.util.Assert;
+
+/**
+ * <p>
+ * Option.
+ *
+ * Option to choice
+ * </p>
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ */
+public class
+ChoiceOption
+extends AbstractOption
+{
+ /**
+ * Constructor with choice name
+ *
+ * @param name choice name
+ *
+ * #see {@link #Option(String, boolean)}
+ */
+ public
+ ChoiceOption(
+ final String name
+ )
+ {
+ this( name, false );
+ }
+
+ /**
+ * Constructor with choice name and default flag
+ *
+ * @param name choice name
+ * @param bDefault default flag
+ *
+ * @see #Option(String, boolean, boolean)
+ */
+ public
+ ChoiceOption(
+ final String name,
+ final boolean bDefault
+ )
+ {
+ this( name, bDefault, true );
+ }
+
+ /**
+ * Constructor with choice name, default flag and abbreviation flag
+ *
+ * @param name choice name
+ * @param bDefault default flag
+ * @param bPermitAbbreviation abbreviation flag
+ */
+ public
+ ChoiceOption(
+ final String name,
+ final boolean bDefault,
+ final boolean bPermitAbbreviation
+ )
+ {
+ super( name, bDefault, bPermitAbbreviation );
+ Assert.isTrue( hasText( name ) );
+ }
+
+
+}
diff --git a/org.tizen.common/src/org/tizen/common/core/command/prompter/EclipsePrompter.java b/org.tizen.common/src/org/tizen/common/core/command/prompter/EclipsePrompter.java
new file mode 100644
index 000000000..cb4f3e6d3
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/core/command/prompter/EclipsePrompter.java
@@ -0,0 +1,201 @@
+/*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common.core.command.prompter;
+
+import java.util.HashMap;
+
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IConfigurationElement;
+import org.eclipse.core.runtime.IExtension;
+import org.eclipse.core.runtime.IExtensionPoint;
+import org.eclipse.core.runtime.IExtensionRegistry;
+import org.eclipse.core.runtime.Platform;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.tizen.common.core.command.Prompter;
+import org.tizen.common.util.ObjectUtil;
+import org.tizen.common.util.StringUtil;
+
+/**
+ * <p>
+ * EclipsePrompter.
+ *
+ * Context aware prompter using extension
+ * </p>
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ */
+public class
+EclipsePrompter
+implements Prompter
+{
+ protected static final String EP_ID = "org.tizen.common.prompter";
+
+ protected static final String ATTR_SCOPE = "scope";
+
+ protected static final String ATTR_CLASS = "class";
+
+ protected final Logger logger = LoggerFactory.getLogger( getClass() );
+
+ /**
+ * Default prompter
+ */
+ protected final Prompter defaultPrompter;
+
+ protected final HashMap<String, Prompter> name2prompter;
+
+ /**
+ * Constructor with default prompter
+ *
+ * @param defaultPrompter {@link Prompter}
+ */
+ public EclipsePrompter(
+ final Prompter defaultPrompter
+ )
+ {
+ this.defaultPrompter = defaultPrompter;
+ this.name2prompter = new HashMap<String, Prompter>();
+ }
+
+ protected Prompter
+ getPrompter()
+ {
+ final StackTraceElement[] stacks = Thread.currentThread().getStackTrace();
+
+ final IExtensionRegistry registry = Platform.getExtensionRegistry();
+ final IExtensionPoint ep = registry.getExtensionPoint( EP_ID );
+ final IExtension[] exts = ep.getExtensions();
+
+ for ( final StackTraceElement stack : stacks )
+ {
+ final String className = stack.getClassName();
+
+ for ( final IExtension ext : exts )
+ {
+ final IConfigurationElement[] configs = ext.getConfigurationElements();
+ for ( IConfigurationElement config : configs )
+ {
+ final String scope = config.getAttribute( ATTR_SCOPE );
+ if ( StringUtil.isEmpty( scope ) )
+ {
+ continue;
+ }
+
+ if ( !ObjectUtil.equals( className, scope ) )
+ {
+ continue;
+ }
+
+ try {
+ return (Prompter) config.createExecutableExtension( ATTR_CLASS );
+ } catch ( CoreException e )
+ {
+ logger.error( "Can't create prompter :" + config.getAttribute( ATTR_CLASS ) );
+ return defaultPrompter;
+ }
+ }
+ }
+ }
+
+ return defaultPrompter;
+ }
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.core.command.Prompter#interact(java.lang.String, org.tizen.common.core.command.prompter.Option[])
+ */
+ @Override
+ public Option interact(
+ final String question,
+ final Option... options
+ )
+ {
+ final Prompter prompter = getPrompter();
+ return prompter.interact(question, options);
+ }
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.core.command.Prompter#password(java.lang.String)
+ */
+ @Override
+ public
+ char[] password(
+ final String message
+ )
+ {
+ final Prompter prompter = getPrompter();
+ return prompter.password(message);
+ }
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.core.command.Prompter#error(java.lang.String)
+ */
+ @Override
+ public
+ void
+ error(
+ final String message
+ )
+ {
+ final Prompter prompter = getPrompter();
+ prompter.error(message);
+ }
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.core.command.Prompter#notify(java.lang.String)
+ */
+ @Override
+ public
+ void
+ notify(
+ final String message
+ )
+ {
+ final Prompter prompter = getPrompter();
+ prompter.notify(message);
+ }
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.core.command.Prompter#cancel()
+ */
+ @Override
+ public
+ void
+ cancel()
+ {
+ final Prompter prompter = getPrompter();
+ prompter.cancel();
+ }
+
+
+ /* (non-Javadoc)
+ * @see java.lang.Object#toString()
+ */
+ @Override
+ public String toString()
+ {
+ return getClass().getSimpleName() + "@" + Integer.toHexString( hashCode() ).substring( 0, 4 );
+ }
+
+}
diff --git a/org.tizen.common/src/org/tizen/common/core/command/prompter/GenericOption.java b/org.tizen.common/src/org/tizen/common/core/command/prompter/GenericOption.java
new file mode 100644
index 000000000..003b35bd8
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/core/command/prompter/GenericOption.java
@@ -0,0 +1,149 @@
+/*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common.core.command.prompter;
+
+import static org.tizen.common.util.StringUtil.hasText;
+
+import org.tizen.common.util.Assert;
+
+/**
+ * <p>
+ * GenericOption.
+ *
+ * {@link ChoiceOption} for general input
+ * </p>
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ */
+public class
+GenericOption
+extends AbstractOption
+{
+
+ /**
+ * User input
+ */
+ protected String answer;
+
+ /**
+ * Default constructor
+ */
+ public
+ GenericOption()
+ {
+ super( "", false, false );
+ }
+
+ /**
+ * Constructor with choice name
+ *
+ * @param name choice name
+ *
+ * #see {@link #Option(String, boolean)}
+ */
+ public
+ GenericOption(final String name)
+ {
+ super( name, false, false );
+ this.answer = name;
+ }
+
+ /**
+ * Constructor with choice name and default flag
+ *
+ * @param name choice name
+ * @param bDefault default flag
+ *
+ * @see #Option(String, boolean, boolean)
+ */
+ public
+ GenericOption (
+ final String name,
+ final boolean bDefault
+ )
+ {
+ super( name, bDefault, false );
+ this.answer = name;
+ }
+
+ /**
+ * Constructor with choice name, default flag and abbreviation flag
+ *
+ * @param name choice name
+ * @param bDefault default flag
+ * @param bPermitAbbreviation abbreviation flag
+ */
+ public
+ GenericOption (
+ final String name,
+ final boolean bDefault,
+ final boolean bPermitAbbreviation
+ )
+ {
+ super( name, bDefault, bPermitAbbreviation );
+ Assert.isTrue( hasText( name ) );
+ this.answer = name;
+ }
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.core.command.prompter.AbstractOption#isMatch(java.lang.String)
+ */
+ @Override
+ public
+ boolean
+ isMatch(
+ final String value
+ )
+ {
+ this.answer = value;
+ return true;
+ }
+
+ /**
+ * Return user input
+ *
+ * @return user input
+ */
+ public String
+ getAnswer()
+ {
+ return this.answer;
+ }
+
+ /* (non-Javadoc)
+ * @see java.lang.Object#toString()
+ */
+ @Override
+ public
+ String
+ toString()
+ {
+ if ( isDefault() )
+ {
+ return "[" + this.answer + "]";
+ }
+ return this.answer;
+ }
+}
diff --git a/org.tizen.common/src/org/tizen/common/core/command/prompter/NopPrompter.java b/org.tizen.common/src/org/tizen/common/core/command/prompter/NopPrompter.java
new file mode 100644
index 000000000..c202a35b6
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/core/command/prompter/NopPrompter.java
@@ -0,0 +1,129 @@
+/*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common.core.command.prompter;
+
+import org.tizen.common.core.command.Prompter;
+
+/**
+ * <p>
+ * NopPrompter.
+ *
+ * No-Operation Prompter doesn't interact with human
+ *
+ * It is used for batch process or test
+ *
+ * </p>
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ */
+public class
+NopPrompter
+extends AbstractPrompter
+implements Prompter
+{
+
+ protected char[] password;
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.core.command.Prompter#interact(java.lang.String, int, org.tizen.common.core.command.prompter.Option[])
+ */
+ public
+ Option
+ interact(
+ final String question,
+ final Option... options
+ )
+ {
+ for ( Option option : options )
+ {
+ if ( option.isDefault() )
+ {
+ return option;
+ }
+ }
+ throw new IllegalArgumentException();
+ }
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.core.command.Prompter#notify(java.lang.String, java.lang.Object[])
+ */
+ @Override
+ public
+ void
+ notify(
+ final String message
+ )
+ {
+ logger.info( "Notification >>> {}", message );
+ }
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.core.command.Prompter#cancel()
+ */
+ @Override
+ public void cancel()
+ {
+ }
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.core.command.Prompter#password(java.lang.String)
+ */
+ @Override
+ public
+ char[] password(
+ final String message
+ )
+ {
+ return password;
+ }
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.core.command.Prompter#error(java.lang.String, java.lang.Object[])
+ */
+ @Override
+ public
+ void
+ error(
+ final String message
+ )
+ {
+ logger.error( "Error >>> {}", message );
+ }
+
+ /**
+ * Set password
+ *
+ * @param password password to be provided automatically
+ */
+ public
+ void
+ setPassword(
+ final char[] password
+ )
+ {
+ this.password = password;
+ }
+
+}
diff --git a/org.tizen.common/src/org/tizen/common/core/command/prompter/Option.java b/org.tizen.common/src/org/tizen/common/core/command/prompter/Option.java
new file mode 100644
index 000000000..c2c624ce4
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/core/command/prompter/Option.java
@@ -0,0 +1,11 @@
+package org.tizen.common.core.command.prompter;
+
+public interface Option
+{
+ String getName();
+
+ boolean isDefault();
+
+ boolean isMatch( final String value );
+
+}
diff --git a/org.tizen.common/src/org/tizen/common/core/command/prompter/RunableOption.java b/org.tizen.common/src/org/tizen/common/core/command/prompter/RunableOption.java
new file mode 100644
index 000000000..dc78fe7de
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/core/command/prompter/RunableOption.java
@@ -0,0 +1,124 @@
+/*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * Ho Namkoong <ho.namkoong@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+
+package org.tizen.common.core.command.prompter;
+
+public abstract class RunableOption implements Option{
+
+ /**
+ * Arguments which will be used in run.
+ */
+ private Object[] args;
+
+ /**
+ * if true, remaning selection is following this option
+ * For example, if you select ignore all or overwrite all when deuplicate files are found, then this flag becomes true.
+ */
+ private boolean allFlag = false;
+
+ /**
+ * name of this option
+ */
+ private String name;
+
+ /**
+ * Constructor with name
+ *
+ * @param name name of this operation
+ */
+ public RunableOption(String name) {
+ this.name = name;
+ this.args = null;
+ }
+
+ /**
+ * Constructor with name and arguments
+ *
+ * @param name name of this operation
+ * @param args arguments of this operation
+ */
+ public RunableOption(String name, Object... args) {
+ this.name = name;
+ this.args = args;
+ }
+
+ /**
+ * Set arguments
+ *
+ * @param args arguments of this operation
+ */
+ public void setArgument(Object... args) {
+ this.args = args;
+ }
+
+ /**
+ * Set all flag
+ *
+ * @param allFlag all flag of this operation
+ */
+ protected void setAllFlag(boolean allFlag) {
+ this.allFlag = allFlag;
+ }
+
+ /**
+ * return all flag
+ *
+ * @return return true if all flag is true, else return false
+ */
+ public boolean isAllFlag() {
+ return allFlag;
+ }
+
+ /**
+ * return name
+ *
+ * @return return name of this operation
+ */
+ @Override
+ public String getName() {
+ return name;
+ }
+
+ /**
+ * Check if name of this operation and value are matched.
+ *
+ * @arg value value which is compared with name of this operation
+ * @return return true if matched, else return false.
+ */
+ @Override
+ public boolean isMatch(String value) {
+ if(this.getName().equals(value)) {
+ return true;
+ }
+ return false;
+ }
+
+ protected abstract void runWithArgument(Object... args) throws Exception;
+
+ public void run() throws Exception {
+ this.runWithArgument(args);
+ }
+
+}
diff --git a/org.tizen.common/src/org/tizen/common/core/command/prompter/SWTPrompter.java b/org.tizen.common/src/org/tizen/common/core/command/prompter/SWTPrompter.java
new file mode 100755
index 000000000..ca29bffc6
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/core/command/prompter/SWTPrompter.java
@@ -0,0 +1,233 @@
+/*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common.core.command.prompter;
+
+import static org.tizen.common.util.SWTUtil.asyncExec;
+import static org.tizen.common.util.SWTUtil.exec;
+import static org.tizen.common.util.SWTUtil.getActiveShell;
+import static org.tizen.common.util.SWTUtil.syncExec;
+import static org.tizen.common.util.StringUtil.trim;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.LinkedHashSet;
+
+import org.eclipse.jface.dialogs.Dialog;
+import org.eclipse.jface.dialogs.IDialogConstants;
+import org.eclipse.jface.dialogs.MessageDialog;
+import org.tizen.common.core.command.Prompter;
+import org.tizen.common.ui.dialog.PasswordInputDialog;
+import org.tizen.common.util.NotificationType;
+import org.tizen.common.util.NotifierDialog;
+import org.tizen.common.util.SWTRunner;
+
+/**
+ * <p>
+ * SWTPrompter.
+ *
+ * {@link Prompter} in SWT environment
+ * </p>
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ */
+public class
+SWTPrompter
+extends AbstractPrompter
+implements Prompter
+{
+
+ /**
+ * Create dialog for user interaction
+ *
+ * @param question message for dialog
+ * @param optionNames option names for dialog
+ * @param defaultOptionIndex initial selection for option
+ *
+ * @return {@link Dialog} for user selection
+ */
+ protected
+ Dialog
+ createDialog(
+ final String question,
+ final String[] optionNames,
+ final int defaultOptionIndex
+ )
+ {
+ return new MessageDialog(
+ getActiveShell(),
+ "Question",
+ null,
+ question,
+ MessageDialog.QUESTION,
+ optionNames,
+ defaultOptionIndex
+ )
+ {
+ protected void buttonPressed( int buttonId )
+ {
+ setReturnCode( buttonId );
+ close();
+ }
+ };
+ }
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.core.command.Prompter#interact(java.lang.String, org.tizen.common.core.command.prompter.Option[])
+ */
+ @Override
+ public
+ Option
+ interact(
+ final String question,
+ final Option... options
+ )
+ {
+ final HashSet<Option> reducedOptions = new LinkedHashSet<Option>();
+ Option defaultOption = null;
+ final ArrayList<String> optionNames = new ArrayList<String>();
+ for ( final Option option : options )
+ {
+ if ( reducedOptions.contains( option ) )
+ {
+ throw new IllegalArgumentException(
+ "Question can't have duplicated choice(s) :" + option
+ );
+ }
+ optionNames.add( option.getName() );
+ reducedOptions.add( option );
+ if ( option.isDefault() )
+ {
+ if ( null != defaultOption )
+ {
+ throw new IllegalArgumentException(
+ "Question must have only one default choice"
+ );
+ }
+
+ defaultOption = option;
+ }
+ }
+ final int defaultIndex = optionNames.indexOf( defaultOption.getName() );
+
+ return exec( new SWTRunner<Option>()
+ {
+ /* (non-Javadoc)
+ * @see org.tizen.common.util.SWTRunner#process()
+ */
+ public Option process() {
+ final Dialog dialog = createDialog( question, optionNames.toArray( new String[0] ), defaultIndex );
+ dialog.open();
+ return options[dialog.getReturnCode()];
+ }
+ } );
+ }
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.core.command.Prompter#notify(java.lang.String, java.lang.Object[])
+ */
+ @Override
+ public void
+ notify(
+ final String message
+ )
+ {
+ asyncExec( new Runnable() {
+
+ /* (non-Javadoc)
+ * @see java.lang.Runnable#run()
+ */
+ @Override
+ public void run() {
+ NotifierDialog.notify( "Notify", message, NotificationType.INFO );
+ }
+ } );
+ }
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.core.command.Prompter#cancel()
+ */
+ @Override
+ public void cancel() {
+ }
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.core.command.Prompter#password(java.lang.String)
+ */
+ @Override
+ public
+ char[] password(
+ final String message
+ )
+ {
+ return exec( new SWTRunner<char[]>()
+ {
+ /* (non-Javadoc)
+ * @see java.lang.Runnable#run()
+ */
+ @Override
+ public char[] process()
+ {
+ final PasswordInputDialog dialog =
+ new PasswordInputDialog( "Password Input Dialog", message );
+
+ dialog.open();
+
+ if ( IDialogConstants.OK_ID != dialog.getReturnCode() )
+ {
+ return null;
+ }
+
+ return trim( dialog.getValue() ).toCharArray();
+ }
+ } );
+
+
+
+ }
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.core.command.Prompter#error(java.lang.String, java.lang.Object[])
+ */
+ @Override
+ public
+ void
+ error(
+ final String message
+ )
+ {
+ syncExec( new Runnable() {
+
+ /* (non-Javadoc)
+ * @see java.lang.Runnable#run()
+ */
+ @Override
+ public void run() {
+ MessageDialog.openError( getActiveShell(), "Error", message );
+ }
+ } );
+
+ }
+
+}
diff --git a/org.tizen.common/src/org/tizen/common/core/command/sdb/DevicesSdbCommand.java b/org.tizen.common/src/org/tizen/common/core/command/sdb/DevicesSdbCommand.java
new file mode 100644
index 000000000..e86d38d07
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/core/command/sdb/DevicesSdbCommand.java
@@ -0,0 +1,65 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* GyeongSeok Seo <gyeongseok.seo@samsung.com>
+* BonYong Lee <bonyong.lee@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+package org.tizen.common.core.command.sdb;
+
+import org.tizen.common.core.command.ExecutionContext;
+import org.tizen.common.core.command.Executor;
+import org.tizen.common.util.Assert;
+import org.tizen.sdblib.IDevice;
+
+public class DevicesSdbCommand
+extends SdbHandlingCommand
+{
+ protected SmartDevelopmentBridgeManager createBridge()
+ {
+ return new SmartDevelopmentBridgeManager();
+ }
+
+ @Override
+ public void run( final Executor executor, ExecutionContext context)
+ {
+ SmartDevelopmentBridgeManager bridge = createBridge();
+ Assert.notNull( bridge );
+
+ IDevice devices[] = bridge.getDevices();
+ String result = new String();
+ for ( IDevice device : devices )
+ {
+ result += device.toString() + System.getProperty("line.separator");
+ }
+ setResult( result );
+
+ context.getPrompter().notify( getResult() );
+ }
+
+ @Override
+ public void undo(final Executor executor, ExecutionContext context) throws Exception
+ {
+ // TODO Auto-generated method stub
+
+ }
+
+}
diff --git a/org.tizen.common/src/org/tizen/common/core/command/sdb/DlogSdbCommand.java b/org.tizen.common/src/org/tizen/common/core/command/sdb/DlogSdbCommand.java
new file mode 100644
index 000000000..f4bfb887d
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/core/command/sdb/DlogSdbCommand.java
@@ -0,0 +1,54 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* GyeongSeok Seo <gyeongseok.seo@samsung.com>
+* BonYong Lee <bonyong.lee@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+package org.tizen.common.core.command.sdb;
+
+import org.tizen.common.core.command.ExecutionContext;
+import org.tizen.common.core.command.Executor;
+
+public class DlogSdbCommand
+extends ShellSdbCommand
+{
+ protected String DLOG_COMMAND = "dlogutil";
+
+ public void setFilter(String filter) {
+ this.DLOG_COMMAND = "dlogutil "+filter;
+ }
+
+ @Override
+ public void run(Executor executor, ExecutionContext context)
+ throws Exception {
+ setCommand( this.DLOG_COMMAND );
+ super.run( executor, context );
+ }
+
+ @Override
+ public void undo(Executor executor, ExecutionContext context)
+ throws Exception {
+ // TODO Auto-generated method stub
+
+ }
+
+}
diff --git a/org.tizen.common/src/org/tizen/common/core/command/sdb/ForwardSdbCommand.java b/org.tizen.common/src/org/tizen/common/core/command/sdb/ForwardSdbCommand.java
new file mode 100644
index 000000000..11540d85b
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/core/command/sdb/ForwardSdbCommand.java
@@ -0,0 +1,70 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* GyeongSeok Seo <gyeongseok.seo@samsung.com>
+* BonYong Lee <bonyong.lee@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+package org.tizen.common.core.command.sdb;
+
+import org.tizen.common.core.command.ExecutionContext;
+import org.tizen.common.core.command.Executor;
+import org.tizen.common.util.Assert;
+import org.tizen.sdblib.IDevice;
+
+public class ForwardSdbCommand
+extends SdbDevicesHandlingCommand
+{
+ private int localPort;
+ private int remotePort;
+
+ public ForwardSdbCommand(int localPort, int remotePort) {
+ this.localPort = localPort;
+ this.remotePort = remotePort;
+ }
+
+ @Override
+ public void run(final Executor executor, ExecutionContext context) throws InterruptedException {
+ IDevice device = getDevice();
+ Assert.notNull( device );
+
+ try {
+ device.createForward( localPort, remotePort );
+ } catch (Exception e) {
+ // TODO Message fix need
+ context.getPrompter().notify( "forward socket connections error" );
+ }
+ }
+
+ @Override
+ public void undo(Executor executor, ExecutionContext context)
+ throws Exception {
+ IDevice device = getDevice();
+ Assert.notNull( device );
+
+ try {
+ device.removeForward( localPort, remotePort );
+ } catch (Exception e) {
+ // TODO Message fix need
+ context.getPrompter().notify( "remove forward socket connections error" );
+ }
+ }
+}
diff --git a/org.tizen.common/src/org/tizen/common/core/command/sdb/PullSdbCommand.java b/org.tizen.common/src/org/tizen/common/core/command/sdb/PullSdbCommand.java
new file mode 100644
index 000000000..925729877
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/core/command/sdb/PullSdbCommand.java
@@ -0,0 +1,87 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* GyeongSeok Seo <gyeongseok.seo@samsung.com>
+* BonYong Lee <bonyong.lee@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+package org.tizen.common.core.command.sdb;
+
+import java.io.IOException;
+
+import org.tizen.common.core.command.ExecutionContext;
+import org.tizen.common.core.command.Executor;
+import org.tizen.common.util.Assert;
+import org.tizen.sdblib.IDevice;
+import org.tizen.sdblib.SdbCommandRejectedException;
+import org.tizen.sdblib.SyncService;
+import org.tizen.sdblib.SyncService.ISyncProgressMonitor;
+import org.tizen.sdblib.SyncService.SyncResult;
+import org.tizen.sdblib.TimeoutException;
+
+public class PullSdbCommand
+extends SdbDevicesHandlingCommand
+{
+ protected String remotePath;
+ protected String localPath;
+
+ public PullSdbCommand(String remotePath, String localPath)
+ {
+ this.remotePath = remotePath;
+ this.localPath = localPath;
+ }
+
+ protected SyncService getSyncService() throws TimeoutException, SdbCommandRejectedException, IOException
+ {
+ return device.getSyncService();
+ }
+
+ protected ISyncProgressMonitor getProgressMonitor() {
+ return SyncService.getNullProgressMonitor();
+ }
+
+ @Override
+ public void run(final Executor executor, ExecutionContext context)
+ throws Exception
+ {
+ IDevice device = getDevice();
+ Assert.notNull( device );
+
+ try
+ {
+ SyncService service = getSyncService();
+ SyncResult syncSuccess =
+ service.pullFile( remotePath, localPath, getProgressMonitor() );
+ if ( syncSuccess.getCode() != SyncService.RESULT_OK ) {
+ // TODO Message fix need
+ context.getPrompter().notify( "transfer error" );
+ }
+ } catch (Exception e) {
+ throw new IllegalStateException( e );
+ }
+ }
+
+ @Override
+ public void undo(final Executor executor, ExecutionContext context) throws Exception {
+ // TODO Auto-generated method stub
+
+ }
+}
diff --git a/org.tizen.common/src/org/tizen/common/core/command/sdb/PushSdbCommand.java b/org.tizen.common/src/org/tizen/common/core/command/sdb/PushSdbCommand.java
new file mode 100644
index 000000000..46db4c404
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/core/command/sdb/PushSdbCommand.java
@@ -0,0 +1,93 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* GyeongSeok Seo <gyeongseok.seo@samsung.com>
+* BonYong Lee <bonyong.lee@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+package org.tizen.common.core.command.sdb;
+
+import java.io.IOException;
+
+import org.tizen.common.core.command.ExecutionContext;
+import org.tizen.common.core.command.Executor;
+import org.tizen.common.util.Assert;
+import org.tizen.common.util.FilenameUtil;
+import org.tizen.sdblib.IDevice;
+import org.tizen.sdblib.SdbCommandRejectedException;
+import org.tizen.sdblib.SyncService;
+import org.tizen.sdblib.SyncService.ISyncProgressMonitor;
+import org.tizen.sdblib.SyncService.SyncResult;
+import org.tizen.sdblib.TimeoutException;
+
+public class PushSdbCommand
+extends SdbDevicesHandlingCommand
+{
+ protected String localPath;
+ protected String remotePath;
+
+ public PushSdbCommand(String localPath, String remotePath)
+ {
+ this.localPath = localPath;
+ this.remotePath = remotePath;
+ }
+
+ protected SyncService getSyncService() throws TimeoutException, SdbCommandRejectedException, IOException
+ {
+ return device.getSyncService();
+ }
+
+ protected ISyncProgressMonitor getProgressMonitor() {
+ return SyncService.getNullProgressMonitor();
+ }
+
+ @Override
+ public void run(final Executor executor, ExecutionContext context)
+ throws Exception
+ {
+ IDevice device = getDevice();
+ Assert.notNull( device );
+
+ try
+ {
+ SyncService service = getSyncService();
+ SyncResult syncSuccess =
+ service.pushFile( localPath, remotePath, getProgressMonitor() );
+ String name = FilenameUtil.getFilename( localPath );
+ if ( syncSuccess.getCode() != SyncService.RESULT_OK ) {
+ setResult( "failed" );
+ context.getPrompter().notify( name + " file transfer failed" );
+ return ;
+ }
+ setResult( "success" );
+ context.getPrompter().notify( name + " file transfer success" );
+ } catch (Exception e) {
+ throw new IllegalStateException( e );
+ }
+ }
+
+ @Override
+ public void undo(final Executor executor, ExecutionContext context) throws Exception {
+ // TODO Auto-generated method stub
+
+ }
+
+}
diff --git a/org.tizen.common/src/org/tizen/common/model/DefaultTreeModel.java b/org.tizen.common/src/org/tizen/common/core/command/sdb/SdbDevicesHandlingCommand.java
index 687c3089a..95230fce0 100644
--- a/org.tizen.common/src/org/tizen/common/model/DefaultTreeModel.java
+++ b/org.tizen.common/src/org/tizen/common/core/command/sdb/SdbDevicesHandlingCommand.java
@@ -1,44 +1,45 @@
-/*
-* Common
-*
-* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
-*
-* Contact:
-* Kangho Kim <kh5325.kim@samsung.com>
-*
-* 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.
-*
-* Contributors:
-* - S-Core Co., Ltd
-*
-*/
-
-package org.tizen.common.model;
-
-
-
-public class DefaultTreeModel extends AbstractTreeModel {
-
- public DefaultTreeModel(ITreeVO source){
- super(source);
- }
-
- public String getSourceName() {
- String str = this.source.getClass().getSimpleName();
- if(str.endsWith("VO")) //$NON-NLS-1$
- str = str.substring(0,str.length()-2);
- return str;
- }
-}
-
-
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* GyeongSeok Seo <gyeongseok.seo@samsung.com>
+* BonYong Lee <bonyong.lee@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+package org.tizen.common.core.command.sdb;
+
+import org.tizen.sdblib.IDevice;
+
+public abstract class
+SdbDevicesHandlingCommand
+extends SdbHandlingCommand
+{
+ protected IDevice device;
+
+ public void setDevice(IDevice device)
+ {
+ this.device = device;
+ }
+
+ public IDevice getDevice()
+ {
+ return this.device;
+ }
+}
diff --git a/org.tizen.common/src/org/tizen/common/core/command/sdb/SdbHandlingCommand.java b/org.tizen.common/src/org/tizen/common/core/command/sdb/SdbHandlingCommand.java
new file mode 100644
index 000000000..6c98a729a
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/core/command/sdb/SdbHandlingCommand.java
@@ -0,0 +1,60 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* GyeongSeok Seo <gyeongseok.seo@samsung.com>
+* BonYong Lee <bonyong.lee@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+package org.tizen.common.core.command.sdb;
+
+import org.tizen.common.core.command.Command;
+
+public abstract class
+SdbHandlingCommand
+implements Command<String>
+{
+ protected StringBuffer result;
+
+ public void clearResult() {
+ if ( this.result == null ) {
+ this.result = new StringBuffer();
+ } else {
+ this.result.delete( 0, result.capacity() );
+ this.result.setLength( 0 );
+ }
+ }
+
+ public String getResult()
+ {
+ if ( this.result == null ) {
+ return null;
+ }
+ return this.result.toString();
+ }
+
+ public void setResult(String result)
+ {
+ if ( this.result == null ) {
+ this.result = new StringBuffer();
+ }
+ this.result.append( result );
+ }
+}
diff --git a/org.tizen.common/src/org/tizen/common/core/command/sdb/ShellSdbCommand.java b/org.tizen.common/src/org/tizen/common/core/command/sdb/ShellSdbCommand.java
new file mode 100644
index 000000000..5efc22f53
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/core/command/sdb/ShellSdbCommand.java
@@ -0,0 +1,142 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* GyeongSeok Seo <gyeongseok.seo@samsung.com>
+* BonYong Lee <bonyong.lee@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+package org.tizen.common.core.command.sdb;
+
+import org.tizen.common.core.command.ExecutionContext;
+import org.tizen.common.core.command.Executor;
+import org.tizen.common.util.Assert;
+import org.tizen.sdblib.IDevice;
+import org.tizen.sdblib.MultiLineReceiver;
+
+/**
+ * <p>
+ * ShellSdbCommand.
+ *
+ * Command to run shell in target
+ * </p>
+ *
+ * @author GyeongSeok Seo{@literal <gyeongseok.seo@samsung.com>} (S-Core)
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ */
+public class ShellSdbCommand
+extends SdbDevicesHandlingCommand
+{
+ private String command;
+ private static int DEFAULT_TIME = 90;
+
+ /**
+ * Wait for shell command completion
+ */
+ private int time;
+
+ /**
+ * Get wait for shell command completion time
+ *
+ * @return time value
+ */
+ public int getTime() {
+ return time;
+ }
+
+ /**
+ * Set wait for shell command completion time
+ *
+ * @param time value
+ */
+ public void setTime(int time) {
+ this.time = time <= 0 ? DEFAULT_TIME : time;
+ }
+
+ /**
+ * Constructor, default command is empty so if using this constructor then must call setCommand
+ */
+ public ShellSdbCommand() {
+ this.time = DEFAULT_TIME;
+ }
+
+ /**
+ * Constructor with command, command is running in target device.
+ *
+ * @param command
+ */
+ public ShellSdbCommand(String command) {
+ this.command = command;
+ this.time = DEFAULT_TIME;
+ }
+
+ /**
+ * Get command, command is running in target device
+ *
+ * @return command
+ */
+ public String getCommand() {
+ return command;
+ }
+
+ /**
+ * Set command, command is running in target device
+ *
+ * @param command
+ */
+ public void setCommand(String command) {
+ this.command = command;
+ }
+
+ /**
+ * Create MultiLineReceiver, MultiLineReceiver's processNewLines method save command running result
+ *
+ * @return MultiLineReceiver
+ */
+ public MultiLineReceiver createMultiLineReceiver() {
+ return new MultiLineReceiver() {
+ @Override
+ public void processNewLines(String[] lines) {
+ for( String content: lines ) {
+ setResult( content+System.getProperty( "line.separator" ) );
+ }
+ }
+ };
+ }
+
+ @Override
+ public void run(Executor executor, ExecutionContext context)
+ throws Exception {
+ IDevice device = getDevice();
+ Assert.notNull( device );
+ Assert.notNull( command );
+
+ clearResult();
+ device.executeShellCommand( command, createMultiLineReceiver(), getTime()*1000 );
+ }
+
+ @Override
+ public void undo(Executor executor, ExecutionContext context)
+ throws Exception {
+ // TODO Auto-generated method stub
+
+ }
+
+}
diff --git a/org.tizen.common/src/org/tizen/common/core/command/sdb/SmartDevelopmentBridgeManager.java b/org.tizen.common/src/org/tizen/common/core/command/sdb/SmartDevelopmentBridgeManager.java
new file mode 100644
index 000000000..66a5bb9f4
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/core/command/sdb/SmartDevelopmentBridgeManager.java
@@ -0,0 +1,93 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* GyeongSeok Seo <gyeongseok.seo@samsung.com>
+* BonYong Lee <bonyong.lee@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+package org.tizen.common.core.command.sdb;
+
+import org.tizen.sdblib.IDevice;
+import org.tizen.sdblib.SmartDevelopmentBridge;
+
+/**
+ * <p>
+ * SmartDevelopmentBridgeManager.
+ *
+ * class for delegate SmartDevelopmentBridge.
+ *
+ * </p>
+ *
+ * @author GyeongSeok Seo{@literal <gyeongseok.seo@samsung.com>} (S-Core)
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ */
+public class SmartDevelopmentBridgeManager
+{
+ private SmartDevelopmentBridge impl = SmartDevelopmentBridge.getBridge();
+
+ public boolean equals(Object obj) {
+ return impl.equals(obj);
+ }
+
+ public int getConnectionAttemptCount() {
+ return impl.getConnectionAttemptCount();
+ }
+
+ public IDevice[] getDevices() {
+ return impl.getDevices();
+ }
+
+ public int getRestartAttemptCount() {
+ return impl.getRestartAttemptCount();
+ }
+
+ public String getSdbOsLocation() {
+ return impl.getSdbOsLocation();
+ }
+
+ public boolean hasInitialDeviceList() {
+ return impl.hasInitialDeviceList();
+ }
+
+ public int hashCode() {
+ return impl.hashCode();
+ }
+
+ public boolean isConnected() {
+ return impl.isConnected();
+ }
+
+ public boolean restart() {
+ return impl.restart();
+ }
+
+ public String toString() {
+ return impl.toString();
+ }
+
+ public void disconnectBridge() {
+ impl.disconnectBridge();
+ }
+
+ public void terminate() {
+ impl.terminate();
+ }
+}
diff --git a/org.tizen.common/src/org/tizen/common/core/command/zip/ZipCommand.java b/org.tizen.common/src/org/tizen/common/core/command/zip/ZipCommand.java
new file mode 100644
index 000000000..639349f30
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/core/command/zip/ZipCommand.java
@@ -0,0 +1,196 @@
+/*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common.core.command.zip;
+
+import static org.tizen.common.core.command.Policy.EXIST_OUT_WGT;
+import static org.tizen.common.core.command.Policy.NONEXIST_IN_DIRECTORY;
+import static org.tizen.common.util.FilenameUtil.getRelativePath;
+import static org.tizen.common.util.IOUtil.tryClose;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.text.MessageFormat;
+import java.util.Collection;
+import java.util.LinkedList;
+import java.util.Queue;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipOutputStream;
+
+import org.tizen.common.core.command.ExecutionContext;
+import org.tizen.common.core.command.Executor;
+import org.tizen.common.core.command.Policy;
+import org.tizen.common.core.command.file.FileHandlingCommand;
+import org.tizen.common.core.command.policy.FilePolicy;
+import org.tizen.common.core.command.policy.MessagePolicy;
+import org.tizen.common.file.FileHandler;
+import org.tizen.common.file.FileHandler.Attribute;
+import org.tizen.common.file.FileHandler.Type;
+import org.tizen.common.util.Assert;
+import org.tizen.common.util.FilenameUtil;
+import org.tizen.common.util.IOUtil;
+
+/**
+ * <p>
+ * ZipCommand.
+ *
+ * Command to make zip archive
+ * </p>
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ */
+public class
+ZipCommand
+extends FileHandlingCommand<Object>
+{
+ /**
+ * Directory to zip
+ */
+ protected final String baseDir;
+
+ /**
+ * Constructor with base dir and target file name
+ *
+ * @param baseDir base directory path
+ * @param target target file name
+ */
+ public
+ ZipCommand(
+ final String baseDir,
+ final String target
+ )
+ {
+ this.baseDir = baseDir;
+ setPath( target );
+ }
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.core.command.file.FileHandlingCommand#execute(org.tizen.common.core.command.Executor, org.tizen.common.core.command.ExecutionContext)
+ */
+ @Override
+ public
+ void
+ run(
+ final Executor executor,
+ final ExecutionContext context
+ )
+ throws IOException, InterruptedException
+ {
+ final FileHandler handler = context.getFileHandler();
+ Assert.notNull( handler );
+
+ if ( !handler.is( baseDir, Attribute.EXISTS ) )
+ {
+ final Policy policy = context.getPolicy( NONEXIST_IN_DIRECTORY );
+
+ final MessagePolicy messagePolicy = policy.adapt( MessagePolicy.class );
+
+ messagePolicy.print( context.getPrompter(), "{0} doesn't exist", baseDir );
+ return ;
+ }
+
+ if ( handler.is( path, Attribute.EXISTS ) )
+ {
+ final Policy policy = context.getPolicy( EXIST_OUT_WGT );
+
+ final MessagePolicy messagePolicy = policy.adapt( MessagePolicy.class );
+ messagePolicy.print( context.getPrompter(), "Widget already exists" );
+
+ final FilePolicy filePolicy = policy.adapt( FilePolicy.class );
+
+ if ( FilePolicy.OVERWRITE.equals( filePolicy ) )
+ {
+ // No op
+ }
+ else
+ { // It is default to stop process
+ return ;
+ }
+
+ }
+
+ final ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
+ final ZipOutputStream zipOut = new ZipOutputStream( byteOut );
+
+ try
+ {
+ final Queue<String> directories = new LinkedList<String>();
+
+ directories.add( baseDir );
+
+ while ( !directories.isEmpty() )
+ {
+ final String filePath = directories.remove();
+ final Object type = handler.get( filePath, Attribute.TYPE );
+
+ logger.trace( "File path :{}", filePath );
+
+ if (
+ !FilenameUtil.equals( filePath, baseDir ) &&
+ !filter.accept( baseDir, FilenameUtil.getRelativePath( baseDir, filePath ) )
+ )
+ {
+ logger.debug( "Ignore {}", filePath );
+ continue;
+ }
+ logger.trace( "file [{}]'s type :{}", filePath, type );
+ if ( Type.DIRECTORY.equals( type ) )
+ {
+ final Collection<String> childs = handler.list( filePath );
+ directories.addAll( childs );
+ }
+ else if ( Type.FILE.equals( type ) )
+ {
+ final String relative = getRelativePath( baseDir, filePath );
+ final ZipEntry entry = new ZipEntry( relative );
+ zipOut.putNextEntry( entry );
+ IOUtil.redirect( handler.read( filePath ), zipOut );
+ logger.debug( "Zip {}", relative );
+ }
+ }
+ try {
+ handler.write( path, new ByteArrayInputStream( byteOut.toByteArray() ) );
+ context.getPrompter().notify( MessageFormat.format( "Widget[{0}] is created successfully ", path ) );
+ }
+ catch ( IOException e )
+ {
+ throw new IllegalStateException( e );
+ // TODO Handle
+ }
+ }
+ catch( IOException e )
+ {
+
+ // TODO Handle
+ }
+ finally
+ {
+ tryClose( zipOut );
+ }
+
+
+ }
+
+}
diff --git a/org.tizen.common/src/org/tizen/common/file/AbstractFileHandler.java b/org.tizen.common/src/org/tizen/common/file/AbstractFileHandler.java
new file mode 100644
index 000000000..c25d7cfb2
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/file/AbstractFileHandler.java
@@ -0,0 +1,66 @@
+/*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common.file;
+
+import java.io.IOException;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * <p>
+ * AbstractFileHandler.
+ *
+ * Abstract class for {@link FileHandler}
+ * </p>
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ */
+abstract public class
+AbstractFileHandler
+implements FileHandler
+{
+ protected final Logger logger = LoggerFactory.getLogger( getClass() );
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.file.FileHandler#is(java.lang.String, org.tizen.common.file.FileHandler.Attribute)
+ */
+ @Override
+ public boolean is(
+ final String path,
+ final Attribute name
+ )
+ throws IOException
+ {
+ final Object obj = get( path, name );
+ if ( obj instanceof Boolean )
+ {
+ return (Boolean) obj;
+ }
+ return false;
+ }
+
+
+}
diff --git a/org.tizen.common/src/org/tizen/common/file/EclipseFileHandler.java b/org.tizen.common/src/org/tizen/common/file/EclipseFileHandler.java
new file mode 100644
index 000000000..5e98ad426
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/file/EclipseFileHandler.java
@@ -0,0 +1,448 @@
+/*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common.file;
+
+import static org.tizen.common.util.CollectionUtil.concatenate;
+import static org.tizen.common.util.CollectionUtil.removeLast;
+import static org.tizen.common.util.FilenameUtil.getCanonicalForm;
+import static org.tizen.common.util.FilenameUtil.getRelativePath;
+import static org.tizen.common.util.FilenameUtil.isAncestor;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.LinkedList;
+import java.util.Queue;
+
+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.resources.IWorkspaceRoot;
+import org.eclipse.core.resources.ResourcesPlugin;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.NullProgressMonitor;
+import org.eclipse.core.runtime.Path;
+import org.tizen.common.util.FilenameUtil;
+import org.tizen.common.util.ObjectUtil;
+
+/**
+ * <p>
+ * EclipseFileHandler.
+ *
+ * {@link FileHandler} for eclipse plugin
+ * </p>
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ */
+public class
+EclipseFileHandler
+extends StandardFileHandler
+{
+
+ /**
+ * @return
+ */
+ protected
+ IWorkspaceRoot
+ getWorkspace()
+ {
+ return ResourcesPlugin.getWorkspace().getRoot();
+ }
+
+ protected IResource getFile( final String path ) throws IOException
+ {
+ final String root = getWorkspace().getLocation().toPortableString();
+ logger.trace( "Path :{}, Root :{}", path, root );
+
+ final File fileChecker = new File( path );
+ String relativePath = path;
+ if ( isAncestor( root, path ) )
+ {
+ relativePath = getRelativePath( root, path );
+ }
+ else if ( fileChecker.isAbsolute() )
+ {
+ return null;
+ }
+
+ final Queue<String> fragments =
+ new LinkedList<String>( Arrays.asList( FilenameUtil.getCanonicalFragments( relativePath ) ) );
+
+ final String projectName = fragments.remove();
+ if ( ".metadata".equals( projectName ) )
+ {
+ return null;
+ }
+ final IProject project = getWorkspace().getProject( projectName );
+ if ( fragments.isEmpty() )
+ {
+ return project;
+ }
+
+ final String fileName = removeLast( fragments );
+
+ IContainer parent = project;
+ if ( !fragments.isEmpty() )
+ {
+ parent = project.getFolder( concatenate( fragments, "/" ) );
+ }
+
+ try {
+ final IResource[] children = parent.members();
+ for ( final IResource chlid : children )
+ {
+ if ( ObjectUtil.equals( fileName, chlid.getName() ) )
+ {
+ return chlid;
+ }
+ }
+ fragments.add( fileName );
+ final String relativeFile = concatenate( fragments, "/" );
+ return project.getFile( relativeFile );
+ } catch (
+ CoreException e
+ )
+ {
+ logger.warn( "Exception :{}", e );
+ }
+ return null;
+ }
+
+ protected IContainer getFolder( final String path )
+ {
+ final String root = getWorkspace().getLocation().toPortableString();
+ logger.trace( "Path :{}, Root :{}", path, root );
+ final File fileChecker = new File( path );
+ String relativePath = path;
+ if ( isAncestor( root, path ) )
+ {
+ relativePath = getRelativePath( root, path );
+ }
+ else if ( fileChecker.isAbsolute() )
+ {
+ return null;
+ }
+
+ final Queue<String> fragments =
+ new LinkedList<String>( Arrays.asList( FilenameUtil.getCanonicalFragments( relativePath ) ) );
+
+ final String projectName = fragments.remove();
+ if ( ".metadata".equals( projectName ) )
+ {
+ return null;
+ }
+ final IProject project = getWorkspace().getProject( projectName );
+ if ( fragments.isEmpty() )
+ {
+ return project;
+ }
+
+ final String fileName = removeLast( fragments );
+
+ IContainer parent = project;
+ if ( !fragments.isEmpty() )
+ {
+ parent = project.getFolder( concatenate( fragments, "/" ) );
+ }
+
+ try {
+ final IResource[] children = parent.members();
+ for ( final IResource chlid : children )
+ {
+ if ( ObjectUtil.equals( fileName, chlid.getName() ) )
+ {
+ return (IContainer) chlid;
+ }
+ }
+ fragments.add( fileName );
+ final String relativeFile = concatenate( fragments, "/" );
+ return project.getFolder( relativeFile );
+ } catch (
+ CoreException e
+ )
+ {
+ }
+ return null;
+
+ }
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.file.FileHandler#getCurrentWorkingDirectory()
+ */
+ @Override
+ public
+ String
+ getCurrentWorkingDirectory()
+ {
+ return getWorkspace().getLocation().toPortableString();
+ }
+
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.file.FileHandler#setCurrentWorkingDirectory(java.lang.String)
+ */
+ @Override
+ public
+ void
+ setCurrentWorkingDirectory(
+ final String cwd
+ )
+ {
+ throw new UnsupportedOperationException();
+
+ }
+
+ @Override
+ public
+ void
+ makeDirectory(
+ final String path
+ )
+ throws IOException
+ {
+ final File file = new File( path );
+ if ( file.isAbsolute() )
+ {
+ super.makeDirectory( path );
+ final Path p = new Path( path );
+ try {
+ getWorkspace().getFileForLocation( p ).refreshLocal( -1, new NullProgressMonitor() );
+ } catch ( final CoreException e )
+ {
+ throw new IOException( e );
+ }
+ }
+
+ }
+
+ @Override
+ public
+ void
+ moveDirectory(
+ final String source,
+ final String target
+ )
+ throws IOException
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void copyDirectory(String source, String target) throws IOException {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void removeDirectory(String path) throws IOException {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public
+ Collection<String>
+ list(
+ final String path
+ )
+ throws IOException
+ {
+
+ final IContainer folder = getFolder( path );
+ if ( null == folder )
+ {
+ return super.list( path );
+ }
+ try {
+ final IResource[] children = folder.members();
+ final ArrayList<String> ret = new ArrayList<String>();
+
+ for ( final IResource child : children )
+ {
+
+ String childPath = getCanonicalForm( child.getLocation().toPortableString() );
+
+ if ( child instanceof IContainer )
+ {
+ childPath = childPath + "/";
+ }
+
+ if ( childPath.startsWith( "/" ) )
+ {
+ ret.add( childPath.substring( 1 ) );
+ }
+ else
+ {
+ ret.add( childPath );
+ }
+ }
+
+ logger.trace( "Children :{}", ret );
+ return ret;
+ }
+ catch (
+ final CoreException e
+ )
+ {
+ throw new IOException( e );
+ }
+ }
+
+ @Override
+ public void write(String path, InputStream out) throws IOException {
+ logger.trace( "Path :{}", path );
+ final IResource file = getFile( path );
+ final IFile f = (IFile) file.getAdapter( IFile.class );
+
+ try {
+ if ( f.exists() )
+ {
+ f.setContents( out, false, false, new NullProgressMonitor() );
+ }
+ else
+ {
+ f.create( out, false, new NullProgressMonitor() );
+ }
+ }
+ catch ( final CoreException e )
+ {
+ throw new IOException( e );
+ }
+ }
+
+ @Override
+ public InputStream read(
+ final String path
+ )
+ throws IOException
+ {
+ final Path p = new Path( path );
+ final IFile eFile = getWorkspace().getFileForLocation( p );
+ if ( null == eFile )
+ {
+ return super.read( path );
+ }
+ try
+ {
+ return eFile.getContents();
+ }
+ catch ( final CoreException e )
+ {
+ throw new IOException( e );
+ }
+ }
+
+ @Override
+ public void moveFile(String source, String target) throws IOException {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void copyFile(String source, String target) throws IOException {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void removeFile(String path) throws IOException {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public Object get(String path, Attribute name) throws IOException {
+ logger.trace( "Path :{}, Attribute :{}", path, name );
+
+ final IResource file = getFile( path );
+ if ( null == file )
+ {
+ return super.get( path, name );
+ }
+
+ if ( Attribute.TYPE.equals( name ) )
+ {
+ if ( file instanceof IContainer )
+ {
+ return Type.DIRECTORY;
+ }
+ else if ( file instanceof IFile )
+ {
+ return Type.FILE;
+ }
+ }
+ else if ( Attribute.EXISTS.equals( name ) )
+ {
+ return file.exists();
+
+ }
+ else if ( Attribute.PATH.equals( name ) )
+ {
+ return file.getLocation().toPortableString();
+ }
+ else if ( Attribute.URI.equals( name ) || Attribute.URL.equals( name ) )
+ {
+ return file.getLocationURI().toURL().toString();
+ }
+ else if ( Attribute.MODIFIED.equals( name ) )
+ {
+ return file.getLocalTimeStamp();
+ }
+ else if ( Attribute.HIDDEN.equals( name ) )
+ {
+ return file.isHidden();
+ }
+ else if ( Attribute.READABLE.equals( name ) )
+ {
+ return file.isAccessible();
+ }
+ else if ( Attribute.WRITABLE.equals( name ) )
+ {
+ return file.isAccessible();
+ }
+ throw new IOException( path + "'s Unknown attribute :" + name );
+ }
+
+ @Override
+ public void set(String path, Attribute name, Object value)
+ throws IOException {
+ if ( Attribute.QUALIFIED.equals( name ) )
+ {
+// signatureFile.setPersistentProperty(SignatureUtility.stateQualifiedName, "false"); //$NON-NLS-1$
+ return ;
+ }
+
+ throw new UnsupportedOperationException();
+ }
+
+ /* (non-Javadoc)
+ * @see java.lang.Object#toString()
+ */
+ @Override
+ public String toString()
+ {
+ return getClass().getSimpleName() + "@" + Integer.toHexString( hashCode() ).substring( 0, 4 );
+ }
+
+}
diff --git a/org.tizen.common/src/org/tizen/common/file/FileHandler.java b/org.tizen.common/src/org/tizen/common/file/FileHandler.java
new file mode 100644
index 000000000..61d7a81b1
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/file/FileHandler.java
@@ -0,0 +1,235 @@
+/*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common.file;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Collection;
+
+/**
+ * <p>
+ * FileHandler.
+ *
+ * Class to handle file system as abstract api
+ *
+ * </p>
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ */
+public interface
+FileHandler
+{
+ /**
+ * <p>
+ * Attribute.
+ *
+ * File attribute
+ * </p>
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ */
+ enum Attribute
+ {
+ CWD, // Current Working Directory
+ PATH, // Abstract canonical path
+ TYPE, // Type( FILE / DIRECTORY / UNKNOWN )
+ EXISTS, // true / false
+ READABLE, // true / false
+ WRITABLE, // true / false
+ HIDDEN, // true / false
+ READONLY, // true / false
+ MODIFIED, // long
+ URI, // String
+ URL, // String
+ QUALIFIED,
+ CUSTOM
+ }
+
+ /**
+ * <p>
+ * Type.
+ *
+ * Value of {@link Attribute#TYPE}
+ * </p>
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ */
+ enum Type
+ {
+ FILE,
+ DIRECTORY,
+ UNKNOWN
+ }
+
+ /**
+ * Return cwd, abbreviating current working directory
+ *
+ * @return current working directory
+ */
+ String getCurrentWorkingDirectory();
+
+ /**
+ * Change current working directory to <code>cwd</code>
+ *
+ * @param cwd new current working directory
+ */
+ void setCurrentWorkingDirectory( final String cwd );
+
+ /* Directory */
+ /**
+ * Make new directory with <code>path</code>
+ *
+ * @param path path to directory
+ *
+ * @throws IOException If exception occured in making a directory
+ */
+ void makeDirectory( String path ) throws IOException;
+
+ /**
+ * Move <code>source</code> directory to <code>target</code>
+ *
+ * @param source directory path to move
+ * @param target path to move to
+ *
+ * @throws IOException If exception occured in moving a directory
+ */
+ void moveDirectory( String source, String target ) throws IOException;
+
+ /**
+ * Copy <code>source</code> directory to <code>target</code>
+ *
+ * @param source directory path to copy
+ * @param target path to copy to
+ *
+ * @throws IOException If exception occured in copying a directory
+ */
+ void copyDirectory( String source, String target ) throws IOException;
+
+ /**
+ * Delete <code>path</code> directory
+ *
+ * @param path directory path to delete
+ *
+ * @throws IOException If exception occured in deleting a directory
+ */
+ void removeDirectory( String path ) throws IOException;
+
+ /**
+ * List child directory and file in <code>path</code>
+ *
+ * @param path directory path
+ * @return child directory and file's path
+ *
+ * @throws IOException If exception occured in list child in directory
+ */
+ Collection<String> list( String path ) throws IOException;
+
+ /* File */
+ /**
+ * Save file in <code>path</code> using <code>out</code>
+ *
+ * @param path file path to write
+ * @param out {@link InputStream} to provide contents
+ *
+ * @throws IOException If exception occured in saving
+ */
+ void write( String path, InputStream out ) throws IOException;
+
+ /**
+ * Return {@link InputStream} to provice file contents
+ *
+ * @param path file path to read
+ * @return
+ * @throws IOException
+ */
+ InputStream read( String path ) throws IOException;
+
+ /**
+ * Move <code>source</code> file to <code>target</code>
+ *
+ * @param source file path to move
+ * @param target path to move to
+ *
+ * @throws IOException If exception occured in moving a file
+ */
+ void moveFile( String source, String target ) throws IOException;
+
+ /**
+ * Copy <code>source</code> file to <code>target</code>
+ *
+ * @param source file path to copy
+ * @param target path to copy to
+ *
+ * @throws IOException If exception occured in copying a file
+ */
+ void copyFile( String source, String target ) throws IOException;
+
+ /**
+ * Delete file in <code>path</code>
+ *
+ * @param path file path
+ *
+ * @throws IOException If exception occured in deletion
+ */
+ void removeFile( String path ) throws IOException;
+
+ /**
+ * Return <code>path</code>'s attribute value having <code>name</code> as attribute name
+ *
+ * @param path file path
+ * @param name attribute name
+ *
+ * @return attribute value
+ *
+ * @throws IOException If exception occured in reading attribute
+ */
+ Object get( final String path, Attribute name ) throws IOException;
+
+ /**
+ * Check if <code>path</code> file's attribute <code>name</code> is <code>true</code>
+ *
+ * @param path file path to check
+ * @param name attribute name
+ *
+ * @return boolean value if thread is <code>name</code> attribute
+ *
+ * @throws IOException If exception occured in reading attribute
+ */
+ boolean is( final String path, Attribute name ) throws IOException;
+
+ /**
+ * Set <code>path</code> file's attribute <code>name</code> as <code>value</code>
+ *
+ * @param path file path
+ * @param name attribute anme
+ * @param value attribute value
+ *
+ * @throws IOException If exception occured in change file attribute
+ *
+ * @see {@link Attribute}
+ */
+ void set( final String path, Attribute name, Object value ) throws IOException;
+
+}
diff --git a/org.tizen.common/src/org/tizen/common/file/Filter.java b/org.tizen.common/src/org/tizen/common/file/Filter.java
new file mode 100644
index 000000000..17af932db
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/file/Filter.java
@@ -0,0 +1,48 @@
+/*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common.file;
+
+/**
+ * <p>
+ * Filter.
+ *
+ * Object to check if path is valid
+ *
+ * </p>
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ */
+public interface Filter
+{
+ /**
+ * Check and return if <code>path</code> is valid when current working directory is <code>cwd</code>
+ *
+ * @param cwd current working directory
+ * @param path file path
+ *
+ * @return boolean value of validation
+ */
+ boolean accept( final String cwd, final String path );
+}
diff --git a/org.tizen.common/src/org/tizen/common/file/PatternFilter.java b/org.tizen.common/src/org/tizen/common/file/PatternFilter.java
new file mode 100644
index 000000000..f0600870e
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/file/PatternFilter.java
@@ -0,0 +1,77 @@
+/*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common.file;
+
+/**
+ * <p>
+ * PatternFilter.
+ *
+ * {@link Filter} using pattern
+ *
+ * </p>
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ */
+public class
+PatternFilter
+{
+ /**
+ * Pattern string
+ */
+ protected String pattern = "*";
+
+ /**
+ * Return pattern
+ *
+ * @return pattern
+ *
+ * {@link #pattern}
+ */
+ public
+ String
+ getPattern()
+ {
+ return this.pattern;
+ }
+
+ /**
+ * Set pattern
+ *
+ * @param pattern pattern to set
+ */
+ public
+ void
+ setPattern(
+ final String pattern
+ )
+ {
+ if ( null == pattern )
+ {
+ throw new NullPointerException();
+ }
+ this.pattern = pattern;
+ }
+
+}
diff --git a/org.tizen.common/src/org/tizen/common/file/SimpleFileFilter.java b/org.tizen.common/src/org/tizen/common/file/SimpleFileFilter.java
new file mode 100644
index 000000000..efd37f599
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/file/SimpleFileFilter.java
@@ -0,0 +1,193 @@
+/*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common.file;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.tizen.common.util.CollectionUtil;
+
+/**
+ * <p>
+ * SimpleFileFilter.
+ *
+ * File filter using including filter and excluding filter
+ *
+ * </p>
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ */
+public class
+SimpleFileFilter
+implements Filter
+{
+ /**
+ * Logger for this instance
+ */
+ protected final Logger logger = LoggerFactory.getLogger( getClass() );
+
+ /**
+ * Including filters
+ */
+ protected List<Filter> includes = new ArrayList<Filter>();
+
+ /**
+ * Excluding filters
+ */
+ protected List<Filter> excludes = new ArrayList<Filter>();
+
+ // Hiding collection
+ /**
+ * Clear including filters
+ */
+ public
+ void
+ clearIncludes()
+ {
+ includes.clear();
+ }
+
+ /**
+ * Set <code>filters</code> including filters
+ *
+ * @param filters {@link Filter}s to set
+ */
+ public
+ void
+ setIncludes(
+ final Filter... filters
+ )
+ {
+ clearIncludes();
+ addIncludes( filters );
+ }
+
+ /**
+ * Add <code>filters</code> to including filters
+ *
+ * @param filters {@link Filter}s to add
+ */
+ public
+ void
+ addIncludes(
+ final Filter... filters
+ )
+ {
+ for( final Filter filter : filters )
+ {
+ includes.add( filter );
+ }
+ logger.debug( "Include filters[{}] added", CollectionUtil.toString( filters ) );
+ }
+
+ /**
+ * Clear excluding filters
+ */
+ public
+ void
+ clearExcludes()
+ {
+ excludes.clear();
+ }
+
+ /**
+ * Set {@link Filter}s as excluding filters
+ * @param filters
+ */
+ public
+ void
+ setExcludes(
+ final Filter... filters
+ )
+ {
+ clearExcludes();
+ addExcludes( filters );
+ }
+
+ /**
+ * Add <code>filters</code> to excluding filters
+ *
+ * @param filters {@link Filter}s to add
+ */
+ public
+ void
+ addExcludes(
+ final Filter... filters
+ )
+ {
+ for( final Filter filter : filters )
+ {
+ excludes.add( filter );
+ }
+ logger.debug( "Excludes filters[{}] added", CollectionUtil.toString( filters ) );
+ }
+
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.file.Filter#accept(java.lang.String, java.lang.String)
+ */
+ @Override
+ public
+ boolean
+ accept(
+ final String cwd,
+ final String path
+ )
+ {
+ logger.trace( "Current working directory :{}, Path :{}", cwd, path );
+ logger.trace( "Excluding filters :{}", excludes );
+ for ( final Filter filter : excludes )
+ {
+ if ( filter.accept( cwd, path ) )
+ {
+ logger.debug( "Deny because of {}", filter );
+ return false;
+ }
+ }
+
+ logger.trace( "Including filters :{}", excludes );
+ for ( final Filter filter : includes )
+ {
+ if ( filter.accept( cwd, path ) )
+ {
+ logger.debug( "Accept because of {}", filter );
+ return true;
+ }
+ }
+
+ if ( includes.isEmpty() )
+ {
+ return true;
+ }
+ else if ( excludes.isEmpty() )
+ {
+ return false;
+ }
+ throw new IllegalStateException( "Include and Exclude rule is invalid" );
+ }
+
+}
diff --git a/org.tizen.common/src/org/tizen/common/file/StandardFileHandler.java b/org.tizen.common/src/org/tizen/common/file/StandardFileHandler.java
new file mode 100755
index 000000000..a0b852e84
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/file/StandardFileHandler.java
@@ -0,0 +1,394 @@
+/*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+
+package org.tizen.common.file;
+
+import static org.tizen.common.util.FilenameUtil.getCanonicalForm;
+import static org.tizen.common.util.IOUtil.tryClose;
+
+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 org.tizen.common.util.IOUtil;
+
+/**
+ * <p>
+ * StandardFileHandler.
+ *
+ * {@link FileHandler} to use java.io package api like {@link File}, {@link FileInputStream} and {@link FileOutputStream}
+ *
+ * </p>
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ */
+public class
+StandardFileHandler
+extends AbstractFileHandler
+{
+ /* (non-Javadoc)
+ * @see org.tizen.common.file.FileHandler#getCurrentWorkingDirectory()
+ */
+ @Override
+ public
+ String
+ getCurrentWorkingDirectory()
+ {
+ return new File( "." ).getAbsolutePath();
+ }
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.file.FileHandler#setCurrentWorkingDirectory(java.lang.String)
+ */
+ @Override
+ public
+ void
+ setCurrentWorkingDirectory(String cwd) {
+ throw new UnsupportedOperationException();
+ }
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.file.FileHandler#makeDirectory(java.lang.String)
+ */
+ @Override
+ public
+ void
+ makeDirectory(
+ final String path
+ )
+ throws IOException
+ {
+ new File( path ).mkdir();
+
+ }
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.file.FileHandler#moveDirectory(java.lang.String, java.lang.String)
+ */
+ @Override
+ public
+ void
+ moveDirectory(
+ final String source,
+ final String target
+ )
+ throws IOException
+ {
+ final File file = new File( source );
+ if ( !file.isDirectory() )
+ {
+ throw new IOException();
+ }
+ file.renameTo( new File( target ) );
+
+ }
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.file.FileHandler#copyDirectory(java.lang.String, java.lang.String)
+ */
+ @Override
+ public
+ void
+ copyDirectory(
+ final String source,
+ final String target
+ )
+ throws IOException
+ {
+ throw new UnsupportedOperationException();
+// final Stack<File> sourceStack = new Stack<File>();
+// final Stack<File> targetStack = new Stack<File>();
+// sourceStack.push( new File(source ) );
+// targetStack.push( new File( target ) );
+//
+// while ( !sourceStack.isEmpty() )
+// {
+// final File sourceFile = sourceStack.pop();
+// final File targetFile = targetStack.pop();
+//
+// if ( sourceFile.isDirectory() )
+// {
+// targetFile.mkdir();
+// for ( final File sourceChild : sourceFile.listFiles() )
+// {
+// sourceStack.push( sourceChild );
+// targetStack.push( new File( targetFile, sourceChild.getName() ) );
+// }
+// }
+// else if ( sourceFile.isFile())
+// {
+// final FileInputStream fileIn = new FileInputStream( sourceFile );
+// final FileOutputStream fileOut = new FileOutputStream( targetFile );
+//
+// IOUtil.redirect( fileIn, fileOut );
+// tryClose( fileOut, fileIn );
+// }
+// else {
+// Logger.error(sourceFile + " is not file or directory");
+// }
+// }
+ }
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.file.FileHandler#removeDirectory(java.lang.String)
+ */
+ @Override
+ public
+ void
+ removeDirectory(
+ final String path
+ )
+ throws IOException
+ {
+ if ( !Type.DIRECTORY.equals( get( path, Attribute.TYPE ) ) )
+ {
+ throw new IOException();
+ }
+
+ for ( final String childPath : list( path ) )
+ {
+ Object type = get( childPath, Attribute.TYPE );
+ if ( Type.DIRECTORY.equals( type ) )
+ {
+ removeDirectory( childPath );
+ }
+ else if ( Type.FILE.equals( type ) )
+ {
+ removeFile( childPath );
+ }
+ }
+
+ new File( path ).delete();
+ }
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.file.FileHandler#list(java.lang.String)
+ */
+ @Override
+ public
+ Collection<String>
+ list(
+ final String path
+ )
+ throws IOException
+ {
+ final File file = new File( path );
+ final File[] children = file.listFiles();
+ final ArrayList<String> ret = new ArrayList<String>();
+ for ( final File child : children )
+ {
+ ret.add( getCanonicalForm( child.getAbsolutePath() ) );
+ }
+
+ return ret;
+ }
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.file.FileHandler#write(java.lang.String, java.io.InputStream)
+ */
+ @Override
+ public
+ void
+ write(
+ final String path,
+ final InputStream in
+ )
+ throws IOException
+ {
+ final FileOutputStream fileOut = new FileOutputStream( path );
+
+ try
+ {
+ IOUtil.redirect( in, fileOut );
+ }
+ finally
+ {
+ tryClose( fileOut );
+ }
+ }
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.file.FileHandler#read(java.lang.String)
+ */
+ @Override
+ public
+ InputStream
+ read(
+ final String path
+ )
+ throws IOException
+ {
+ return new FileInputStream( path );
+ }
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.file.FileHandler#moveFile(java.lang.String, java.lang.String)
+ */
+ @Override
+ public
+ void
+ moveFile(
+ final String source,
+ final String target
+ )
+ throws IOException
+ {
+ final File file = new File( source );
+ if ( !file.isFile() )
+ {
+ throw new IOException();
+ }
+ file.renameTo( new File( target ) );
+ }
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.file.FileHandler#copyFile(java.lang.String, java.lang.String)
+ */
+ @Override
+ public
+ void
+ copyFile(
+ final String source,
+ final String target
+ )
+ throws IOException
+ {
+ final File file = new File( source );
+ if ( !file.isFile() )
+ {
+ throw new IOException();
+ }
+
+ final FileInputStream sourceIn = new FileInputStream( source );
+ final FileOutputStream targetOut = new FileOutputStream( target );
+ try
+ {
+ IOUtil.redirect( sourceIn, targetOut );
+ }
+ finally
+ {
+ tryClose( targetOut, sourceIn );
+ }
+ }
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.file.FileHandler#removeFile(java.lang.String)
+ */
+ @Override
+ public
+ void
+ removeFile(
+ final String path
+ )
+ throws IOException
+ {
+ final File file = new File( path );
+ if ( !file.isFile() )
+ {
+ throw new IOException();
+ }
+
+ file.delete();
+ }
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.file.FileHandler#get(java.lang.String, org.tizen.common.file.FileHandler.Attribute)
+ */
+ @Override
+ public
+ Object
+ get(
+ final String path,
+ final Attribute name
+ )
+ throws IOException
+ {
+ logger.trace( "Path :{}, Attribute :{}", path, name );
+
+ final File file = new File( path );
+
+ if ( Attribute.TYPE.equals( name ) )
+ {
+ if ( file.isDirectory() )
+ {
+ return Type.DIRECTORY;
+ }
+ else if ( file.isFile() )
+ {
+ return Type.FILE;
+ }
+ }
+ else if ( Attribute.EXISTS.equals( name ) )
+ {
+ return file.exists();
+
+ }
+ else if ( Attribute.PATH.equals( name ) )
+ {
+ return file.getCanonicalPath();
+ }
+ else if ( Attribute.URI.equals( name ) || Attribute.URL.equals( name ) )
+ {
+ return file.toURI().toURL().toString();
+ }
+ else if ( Attribute.MODIFIED.equals( name ) )
+ {
+ return file.lastModified();
+ }
+ else if ( Attribute.HIDDEN.equals( name ) )
+ {
+ return file.isHidden();
+ }
+ else if ( Attribute.READABLE.equals( name ) )
+ {
+ return file.canRead();
+ }
+ else if ( Attribute.WRITABLE.equals( name ) )
+ {
+ return file.canWrite();
+ }
+ throw new IOException( path + "'s Unknown attribute :" + name );
+ }
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.file.FileHandler#set(java.lang.String, org.tizen.common.file.FileHandler.Attribute, java.lang.Object)
+ */
+ @Override
+ public void
+ set(
+ final String path,
+ final Attribute name,
+ final Object value
+ )
+ throws IOException
+ {
+ }
+
+
+}
diff --git a/org.tizen.common/src/org/tizen/common/file/VirtualFileHandler.java b/org.tizen.common/src/org/tizen/common/file/VirtualFileHandler.java
new file mode 100644
index 000000000..c35f4d084
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/file/VirtualFileHandler.java
@@ -0,0 +1,798 @@
+/*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common.file;
+
+import static org.tizen.common.util.ArrayUtil.size;
+import static org.tizen.common.util.FilenameUtil.SEPARATOR_DIRECTORY;
+import static org.tizen.common.util.FilenameUtil.addTailingPath;
+import static org.tizen.common.util.FilenameUtil.getCanonicalFragments;
+import static org.tizen.common.util.FilenameUtil.getFilename;
+import static org.tizen.common.util.FilenameUtil.removeTailingPath;
+import static org.tizen.common.util.IOUtil.tryClose;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.tizen.common.util.IOUtil;
+import org.tizen.common.util.StringUtil;
+
+/**
+ * <p>
+ * VirtualFileHandler.
+ *
+ * {@link FileHandler} to handling in memory
+ *
+ * </p>
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ */
+public class
+VirtualFileHandler
+extends AbstractFileHandler
+{
+
+ /**
+ * <p>
+ * File.
+ *
+ * File contents container
+ *
+ * </p>
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ */
+ private class
+ File
+ implements Cloneable
+ {
+ /**
+ * File name
+ */
+ String name;
+
+ /**
+ * File contents
+ */
+ byte[] contents;
+
+ /**
+ * File attributes
+ */
+ HashMap<Attribute, Object> attr = new HashMap<Attribute, Object>();
+
+ /**
+ * Default constructor
+ */
+ public File()
+ {
+ }
+
+ /**
+ * Constructor with name and contents
+ *
+ * @param name file name
+ * @param contents file contents
+ */
+ public
+ File(
+ final String name,
+ final byte[] contents
+ )
+ {
+ this.name = name;
+ this.contents = contents;
+ }
+
+ /**
+ * Return file name
+ *
+ * @return file name
+ */
+ public
+ String
+ getName()
+ {
+ return this.name;
+ }
+
+ /**
+ * Return file contents
+ *
+ * @return file contents
+ */
+ public
+ byte[] getContents()
+ {
+ return this.contents;
+ }
+
+ /**
+ * Set <code>contents</code> as file contents
+ *
+ * @param contents new file contents
+ */
+ public
+ void
+ setContents(
+ final byte[] contents
+ )
+ {
+ this.contents = contents;
+ }
+
+ /**
+ * Set file attribute value whose name is <code>name</code> as <code>value</code>
+ *
+ * @param name attribute name
+ * @param value attribute value
+ */
+ public
+ void
+ setAttribute(
+ final Attribute name,
+ final Object value
+ )
+ {
+ attr.put( name, value );
+ }
+ /**
+ * Return file attribute value whose name is <code>name</code>
+ *
+ * @param name attribute name
+ *
+ * @return attribute value
+ */
+ public
+ Object
+ getAttribute(
+ final Attribute name
+ )
+ {
+ return attr.get( name );
+ }
+
+ /* (non-Javadoc)
+ * @see java.lang.Object#clone()
+ */
+ @Override
+ public
+ Object
+ clone()
+ {
+ final File file = new File();
+ file.name = this.name;
+ file.contents = this.contents;
+ return file;
+ }
+
+ }
+
+ /**
+ * <p>
+ * Directory.
+ *
+ * Directory in memory
+ *
+ * </p>
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ */
+ class Directory
+ extends File
+ implements Cloneable
+ {
+ /**
+ * Child files & directories
+ */
+ protected final HashMap<String, File> name2file = new HashMap<String, File>();
+
+ /**
+ * Default constructor
+ */
+ public Directory()
+ {
+ }
+
+ /**
+ * Constructor with directory name
+ *
+ * @param name directory name
+ */
+ public
+ Directory(
+ final String name
+ )
+ {
+ super( name, null );
+ }
+
+ /**
+ * Return child file whose name is <code>name</code>
+ *
+ * @param name file name
+ *
+ * @return {@link File}
+ */
+ public
+ File
+ get(
+ final String name
+ )
+ {
+ return name2file.get( name );
+ }
+
+ /**
+ * Delete child file whose name is <code>name</code>
+ *
+ * @param name file name
+ *
+ * @return file to be deleted
+ */
+ public
+ File
+ remove(
+ final String name
+ )
+ {
+ return name2file.remove( name );
+ }
+
+ /**
+ * Add new file whose name is <code>contents<code> and whose contents is <code>contents</code>
+ *
+ * @param name file name
+ * @param contents file contents
+ */
+ public
+ void
+ add(
+ final String name,
+ final byte[] contents
+ )
+ {
+ name2file.put( name, new File( name, contents ) );
+ }
+
+ /**
+ * Add directory whose name is <code>name</code>
+ *
+ * @param name directory name
+ */
+ public
+ void
+ add(
+ final String name
+ )
+ {
+ name2file.put( name, new Directory( name ) );
+ }
+
+ /**
+ * Add <code>file</code>
+ *
+ * @param file file or directory to add
+ */
+ public
+ void
+ add(
+ final File file
+ )
+ {
+ name2file.put( file.getName(), file );
+ }
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.file.VirtualFileHandler.File#clone()
+ */
+ @Override
+ public
+ Object
+ clone()
+ {
+ final Directory dir = new Directory();
+ dir.contents = this.contents;
+ dir.name = this.name;
+ for ( final String name : name2file.keySet() )
+ {
+ name2file.put( name, (File) name2file.get( name ).clone() );
+ }
+
+ return dir;
+ }
+
+ /* (non-Javadoc)
+ * @see java.lang.Object#toString()
+ */
+ @Override
+ public
+ String
+ toString()
+ {
+ return name2file.keySet().toString();
+ }
+ }
+
+ /**
+ * Prefix abstract path
+ */
+ protected static final String ROOT_PREFIX = "/";
+
+ /**
+ * Logger for this instance
+ */
+ protected final Logger logger = LoggerFactory.getLogger( getClass() );
+
+ /**
+ * Root directory
+ */
+ protected final Directory root = new Directory();
+
+ /**
+ * Current working directory
+ */
+ protected String cwd = "/";
+
+ /**
+ * Return {@link File} matching with <code>path</code>
+ *
+ * @param path file path
+ * @return {@link File} matching with <code>path</code>
+ *
+ * @throws IOException If file is not accessible
+ */
+ protected
+ File
+ getFile(
+ final String path
+ )
+ throws IOException
+ {
+ logger.trace( "Path :{}", path );
+
+ final String[] fragments = getCanonicalFragments( path );
+
+ File iter = root;
+ for ( int i = 0, n = fragments.length ; i < n ; ++i )
+ {
+ Directory dir = (Directory) iter;
+ iter = dir.get( fragments[i] );
+ if ( null == iter )
+ {
+ logger.debug( "fragment :{}", fragments[i] );
+ logger.debug( "in-processing directory :{}", dir );
+
+ throw new IOException( "Can't access " + path );
+ }
+ }
+
+ return iter;
+ }
+
+ /**
+ * Return parent directory of file matching with <code>path</code>
+ * @param path file path
+ *
+ * @return parent directory
+ *
+ * @throws IOException If file or directory is not accessible
+ */
+ public
+ Directory
+ getParent(
+ final String path
+ )
+ throws IOException
+ {
+ final File parent = getFile( removeTailingPath( path, 1 ) );
+ if ( !( parent instanceof Directory ) )
+ {
+ throw new IOException();
+ }
+
+ return (Directory) parent;
+ }
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.file.FileHandler#makeDirectory(java.lang.String)
+ */
+ @Override
+ public
+ void
+ makeDirectory(
+ final String path
+ )
+ throws IOException
+ {
+ final Directory parent = getParent( path );
+ final String dirName = getFilename( path );
+ parent.add( dirName );
+ }
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.file.FileHandler#moveDirectory(java.lang.String, java.lang.String)
+ */
+ @Override
+ public
+ void
+ moveDirectory(
+ final String source,
+ final String target
+ )
+ throws IOException
+ {
+ final String filename = getFilename( source );
+
+ final Directory parent = getParent( source );
+ final File file = parent.get( filename );
+ if ( !( file instanceof Directory ) )
+ {
+ throw new IOException();
+ }
+ final Directory newParent = (Directory) getFile( target );
+ newParent.add( newParent.remove( filename ) );
+ }
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.file.FileHandler#copyDirectory(java.lang.String, java.lang.String)
+ */
+ @Override
+ public
+ void
+ copyDirectory(
+ final String source,
+ final String target
+ )
+ throws IOException
+ {
+ final Directory dir = (Directory) getFile( source );
+ final Directory targetDir = (Directory) getFile( target );
+
+ targetDir.add( (File) dir.clone() );
+ }
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.file.FileHandler#removeDirectory(java.lang.String)
+ */
+ @Override
+ public
+ void
+ removeDirectory(
+ final String path
+ )
+ throws IOException
+ {
+ final Directory dir = getParent( path );
+ final String name = getFilename( path );
+ dir.remove( name );
+ }
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.file.FileHandler#list(java.lang.String)
+ */
+ @Override
+ public
+ Collection<String>
+ list(
+ final String path
+ )
+ throws IOException
+ {
+ final Directory dir = (Directory) getFile( path );
+ final Collection<String> childNames = dir.name2file.keySet();
+ logger.trace( "Directory[{}]'s child :{}", path, childNames );
+
+ final ArrayList<String> fullNames = new ArrayList<String>();
+
+ for ( final String name : dir.name2file.keySet() )
+ {
+ fullNames.add( addTailingPath( path, name ) );
+ }
+
+ logger.debug( "Fullnames :\n{}", fullNames );
+ return fullNames;
+ }
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.file.FileHandler#write(java.lang.String, java.io.InputStream)
+ */
+ @Override
+ public
+ void
+ write(
+ final String path,
+ final InputStream in
+ )
+ throws IOException
+ {
+ final Directory parent = getParent( path );
+ if ( !(parent instanceof Directory ) )
+ {
+ throw new IOException();
+ }
+
+ final String filename = getFilename( path );
+
+ File file = parent.get( filename );
+
+ if ( file instanceof Directory )
+ {
+ throw new IOException();
+ }
+ if ( null == file )
+ {
+ file = new File( getFilename( path ), null );
+ }
+ getParent( path ).add( file );
+
+ final byte[] contents = IOUtil.getBytes( in );
+
+ if ( logger.isTraceEnabled() )
+ {
+ int nSize = size( contents );
+ logger.trace(
+ "Save file[{}] :{} byte(s)\n{}",
+ new Object[] {
+ path,
+ nSize,
+ StringUtil.text2hexa( contents, 0, Math.min( 64, size( contents ) ) ) + ( (64 < size( contents ) )?"...":"" )
+ }
+ );
+ }
+
+ file.setContents( contents );
+ }
+
+ /**
+ * write <code>contents</code> to file with <code>path</code>
+ *
+ * @param path file path
+ * @param contents file contents
+ *
+ * @throws IOException If file can't be writable
+ *
+ * @see {@link #write(String, InputStream)}
+ */
+ public
+ void
+ write(
+ final String path,
+ final String contents
+ )
+ throws IOException
+ {
+ logger.trace( "Save file :{}\n{}", path, contents );
+ final InputStream in = new ByteArrayInputStream( (null==contents)?(new byte[0]):contents.getBytes() );
+ try
+ {
+ write( path, in );
+ }
+ finally
+ {
+ tryClose( in );
+ }
+
+ }
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.file.FileHandler#read(java.lang.String)
+ */
+ @Override
+ public
+ InputStream
+ read(
+ final String path
+ )
+ throws IOException
+ {
+ final File file = getFile( path );
+ if ( file instanceof Directory )
+ {
+ throw new IOException();
+ }
+
+ return new ByteArrayInputStream( file.contents );
+ }
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.file.FileHandler#moveFile(java.lang.String, java.lang.String)
+ */
+ @Override
+ public
+ void
+ moveFile(
+ final String source,
+ final String target
+ )
+ throws IOException
+ {
+ final Directory directory = getParent( source );
+ final String fileName = getFilename( source );
+ final File file = directory.remove( fileName );
+ if ( null == file )
+ {
+ throw new IOException();
+ }
+
+ final Directory targetDirectory = (Directory) getFile( target );
+ targetDirectory.add( file );
+ }
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.file.FileHandler#copyFile(java.lang.String, java.lang.String)
+ */
+ @Override
+ public
+ void
+ copyFile(
+ final String source,
+ final String target
+ )
+ throws IOException
+ {
+ final Directory directory = getParent( source );
+ final String fileName = getFilename( source );
+ final File file = directory.get( fileName );
+ if ( null == file )
+ {
+ throw new IOException();
+ }
+
+ final Directory targetDirectory = (Directory) getFile( target );
+ targetDirectory.add( (File) file.clone() );
+ }
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.file.FileHandler#removeFile(java.lang.String)
+ */
+ @Override
+ public
+ void
+ removeFile(
+ final String path
+ )
+ throws IOException
+ {
+ final File file = getFile( path );
+ if ( file instanceof Directory )
+ {
+ throw new IOException();
+ }
+
+ final Directory directory = getParent( path );
+ final String fileName = getFilename( path );
+ directory.remove( fileName );
+ }
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.file.FileHandler#get(java.lang.String, org.tizen.common.file.FileHandler.Attribute)
+ */
+ @Override
+ public
+ Object
+ get(
+ final String path,
+ final Attribute name
+ )
+ throws IOException
+ {
+ File file = null;
+ try {
+ file = getFile( path );
+ } catch ( Throwable e )
+ {
+ }
+ if ( Attribute.TYPE.equals( name ) )
+ {
+ if ( file instanceof Directory )
+ {
+ return Type.DIRECTORY;
+ }
+ else if ( file instanceof File )
+ {
+ return Type.FILE;
+ }
+ }
+ else if ( Attribute.EXISTS.equals( name ) )
+ {
+ return ( null != file );
+
+ }
+ else if ( Attribute.PATH.equals( name ) )
+ {
+ if ( path.startsWith( ROOT_PREFIX ) )
+ {
+ return path;
+ }
+
+ return cwd + SEPARATOR_DIRECTORY + path;
+ }
+ else if ( Attribute.URI.equals( name ) || Attribute.URL.equals( name ) )
+ {
+ return "vf://" + path;
+ }
+ else
+ {
+ file.getAttribute( name );
+ return false;
+ }
+ throw new IOException( path + "'s Unknown attribute :" + name );
+ }
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.file.FileHandler#set(java.lang.String, org.tizen.common.file.FileHandler.Attribute, java.lang.Object)
+ */
+ @Override
+ public
+ void
+ set(
+ final String path,
+ final Attribute name,
+ final Object value
+ )
+ throws IOException
+ {
+ File file = null;
+ try {
+ file = getFile( path );
+ } catch ( Throwable e )
+ {
+ }
+ if ( null != file )
+ {
+ file.setAttribute( name, value );
+ }
+ }
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.file.FileHandler#getCurrentWorkingDirectory()
+ */
+ @Override
+ public
+ String
+ getCurrentWorkingDirectory() {
+ return this.cwd;
+ }
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.file.FileHandler#setCurrentWorkingDirectory(java.lang.String)
+ */
+ @Override
+ public
+ void
+ setCurrentWorkingDirectory(
+ final String cwd
+ )
+ {
+ this.cwd = cwd;
+ }
+
+}
diff --git a/org.tizen.common/src/org/tizen/common/file/filter/WildCardFilter.java b/org.tizen.common/src/org/tizen/common/file/filter/WildCardFilter.java
new file mode 100644
index 000000000..04ccb0e57
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/file/filter/WildCardFilter.java
@@ -0,0 +1,96 @@
+/*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common.file.filter;
+
+import org.apache.commons.io.FilenameUtils;
+import org.apache.commons.io.filefilter.WildcardFileFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.tizen.common.file.Filter;
+import org.tizen.common.file.PatternFilter;
+import org.tizen.common.util.FilenameUtil;
+
+/**
+ * WildCardFilter
+ *
+ * Filter using wildcard( ?, * )
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ */
+public class
+WildCardFilter
+extends PatternFilter
+implements Filter
+{
+ /**
+ * Logger for this instance
+ */
+ protected final Logger logger = LoggerFactory.getLogger( getClass() );
+
+ /**
+ * Default constructor
+ */
+ public WildCardFilter()
+ {
+ }
+
+ /**
+ * Constructor with pattern
+ *
+ * @param pattern pattern to apply
+ */
+ public WildCardFilter( final String pattern )
+ {
+ setPattern( pattern );
+ }
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.file.Filter#accept(java.lang.String, java.lang.String)
+ */
+ @Override
+ public
+ boolean
+ accept(
+ final String cwd,
+ final String path
+ )
+ {
+ logger.trace( "Current working directory :{}, Path :{}", cwd, path );
+ final String name = FilenameUtil.getFilename( path );
+ logger.trace( "Name :{}", name );
+ return FilenameUtils.wildcardMatch( name, getPattern() );
+ }
+
+ /* (non-Javadoc)
+ * @see java.lang.Object#toString()
+ */
+ @Override
+ public
+ String
+ toString()
+ {
+ return WildcardFileFilter.class.getName() + "[" + getPattern() + "]";
+ }
+}
diff --git a/org.tizen.common/src/org/tizen/common/file/filter/WildCardFilterFactory.java b/org.tizen.common/src/org/tizen/common/file/filter/WildCardFilterFactory.java
new file mode 100644
index 000000000..2cafcbfb9
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/file/filter/WildCardFilterFactory.java
@@ -0,0 +1,60 @@
+/*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common.file.filter;
+
+import org.tizen.common.FactoryWithArgument;
+import org.tizen.common.file.Filter;
+
+/**
+ * <p>
+ * WildCardFilterFactory.
+ *
+ * Factory to create {@link WildCardFilter} for pattern
+ * </p>
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ */
+public class
+WildCardFilterFactory
+implements FactoryWithArgument<Filter, String>
+{
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.FactoryWithArgument#create(java.lang.Object)
+ */
+ @Override
+ public
+ Filter
+ create(
+ final String arg
+ )
+ {
+ final WildCardFilter filter = new WildCardFilter();
+ filter.setPattern( arg );
+ return filter;
+ }
+
+
+}
diff --git a/org.tizen.common/src/org/tizen/common/handler/ClearHandler.java b/org.tizen.common/src/org/tizen/common/handler/ClearHandler.java
deleted file mode 100644
index ba8c72731..000000000
--- a/org.tizen.common/src/org/tizen/common/handler/ClearHandler.java
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
-* Common
-*
-* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
-*
-* Contact:
-* Kangho Kim <kh5325.kim@samsung.com>
-*
-* 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.
-*
-* Contributors:
-* - S-Core Co., Ltd
-*
-*/
-
-package org.tizen.common.handler;
-
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.ui.IViewPart;
-import org.eclipse.ui.handlers.HandlerUtil;
-import org.tizen.common.manager.StatusLineMessageManager;
-import org.tizen.common.model.ITableModel;
-
-
-
-public class ClearHandler extends AbstractHandler {
- private IViewPart part;
- private TableViewer viewer;
- private StatusLineMessageManager statusLine;
-
- private String message = Messages.ClearHandler_0;
-
- public Object execute(ExecutionEvent event) throws ExecutionException {
-
- part = (IViewPart)HandlerUtil.getActivePart(event);
- viewer = (TableViewer)part.getSite().getSelectionProvider();
- statusLine = new StatusLineMessageManager(part);
-
- clearData();
- return null;
- }
-
- private void clearData() throws ExecutionException {
- ITableModel model = (ITableModel)viewer.getInput();
- model.clear();
- viewer.refresh();
- statusLine.setMessage(message);
- }
-
-
-}
-
diff --git a/org.tizen.common/src/org/tizen/common/handler/ClipboardHandler.java b/org.tizen.common/src/org/tizen/common/handler/ClipboardHandler.java
deleted file mode 100644
index e31e5eed2..000000000
--- a/org.tizen.common/src/org/tizen/common/handler/ClipboardHandler.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
-* Common
-*
-* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
-*
-* Contact:
-* Kangho Kim <kh5325.kim@samsung.com>
-*
-* 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.
-*
-* Contributors:
-* - S-Core Co., Ltd
-*
-*/
-
-package org.tizen.common.handler;
-
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.swt.dnd.Clipboard;
-import org.eclipse.ui.handlers.HandlerUtil;
-
-/**
- * Superclass for clipboard related handlers providing safe creation and
- * disposal of the {@link Clipboard}.
- */
-public abstract class ClipboardHandler extends AbstractHandler {
- public Object execute(ExecutionEvent event) throws ExecutionException {
- Clipboard clipboard = new Clipboard(HandlerUtil.getActiveShell(event)
- .getDisplay());
- try {
- return execute(event, clipboard);
- } finally {
- clipboard.dispose();
- }
- }
-
- protected abstract Object execute(ExecutionEvent event, Clipboard clipboard)
- throws ExecutionException;
-} \ No newline at end of file
diff --git a/org.tizen.common/src/org/tizen/common/handler/CopyHandler.java b/org.tizen.common/src/org/tizen/common/handler/CopyHandler.java
deleted file mode 100644
index 54d604f79..000000000
--- a/org.tizen.common/src/org/tizen/common/handler/CopyHandler.java
+++ /dev/null
@@ -1,101 +0,0 @@
-/*
-* Common
-*
-* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
-*
-* Contact:
-* Kangho Kim <kh5325.kim@samsung.com>
-*
-* 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.
-*
-* Contributors:
-* - S-Core Co., Ltd
-*
-*/
-
-package org.tizen.common.handler;
-
-import java.util.ArrayList;
-import java.util.Collection;
-
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.swt.SWTError;
-import org.eclipse.swt.dnd.Clipboard;
-import org.eclipse.swt.dnd.TextTransfer;
-import org.eclipse.swt.dnd.Transfer;
-import org.eclipse.ui.handlers.HandlerUtil;
-import org.eclipse.ui.part.ResourceTransfer;
-
-/**
- * Copy each currently selected object in the Favorites view to the clipboard.
- */
-public class CopyHandler extends ClipboardHandler {
- /**
- * Called by the superclass {@link #execute(ExecutionEvent)} method so that
- * this method can concentrate on the operation and does not have to manage
- * clipboard creation and disposal.
- */
- public Object execute(ExecutionEvent event, Clipboard clipboard)
- throws ExecutionException {
- ISelection selection = HandlerUtil.getCurrentSelection(event);
- if (selection instanceof IStructuredSelection) {
- Object[] objects = ((IStructuredSelection) selection).toArray();
- if (objects.length > 0) {
- try {
- clipboard.setContents(new Object[] { asResources(objects),
- asText(objects), }, new Transfer[] {
- ResourceTransfer.getInstance(),
- TextTransfer.getInstance(), });
- } catch (SWTError error) {
- // Copy to clipboard failed.
- // This happens when another application
- // is accessing the clipboard while we copy.
- // Ignore the error.
- }
- }
- }
- return null;
- }
-
- public static IResource[] asResources(Object[] objects) {
- Collection<IResource> resources = new ArrayList<IResource>(
- objects.length);
- for (int i = 0; i < objects.length; i++) {
- Object each = objects[i];
- if (each instanceof IAdaptable) {
- IResource res = (IResource) ((IAdaptable) each)
- .getAdapter(IResource.class);
- if (res != null)
- resources.add(res);
- }
- }
- return resources.toArray(new IResource[resources.size()]);
- }
-
- public static String asText(Object[] objects) {
- StringBuffer buf = new StringBuffer();
- for (int i = 0; i < objects.length; i++) {
- Object each = objects[i];
- if (each != null) {
- buf.append(each.toString());
- }
- buf.append(System.getProperty("line.separator")); //$NON-NLS-1$
- }
- return buf.toString();
- }
-}
diff --git a/org.tizen.common/src/org/tizen/common/handler/Messages.java b/org.tizen.common/src/org/tizen/common/handler/Messages.java
deleted file mode 100644
index 7cb9e48ae..000000000
--- a/org.tizen.common/src/org/tizen/common/handler/Messages.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
-* Common
-*
-* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
-*
-* Contact:
-* Kangho Kim <kh5325.kim@samsung.com>
-*
-* 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.
-*
-* Contributors:
-* - S-Core Co., Ltd
-*
-*/
-
-package org.tizen.common.handler;
-
-import org.eclipse.osgi.util.NLS;
-
-public class Messages extends NLS {
- private static final String BUNDLE_NAME = "org.tizen.common.handler.messages"; //$NON-NLS-1$
- public static String ClearHandler_0;
- public static String OpenFileHandler_0;
- public static String OpenFileHandler_2;
- public static String OpenFileHandler_3;
- public static String SaveFileHandler_0;
- public static String SaveFileHandler_1;
- public static String SaveFileHandler_11;
- public static String SaveFileHandler_12;
- public static String SaveFileHandler_4;
- public static String SaveFileHandler_5;
- static {
- // initialize resource bundle
- NLS.initializeMessages(BUNDLE_NAME, Messages.class);
- }
-
- private Messages() {
- }
-}
diff --git a/org.tizen.common/src/org/tizen/common/handler/OpenFileHandler.java b/org.tizen.common/src/org/tizen/common/handler/OpenFileHandler.java
deleted file mode 100644
index f97b3e066..000000000
--- a/org.tizen.common/src/org/tizen/common/handler/OpenFileHandler.java
+++ /dev/null
@@ -1,103 +0,0 @@
-/*
-* Common
-*
-* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
-*
-* Contact:
-* Kangho Kim <kh5325.kim@samsung.com>
-*
-* 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.
-*
-* Contributors:
-* - S-Core Co., Ltd
-*
-*/
-
-package org.tizen.common.handler;
-
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.core.filesystem.EFS;
-import org.eclipse.core.filesystem.IFileInfo;
-import org.eclipse.core.filesystem.IFileStore;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.widgets.FileDialog;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IViewPart;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.handlers.HandlerUtil;
-import org.eclipse.ui.ide.IDE;
-import org.tizen.common.manager.StatusLineMessageManager;
-
-
-
-public class OpenFileHandler extends AbstractHandler {
- private IViewPart part;
- private String fileName;
- private Shell shell;
- private IWorkbenchPage page;
- private StatusLineMessageManager statusLine;
-
- private final String title = Messages.OpenFileHandler_0;
- private final String PARAMETER_ID = "org.tizen.common.command.openFile.parameter"; //$NON-NLS-1$
-
- public Object execute(ExecutionEvent event) throws ExecutionException {
-
- part = (IViewPart)HandlerUtil.getActivePart(event);
- shell = part.getSite().getShell();
- page = part.getSite().getPage();
- statusLine = new StatusLineMessageManager(part);
-
- String extension = event.getParameter(PARAMETER_ID);
-
- openFile(extension);
- return null;
- }
-
- private void openFile(String extension) throws ExecutionException {
- fileName = getLoadFileName(extension);
- if(fileName==null)
- return;
-
- IFileStore fileStore = EFS.getLocalFileSystem().getStore(new Path(fileName));
- IFileInfo fileInfo = fileStore.fetchInfo();
- fileInfo.setAttribute(EFS.ATTRIBUTE_READ_ONLY, true);
-
- if( fileInfo.isDirectory()||!fileInfo.exists() ){
- statusLine.setErrorMessage(Messages.OpenFileHandler_2);
- return;
- }
-
- try {
- IDE.openEditorOnFileStore(page, fileStore);
- } catch (PartInitException e) {
- statusLine.setErrorMessage(fileName+ Messages.OpenFileHandler_3);
- return;
- }
-
- }
-
- private String getLoadFileName(String extension) {
- String[] extFilter = {"*."+extension}; //$NON-NLS-1$
-
- FileDialog dialog = new FileDialog(shell, SWT.OPEN);
- dialog.setFilterExtensions(extFilter);
- dialog.setText(title);
- return dialog.open();
- }
-
-}
-
diff --git a/org.tizen.common/src/org/tizen/common/handler/OpenPreferencesHandler.java b/org.tizen.common/src/org/tizen/common/handler/OpenPreferencesHandler.java
deleted file mode 100644
index 32932b811..000000000
--- a/org.tizen.common/src/org/tizen/common/handler/OpenPreferencesHandler.java
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
-* Common
-*
-* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
-*
-* Contact:
-* Kangho Kim <kh5325.kim@samsung.com>
-*
-* 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.
-*
-* Contributors:
-* - S-Core Co., Ltd
-*
-*/
-
-package org.tizen.common.handler;
-
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.jface.preference.PreferenceDialog;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IViewPart;
-import org.eclipse.ui.dialogs.PreferencesUtil;
-import org.eclipse.ui.handlers.HandlerUtil;
-
-public class OpenPreferencesHandler extends AbstractHandler {
- private IViewPart part;
- private Shell shell;
- private final String PARAMETER_ID = "org.tizen.common.command.setting.parameter"; //$NON-NLS-1$
-
- public Object execute(ExecutionEvent event) throws ExecutionException {
-
- part = (IViewPart)HandlerUtil.getActivePart(event);
- shell = part.getSite().getShell();
-
- String preferenceId = event.getParameter(PARAMETER_ID);
- openPreferences(preferenceId);
- return null;
- }
-
- private void openPreferences(String preferenceId) throws ExecutionException {
- PreferenceDialog dialog = PreferencesUtil.createPreferenceDialogOn(shell,
- preferenceId, null, null);
- dialog.open();
- }
-
-
-
-}
-
diff --git a/org.tizen.common/src/org/tizen/common/handler/SaveFileHandler.java b/org.tizen.common/src/org/tizen/common/handler/SaveFileHandler.java
deleted file mode 100644
index c703e302d..000000000
--- a/org.tizen.common/src/org/tizen/common/handler/SaveFileHandler.java
+++ /dev/null
@@ -1,139 +0,0 @@
-/*
-* Common
-*
-* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
-*
-* Contact:
-* Kangho Kim <kh5325.kim@samsung.com>
-*
-* 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.
-*
-* Contributors:
-* - S-Core Co., Ltd
-*
-*/
-
-package org.tizen.common.handler;
-
-import java.io.File;
-import java.lang.reflect.InvocationTargetException;
-
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.jface.operation.IRunnableWithProgress;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.widgets.FileDialog;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IViewPart;
-import org.eclipse.ui.handlers.HandlerUtil;
-import org.tizen.common.manager.StatusLineMessageManager;
-import org.tizen.common.model.ITableModel;
-import org.tizen.common.util.DialogUtil;
-
-
-
-public class SaveFileHandler extends AbstractHandler {
- private IViewPart part;
- private TableViewer viewer;
- private String fileName;
- private Shell shell;
- private StatusLineMessageManager statusLine;
-
- private final String title = Messages.SaveFileHandler_0;
- private final String PARAMETER_ID = "org.tizen.common.command.saveFile.parameter"; //$NON-NLS-1$
-
-
- public Object execute(ExecutionEvent event) throws ExecutionException {
-
- part = (IViewPart)HandlerUtil.getActivePart(event);
- shell = part.getSite().getShell();
- statusLine = new StatusLineMessageManager(part);
-
- viewer = (TableViewer)part.getSite().getSelectionProvider();
- String extension = event.getParameter(PARAMETER_ID);
-
- if(!hasRecord())
- return null;
-
- try {
- saveFile(extension);
- } catch (Exception e) {
- e.printStackTrace();
- }
-
- return null;
- }
-
- private void saveFile(String extension) throws InvocationTargetException, InterruptedException {
- fileName = getSaveFileName(extension);
-
- if(fileName==null)
- return;
-
- if(!fileName.endsWith("."+extension)) //$NON-NLS-1$
- fileName= fileName+"."+extension; //$NON-NLS-1$
-
- if(!(new File(fileName).getParentFile().canWrite())){
- DialogUtil.openErrorDialog(Messages.SaveFileHandler_4);
- return;
- }
-
- part.getSite().getWorkbenchWindow().run(false, false, new IRunnableWithProgress(){
- public void run(IProgressMonitor monitor) {
- monitor.beginTask(Messages.SaveFileHandler_5, 100);
- writeRecord();
- monitor.done();
- }
- });
-
- showRecordCount();
-
- }
-
- private String getSaveFileName(String extension) {
- String[] extFilter = {"*."+extension,"*.*"}; //$NON-NLS-1$ //$NON-NLS-2$
-
- FileDialog dialog = new FileDialog(shell, SWT.SAVE);
- dialog.setFilterExtensions(extFilter);
- dialog.setText(title);
- dialog.setOverwrite(true);
- dialog.setFileName("untitled."+extension); //$NON-NLS-1$
- dialog.setFilterPath(System.getProperty("user.home")); //$NON-NLS-1$
-
- return dialog.open();
- }
-
- private void writeRecord() {
- ITableModel model = (ITableModel) viewer.getInput();
- model.save(fileName);
- }
-
- private void showRecordCount() {
- int size = ((ITableModel) viewer.getInput()).size();
- statusLine.setMessage(Messages.SaveFileHandler_1+size+Messages.SaveFileHandler_11 + fileName);
- }
-
- private boolean hasRecord() {
- int size = ((ITableModel) viewer.getInput()).size();
- if(size==0){
- statusLine.setErrorMessage(Messages.SaveFileHandler_12);
- return false;
- }else
- statusLine.setErrorMessage(""); //$NON-NLS-1$
- return true;
- }
-}
-
diff --git a/org.tizen.common/src/org/tizen/common/handler/messages.properties b/org.tizen.common/src/org/tizen/common/handler/messages.properties
deleted file mode 100644
index f9d98c9af..000000000
--- a/org.tizen.common/src/org/tizen/common/handler/messages.properties
+++ /dev/null
@@ -1,10 +0,0 @@
-ClearHandler_0=All data is cleared
-OpenFileHandler_0=Load File
-OpenFileHandler_2=Input file doesn't exist or isn't a file
-OpenFileHandler_3=isn't opened for internal error
-SaveFileHandler_0=Save File
-SaveFileHandler_1=Total
-SaveFileHandler_11=\ record is saved into
-SaveFileHandler_12=There is no record.
-SaveFileHandler_4=You can store a file into the directory that has write permission. please select another directory
-SaveFileHandler_5=Save File
diff --git a/org.tizen.common/src/org/tizen/common/manager/StatusLineMessageManager.java b/org.tizen.common/src/org/tizen/common/manager/StatusLineMessageManager.java
deleted file mode 100644
index 77d279e10..000000000
--- a/org.tizen.common/src/org/tizen/common/manager/StatusLineMessageManager.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
-* Common
-*
-* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
-*
-* Contact:
-* Kangho Kim <kh5325.kim@samsung.com>
-*
-* 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.
-*
-* Contributors:
-* - S-Core Co., Ltd
-*
-*/
-package org.tizen.common.manager;
-
-import org.eclipse.jface.action.IStatusLineManager;
-import org.eclipse.ui.IViewPart;
-import org.eclipse.ui.IWorkbenchPart;
-
-public class StatusLineMessageManager{
- private IViewPart part;
- private IStatusLineManager manager;
-
- public StatusLineMessageManager(IWorkbenchPart part){
- this.part = (IViewPart)part;
- this.manager = this.part.getViewSite().getActionBars().getStatusLineManager();
- }
-
- public void setErrorMessage(String message){
- manager.setErrorMessage(message);
- }
-
- public void setMessage(String message){
- manager.setMessage(message);
- }
-} \ No newline at end of file
diff --git a/org.tizen.common/src/org/tizen/common/manager/messages.properties b/org.tizen.common/src/org/tizen/common/manager/messages.properties
deleted file mode 100644
index 19dbd56f4..000000000
--- a/org.tizen.common/src/org/tizen/common/manager/messages.properties
+++ /dev/null
@@ -1 +0,0 @@
-ColorCache_0=Argument must not be null
diff --git a/org.tizen.common/src/org/tizen/common/model/AbstractTableModel.java b/org.tizen.common/src/org/tizen/common/model/AbstractTableModel.java
deleted file mode 100644
index 97555e65e..000000000
--- a/org.tizen.common/src/org/tizen/common/model/AbstractTableModel.java
+++ /dev/null
@@ -1,180 +0,0 @@
-/*
-* Common
-*
-* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
-*
-* Contact:
-* Kangho Kim <kh5325.kim@samsung.com>
-*
-* 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.
-*
-* Contributors:
-* - S-Core Co., Ltd
-*
-*/
-
-package org.tizen.common.model;
-
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileReader;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Iterator;
-
-import org.eclipse.ui.IMemento;
-import org.eclipse.ui.XMLMemento;
-
-public abstract class AbstractTableModel implements ITableModel {
- private static final String TAG_ROOT = "root"; //$NON-NLS-1$
-
- private Collection<AbstractTableVO> inventory = new ArrayList<AbstractTableVO>();
- protected AbstractTableVO source;
- private boolean isDirty = false;
-
- public AbstractTableModel(AbstractTableVO source) {
- this.source = source;
-
- }
-
-
-
- public ITableVO[] getDatas() {
- if (inventory == null)
- return null;
-
- return inventory.toArray(new AbstractTableVO[inventory.size()]);
- }
-
- public void add(Collection<AbstractTableVO> datas) {
- if (datas == null)
- return;
-
- inventory.addAll(datas);
- }
-
- public int size(){
- return inventory.size();
- }
-
- public void add(AbstractTableVO data) {
- inventory.add(data);
- }
-
- public void remove(Collection<AbstractTableVO> datas) {
- if (datas == null)
- return;
-
- inventory.removeAll(datas);
- }
-
- public void remove(AbstractTableVO data) {
- inventory.remove(data);
- }
-
- public void clear() {
- inventory.clear();
- }
-
- public void load(String fileName) {
- if (inventory==null||source==null)
- return;
-
- FileReader reader = null;
- try {
- reader = new FileReader(new File(fileName));
- load(XMLMemento.createReadRoot(reader));
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- try {
- if (reader != null)
- reader.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
-
- private void load(XMLMemento memento) {
- IMemento[] children = memento.getChildren(getSourceName());
- AbstractTableVO data = null;
- String[] fields = source.getColumnNames();
- for (int i = 0; i < children.length; i++) {
- data = source.clone();
- for (int j = 0; j < fields.length; j++) {
- data.setColumnValue(j, children[i].getString(fields[j]));
- }
- add(data);
- }
- }
-
- public void save(String fileName) {
- if (inventory == null || source == null)
- return;
-
- XMLMemento memento = XMLMemento.createWriteRoot(TAG_ROOT);
- save(memento);
- FileWriter writer = null;
- try {
- writer = new FileWriter(fileName);
- memento.save(writer);
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- try {
- if (writer != null)
- writer.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
-
- private void save(XMLMemento memento) {
- Iterator<AbstractTableVO> iter = inventory.iterator();
- AbstractTableVO data = null;
- String[] fields = null;
-
- while (iter.hasNext()) {
- data = iter.next();
- fields = data.getColumnNames();
- IMemento child = memento.createChild(getSourceName());
- for (int j = 0; j < fields.length; j++) {
- child.putString(
- fields[j],
- String.valueOf(data.getColumnValue(j)));
- }
- }
-
- }
-
- public String getSourceName() {
- return this.source.getClass().getSimpleName();
- }
-
- public boolean isDirty(){
- return this.isDirty;
- }
-
- public synchronized void setDirty(boolean isDirty){
- this.isDirty = isDirty;
- }
-
-}
-
-
diff --git a/org.tizen.common/src/org/tizen/common/model/AbstractTableVO.java b/org.tizen.common/src/org/tizen/common/model/AbstractTableVO.java
deleted file mode 100644
index 8f359a677..000000000
--- a/org.tizen.common/src/org/tizen/common/model/AbstractTableVO.java
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
-* Common
-*
-* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
-*
-* Contact:
-* Kangho Kim <kh5325.kim@samsung.com>
-*
-* 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.
-*
-* Contributors:
-* - S-Core Co., Ltd
-*
-*/
-
-package org.tizen.common.model;
-
-public abstract class AbstractTableVO implements ITableVO{
- public abstract String[] getColumnNames();
- public abstract Object getColumnValue(int index);
- public abstract void setColumnValue(int index, Object value);
-
- public AbstractTableVO clone(){
- Object obj = null;
- try{
- obj = super.clone();
- }catch(CloneNotSupportedException e){
-
- }
- return (AbstractTableVO)obj;
- }
-
- public Object getColumnValue(String columnName){
- return getColumnValue(getColumnIndex(columnName));
- }
-
- public String getColumnName(int index){
- String[] columnNames = getColumnNames();
- if(index<0||index>columnNames.length)
- return null;
- else
- return columnNames[index];
- }
-
- public int getColumnIndex(String columnName){
- String[] columnNames = getColumnNames();
- int index =-1;
- for(int i=0;i<columnNames.length;i++){
- if(columnName.equals(columnNames[i])){
- index = i;
- break;
- }
- }
- return index;
- }
-
- @Override
- public String toString() {
- StringBuffer buf = new StringBuffer();
- String[] fields = getColumnNames();
- for (int j = 0; j < fields.length; j++) {
- Object obj = getColumnValue(j);
- buf.append(obj==null?"":String.valueOf(obj)); //$NON-NLS-1$
- if(j<fields.length-1)
- buf.append(","); //$NON-NLS-1$
- }
- return buf.toString();
- }
-
-}
diff --git a/org.tizen.common/src/org/tizen/common/model/AbstractTreeModel.java b/org.tizen.common/src/org/tizen/common/model/AbstractTreeModel.java
deleted file mode 100644
index 0282ddf99..000000000
--- a/org.tizen.common/src/org/tizen/common/model/AbstractTreeModel.java
+++ /dev/null
@@ -1,102 +0,0 @@
-/*
-* Common
-*
-* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
-*
-* Contact:
-* Kangho Kim <kh5325.kim@samsung.com>
-*
-* 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.
-*
-* Contributors:
-* - S-Core Co., Ltd
-*
-*/
-
-package org.tizen.common.model;
-
-import java.util.ArrayList;
-import java.util.Collection;
-
-import org.eclipse.ui.XMLMemento;
-
-public class AbstractTreeModel implements ITreeModel {
- private static final String TAG_ROOT = "root"; //$NON-NLS-1$
-
- private Collection<ITreeVO> inventory = new ArrayList<ITreeVO>();
- protected ITreeVO source;
- private boolean isDirty = false;
-
- public AbstractTreeModel(ITreeVO source){
-// if(source.getSuperclass() != ITreeVO.class)
- this.source = source;
- }
-
- public ITreeVO[] getDatas() {
- if (inventory == null)
- return null;
-
- return inventory.toArray(new ITreeVO[inventory.size()]);
- }
-
- public void add(Collection<ITreeVO> datas) {
- if (datas == null)
- return;
-
- inventory.addAll(datas);
- }
-
- public int size(){
- return inventory.size();
- }
-
- public void add(ITreeVO data) {
- inventory.add(data);
- }
-
- public void remove(Collection<ITreeVO> datas) {
- if (datas == null)
- return;
-
- inventory.removeAll(datas);
- }
-
- public void remove(ITreeVO data) {
- inventory.remove(data);
- }
-
- public void clear() {
- inventory.clear();
- }
-
- public void load(String fileName) {
- }
-
- private void load(XMLMemento memento) {
- }
-
- public void save(String fileName) {
- }
-
- private void save(XMLMemento memento) {
- }
-
- public String getSourceName() {
- return this.source.getClass().getSimpleName();
- }
-
-
-
-}
-
-
diff --git a/org.tizen.common/src/org/tizen/common/model/AbstractTreeVO.java b/org.tizen.common/src/org/tizen/common/model/AbstractTreeVO.java
deleted file mode 100644
index 8a7c0f050..000000000
--- a/org.tizen.common/src/org/tizen/common/model/AbstractTreeVO.java
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
-* Common
-*
-* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
-*
-* Contact:
-* Kangho Kim <kh5325.kim@samsung.com>
-*
-* 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.
-*
-* Contributors:
-* - S-Core Co., Ltd
-*
-*/
-
-package org.tizen.common.model;
-
-import java.util.ArrayList;
-
-public abstract class AbstractTreeVO implements ITreeVO{
-
- private String text;
- private String description;
- private Object data = null;
- private int level = 0;
-
- private AbstractTreeVO parent;
- private ArrayList<AbstractTreeVO> children;
-
- public AbstractTreeVO(AbstractTreeVO parent,String text) {
- this.parent = parent;
- this.text = text;
- this.level = parent==null?1:parent.getLevel()+1;
- if(parent!=null)
- parent.addChild(this);
- children = new ArrayList<AbstractTreeVO>();
- }
-
- public AbstractTreeVO(AbstractTreeVO parent) {
- this(parent,null);
- }
-
- public ITreeVO[] getChildren() {
- return (ITreeVO[])children.toArray(new ITreeVO[children.size()]);
- }
-
- public ITreeVO getParent(){
- return this.parent;
- }
-
- public boolean hasChildren() {
- return children.size()>0;
- }
-
- public int size() {
- return children.size();
- }
-
- public void addChild(ITreeVO child) {
- children.add((AbstractTreeVO)child);
- }
-
- public void removeChild(Object child) {
- children.remove(child);
- }
-
- public String toString() {
- return getText();
- }
-
- public String getText() {
- return text;
- }
-
- public void setText(String text) {
- this.text = text;
- }
-
- public String getDescription() {
- return description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
- public void setData(Object data) {
- this.data = data;
- }
-
- public Object getData(){
- return this.data;
- }
-
- public int getLevel(){
- return this.level;
- }
-
-}
diff --git a/org.tizen.common/src/org/tizen/common/model/ITableModel.java b/org.tizen.common/src/org/tizen/common/model/ITableModel.java
deleted file mode 100644
index e21b41f51..000000000
--- a/org.tizen.common/src/org/tizen/common/model/ITableModel.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
-* Common
-*
-* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
-*
-* Contact:
-* Kangho Kim <kh5325.kim@samsung.com>
-*
-* 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.
-*
-* Contributors:
-* - S-Core Co., Ltd
-*
-*/
-
-package org.tizen.common.model;
-
-import java.util.Collection;
-
-
-public interface ITableModel
-{
- public void add(AbstractTableVO datas);
- public void add(Collection<AbstractTableVO> datas);
- public void remove(AbstractTableVO datas);
- public void remove(Collection<AbstractTableVO> datas);
- public ITableVO[] getDatas();
- public void load(String fileName);
- public void save(String fileName);
- public void clear();
- public int size();
- public String getSourceName();
- public boolean isDirty();
- public void setDirty(boolean isDirty);
-}
diff --git a/org.tizen.common/src/org/tizen/common/model/ITreeVO.java b/org.tizen.common/src/org/tizen/common/model/ITreeVO.java
deleted file mode 100644
index b0968aaca..000000000
--- a/org.tizen.common/src/org/tizen/common/model/ITreeVO.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
-* Common
-*
-* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
-*
-* Contact:
-* Kangho Kim <kh5325.kim@samsung.com>
-*
-* 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.
-*
-* Contributors:
-* - S-Core Co., Ltd
-*
-*/
-
-package org.tizen.common.model;
-
-public interface ITreeVO extends IVO{
- public ITreeVO[] getChildren();
- public ITreeVO getParent();
- public boolean hasChildren();
- public int size();
- public void addChild(ITreeVO child);
- public void removeChild(Object child) ;
- public String getText();
- public void setText(String text);
- public String getDescription();
- public void setDescription(String description);
- public void setData(Object data);
- public Object getData();
- public int getLevel();
-}
diff --git a/org.tizen.common/src/org/tizen/common/model/IVO.java b/org.tizen.common/src/org/tizen/common/model/IVO.java
deleted file mode 100644
index c49cf134c..000000000
--- a/org.tizen.common/src/org/tizen/common/model/IVO.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
-* Common
-*
-* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
-*
-* Contact:
-* Kangho Kim <kh5325.kim@samsung.com>
-*
-* 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.
-*
-* Contributors:
-* - S-Core Co., Ltd
-*
-*/
-
-package org.tizen.common.model;
-
-public interface IVO extends Cloneable{
-}
diff --git a/org.tizen.common/src/org/tizen/common/preferences/PreferenceMessages.properties b/org.tizen.common/src/org/tizen/common/preferences/PreferenceMessages.properties
deleted file mode 100644
index c4856e3d8..000000000
--- a/org.tizen.common/src/org/tizen/common/preferences/PreferenceMessages.properties
+++ /dev/null
@@ -1,6 +0,0 @@
-TizenPreferencePage.0=General settings for Tizen developement:
-TizenPreferencePage.1=SDK Path settings
-TizenPreferencePage.2=Location:
-TizenPreferencePage.3=SDK Update
-TizenPreferencePage.4=Automatically find new updates and notify me
-
diff --git a/org.tizen.common/src/org/tizen/common/properties/InstallPathConfig.java b/org.tizen.common/src/org/tizen/common/properties/InstallPathConfig.java
deleted file mode 100644
index d49b70804..000000000
--- a/org.tizen.common/src/org/tizen/common/properties/InstallPathConfig.java
+++ /dev/null
@@ -1,141 +0,0 @@
-/*
-* Common
-*
-* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
-*
-* Contact:
-* Kangho Kim <kh5325.kim@samsung.com>
-*
-* 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.
-*
-* Contributors:
-* - S-Core Co., Ltd
-*
-*/
-
-package org.tizen.common.properties;
-
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStreamReader;
-
-import org.tizen.common.util.DialogUtil;
-import org.tizen.common.util.HostUtil;
-import org.tizen.common.util.OSChecker;
-
-
-
-final public class InstallPathConfig {
-
- private static String sdkInstallPath;
- private final static String SDKSUFFIX = ".TizenSDK"+File.separatorChar+"tizensdkpath";
- private final static String EMULATOR_PATH = "Emulator";
- private final static String INSTALLER_PATH = "InstallManager";
-
- // Registry Key
- private static final String REGISTRY_PATH_OF_SHELL_FOLDER = "HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders";
- // public static final String REGISTRY_APP_DATA_OF_SHELL_FOLDER = "AppData";
- private static final String REGISTRY_LOCAL_APP_DATA_OF_SHELL_FOLDER = "\"Local AppData\"";
- // Value Column
- private static final String REG_SZ = "REG_SZ";
-
- static {
- // FIXME : don't need the following lines if using environment variable
- String sdkPath;
-
- if (OSChecker.isWindows()) {
- String appdataPath = getRegistryValue(REGISTRY_PATH_OF_SHELL_FOLDER,REGISTRY_LOCAL_APP_DATA_OF_SHELL_FOLDER) ;
- sdkPath = appdataPath + File.separatorChar + SDKSUFFIX;
- loadSdkPath(sdkPath);
- } else if (OSChecker.isLinux() == true || OSChecker.isUnix() == true || OSChecker.isMAC() == true) {
- sdkPath= System.getProperty("user.home") + File.separatorChar + SDKSUFFIX;
- loadSdkPath(sdkPath);
- } else {
- DialogUtil.openMessageDialog(System.getProperty("os.name") + " is not supported currently.");
- System.exit(0);
- }
- }
-
- public static String getEmulatorPath(){
- return sdkInstallPath + File.separatorChar + EMULATOR_PATH;
- }
-
- /**
- * @deprecated Use {@link #getSDKPath()} instead.
- */
- @Deprecated
- public static String getIDEPath() {
- // FIXME : can't help but putting the code due to the Web IDE path , It has to be removed soon.
- return System.getProperty("user.dir");
- }
-
- public static String getSDKPath() {
- return sdkInstallPath;
- }
-
- public static String getInstallManagerPath() {
- return sdkInstallPath + File.separatorChar + INSTALLER_PATH;
- }
-
- private static void loadSdkPath(String sdkPath) {
- if (HostUtil.exists(sdkPath)) {
- String[] fileContent = HostUtil.getContents(sdkPath).split("=");
- if (HostUtil.exists(fileContent[1]))
- sdkInstallPath = fileContent[1];
- else {
- DialogUtil.openMessageDialog("Tizen SDK is not installed propertly.");
- System.exit(0);
- }
- } else {
- DialogUtil.openMessageDialog("Tizen SDK is not installed propertly.");
- System.exit(0);
- }
- }
- private static String getRegistryValue(String node, String key) {
- if (!OSChecker.isWindows())
- return null;
-
- BufferedReader br = null;
- String value = "";
-
- String query = "reg query " + "\"" + node + "\" /v " + key;
- try {
- Process process = Runtime.getRuntime().exec(query);
- String encoding = System.getProperty("sun.jnu.encoding");
- br = new BufferedReader(new InputStreamReader(process.getInputStream(), encoding));
-
- String line = null;
- while((line = br.readLine()) != null) {
- int index = line.indexOf(REG_SZ);
- if (index >= 0) {
- value = line.substring(index + REG_SZ.length()).trim();
- }
- }
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } finally {
- if (br != null) {
- try {
- br.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
-
- return value;
- }
-} \ No newline at end of file
diff --git a/org.tizen.common/src/org/tizen/common/queue/Queue.java b/org.tizen.common/src/org/tizen/common/queue/Queue.java
deleted file mode 100644
index 366aba6dd..000000000
--- a/org.tizen.common/src/org/tizen/common/queue/Queue.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
-* Common
-*
-* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
-*
-* Contact:
-* Kangho Kim <kh5325.kim@samsung.com>
-*
-* 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.
-*
-* Contributors:
-* - S-Core Co., Ltd
-*
-*/
-
-package org.tizen.common.queue;
-
-import java.util.concurrent.ConcurrentLinkedQueue;
-
-public class Queue<T>{
-
- private ConcurrentLinkedQueue<T> queue = new ConcurrentLinkedQueue<T>();
- private boolean waiting = false;
-
- public synchronized void add(T e){
- queue.add(e);
- if(waiting)
- notify();
- }
-
- public synchronized T poll(){
- while (isEmpty()) {
- try {
- waiting = true;
- wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- waiting = false;
- return queue.poll();
- }
-
- public synchronized void clear(){
- queue.clear();
- }
-
- public boolean isEmpty() {
- return queue.isEmpty();
- }
-
- public int size() {
- return queue.size();
- }
-
- public synchronized void stop() {
- if (waiting)
- notify();
- }
-
-}
diff --git a/org.tizen.common/src/org/tizen/common/swt/CommonColor.java b/org.tizen.common/src/org/tizen/common/ui/CommonColor.java
index e9e9466ce..702d37745 100644
--- a/org.tizen.common/src/org/tizen/common/swt/CommonColor.java
+++ b/org.tizen.common/src/org/tizen/common/ui/CommonColor.java
@@ -24,20 +24,24 @@
* - S-Core Co., Ltd
*/
-package org.tizen.common.swt;
+package org.tizen.common.ui;
import org.eclipse.swt.graphics.Color;
-import org.eclipse.ui.PlatformUI;
+import org.tizen.common.util.cache.ColorCache;
/**
- * Common SWT Color
+ * Predefined Common SWT Color
+ *
* @author Gyeongseok Seo <gyeongseok.seo@samsung.com>
*
*/
public class CommonColor {
- public static final Color BLACK = new Color(PlatformUI.getWorkbench().getDisplay(), 0, 0, 0);
- public static final Color RED = new Color(PlatformUI.getWorkbench().getDisplay(), 255, 0, 0);
- public static final Color ORANGE_RED = new Color(PlatformUI.getWorkbench().getDisplay(), 255, 69, 0);
- public static final Color ROYAL_BLUE = new Color(PlatformUI.getWorkbench().getDisplay(), 65, 105, 225);
- public static final Color YELLOW_GREEN = new Color(PlatformUI.getWorkbench().getDisplay(), 153, 204, 50);
+ public static final Color BLACK = ColorCache.getBlack();
+ public static final Color RED = ColorCache.getColor( 255, 0, 0 );
+ public static final Color ORANGE_RED = ColorCache.getColor( 255, 69, 0 );
+ public static final Color ROYAL_BLUE = ColorCache.getColor( 65, 105, 225 );
+ public static final Color YELLOW = ColorCache.getColor( 255, 255, 0 );
+ public static final Color LIGHT_YELLOW = ColorCache.getColor( 255, 255, 224 );
+ public static final Color YELLOW_GREEN = ColorCache.getColor( 153, 204, 50 );
+ public static final Color DARK_GOLDENROD = ColorCache.getColor( 184, 134, 11 );
}
diff --git a/org.tizen.common/src/org/tizen/common/ui/TableToolTipListener.java b/org.tizen.common/src/org/tizen/common/ui/TableToolTipListener.java
new file mode 100644
index 000000000..e49672a67
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/ui/TableToolTipListener.java
@@ -0,0 +1,133 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* Ho Namkoong <ho.namkoong@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+
+package org.tizen.common.ui;
+
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.graphics.Point;
+import org.eclipse.swt.graphics.Rectangle;
+import org.eclipse.swt.layout.FillLayout;
+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.swt.widgets.TableItem;
+import org.tizen.common.util.SWTUtil;
+
+/**
+ * TableToolTipListener
+ *
+ * Add tool tip to the table
+ *
+ * @author Ho Namkoong{@literal <ho.namkoong@samsung.com>} (S-Core)
+ */
+public abstract class TableToolTipListener implements Listener{
+
+ private Shell tip = null;
+ private Label label = null;
+ private Table table = null;
+
+ /**
+ * Gets tooltip text from tableitem.
+ *
+ * @param item table item from which tooltip text is extracted.
+ * @return tooltip text
+ */
+ protected abstract String getLabelText(TableItem item);
+
+ /**
+ * Constructor with target table
+ *
+ * @param table will be added listener.
+ */
+
+ public void setTable(Table table) {
+ this.table = table;
+ }
+
+ @Override
+ public void handleEvent(Event event) {
+ int eventType = event.type;
+
+ if(SWT.MouseMove == eventType || SWT.MouseWheel == eventType || SWT.Dispose == eventType) {
+ if(tip != null) {
+ tip.dispose();
+ tip = null;
+ label = null;
+ return;
+ }
+ }
+ if(SWT.MouseHover == eventType) {
+ TableItem item = this.table.getItem(new Point(event.x, event.y));
+ if(item != null) {
+ if(tip != null && !tip.isDisposed()) {
+ tip.dispose();
+ }
+ tip = new Shell(SWTUtil.getActiveShell(), SWT.ON_TOP | SWT.TOOL);
+ tip.setLayout(new FillLayout());
+
+ label = new Label(tip, SWT.None);
+ label.setText(this.getLabelText(item));
+ label.setData(item);
+
+ label.addListener(SWT.MouseExit, labelListener);
+ label.addListener(SWT.MouseDown, labelListener);
+ label.addListener(SWT.MouseWheel, labelListener);
+
+ Point size = tip.computeSize(SWT.DEFAULT, SWT.DEFAULT);
+ Rectangle rect = item.getBounds(0);
+ Point pt = this.table.toDisplay(rect.x, rect.y);
+ tip.setBounds(pt.x, pt.y, size.x, size.y);
+ tip.setVisible(true);
+ }
+ }
+ }
+
+ final private Listener labelListener = new Listener() {
+
+ @Override
+ public void handleEvent(Event event) {
+ Label label = (Label)event.widget;
+ Shell shell = label.getShell();
+
+ int eventType = event.type;
+ if(SWT.MouseDown == eventType) {
+ if(table != null) {
+ Event e = new Event();
+ e.item = (TableItem) label.getData();
+
+ table.setSelection((TableItem)e.item);
+ table.notifyListeners(SWT.Selection, e);
+ }
+ return;
+ }
+ if(SWT.MouseExit == eventType || SWT.MouseWheel == eventType) {
+ shell.dispose();
+ return;
+ }
+ }
+ };
+}
diff --git a/org.tizen.common/src/org/tizen/common/swt/ClosableTray.java b/org.tizen.common/src/org/tizen/common/ui/dialog/ClosableTray.java
index ec149654f..34d96d075 100644
--- a/org.tizen.common/src/org/tizen/common/swt/ClosableTray.java
+++ b/org.tizen.common/src/org/tizen/common/ui/dialog/ClosableTray.java
@@ -23,7 +23,7 @@
*
*/
-package org.tizen.common.swt;
+package org.tizen.common.ui.dialog;
import org.eclipse.jface.action.ContributionItem;
import org.eclipse.jface.action.ToolBarManager;
@@ -47,6 +47,7 @@ import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
+import org.tizen.common.util.SWTUtil;
/**
@@ -60,7 +61,7 @@ public abstract class ClosableTray extends DialogTray {
private Shell shell;
private void createImages() {
- Display display = Display.getCurrent();
+ Display display = SWTUtil.getDisplay();
int[] shape = new int[] {
3, 3, 5, 3, 7, 5, 8, 5, 10, 3, 12, 3, 12, 5, 10, 7, 10, 8, 12, 10,
12, 12, 10, 12, 8, 10, 7, 10, 5, 12, 3, 12, 3, 10, 5, 8, 5, 7, 3, 5
@@ -169,4 +170,4 @@ public abstract class ClosableTray extends DialogTray {
closeHover.dispose();
}
}
-} \ No newline at end of file
+}
diff --git a/org.tizen.common/src/org/tizen/common/ui/dialog/PasswordInputDialog.java b/org.tizen.common/src/org/tizen/common/ui/dialog/PasswordInputDialog.java
new file mode 100644
index 000000000..0229496b6
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/ui/dialog/PasswordInputDialog.java
@@ -0,0 +1,114 @@
+/*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common.ui.dialog;
+
+import static org.tizen.common.util.SWTUtil.getActiveShell;
+import static org.tizen.common.util.StringUtil.EMPTY_STRING;
+
+import org.eclipse.jface.dialogs.IInputValidator;
+import org.eclipse.jface.dialogs.InputDialog;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.widgets.Shell;
+
+/**
+ * <p>
+ * PasswordInputDialog.
+ *
+ * Dialog for password input
+ * </p>
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ */
+public class
+PasswordInputDialog
+extends InputDialog
+{
+ /**
+ * Constructor with title, message
+ *
+ * @param dialogTitle title of dialog
+ * @param dialogMessage message of dialog
+ *
+ * @see #PasswordInputDialog(Shell, String, String)
+ */
+
+ public
+ PasswordInputDialog(
+ final String dialogTitle,
+ final String dialogMessage
+ )
+ {
+ this( getActiveShell(), dialogTitle, dialogMessage );
+ }
+
+ /**
+ * Constructor with shell, title, message
+ *
+ * @param parentShell parent of dialog shell
+ * @param dialogTitle title of dialog
+ * @param dialogMessage message of dialog
+ *
+ * @see #PasswordInputDialog(Shell, String, String, IInputValidator)
+ */
+ public
+ PasswordInputDialog(
+ final Shell parentShell,
+ final String dialogTitle,
+ final String dialogMessage
+ )
+ {
+ this( parentShell, dialogTitle, dialogMessage, null );
+ }
+
+ /**
+ * Constructor with shell, title, message and input validator
+ *
+ * @param parentShell parent of dialog shell
+ * @param dialogTitle title of dialog
+ * @param dialogMessage message of dialog
+ * @param validator validator for input
+ */
+ public
+ PasswordInputDialog(
+ final Shell parentShell,
+ final String dialogTitle,
+ final String dialogMessage,
+ final IInputValidator validator
+ )
+ {
+ super( parentShell, dialogTitle, dialogMessage, EMPTY_STRING, validator );
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.jface.dialogs.InputDialog#getInputTextStyle()
+ */
+ @Override
+ protected
+ int
+ getInputTextStyle()
+ {
+ return SWT.SINGLE | SWT.BORDER | SWT.PASSWORD;
+ }
+} \ No newline at end of file
diff --git a/org.tizen.common/src/org/tizen/common/manager/Messages.java b/org.tizen.common/src/org/tizen/common/ui/page/preference/Messages.java
index f5fa5a835..169463a68 100644
--- a/org.tizen.common/src/org/tizen/common/manager/Messages.java
+++ b/org.tizen.common/src/org/tizen/common/ui/page/preference/Messages.java
@@ -22,19 +22,24 @@
* - S-Core Co., Ltd
*
*/
-
-package org.tizen.common.manager;
+package org.tizen.common.ui.page.preference;
import org.eclipse.osgi.util.NLS;
-public class Messages extends NLS {
- private static final String BUNDLE_NAME = "org.tizen.common.manager.messages"; //$NON-NLS-1$
- public static String ColorCache_0;
+public class Messages {
+
+ private static final String BUNDLE_NAME = Messages.class.getName();//$NON-NLS-1$
+
+ public static String DESCRIPTION;
+
+ public static String GROUP1;
+ public static String GROUP2;
+
+ public static String LABEL_LOCATION;
+ public static String LABEL_UPDATE;
+
static {
// initialize resource bundle
- NLS.initializeMessages(BUNDLE_NAME, Messages.class);
- }
-
- private Messages() {
+ NLS.initializeMessages( BUNDLE_NAME, Messages.class );
}
}
diff --git a/org.tizen.common/src/org/tizen/common/ui/page/preference/Messages.properties b/org.tizen.common/src/org/tizen/common/ui/page/preference/Messages.properties
new file mode 100644
index 000000000..b26e800b8
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/ui/page/preference/Messages.properties
@@ -0,0 +1,5 @@
+DESCRIPTION=General settings
+GROUP1=SDK path
+LABEL_LOCATION=Location:
+GROUP2=SDK update
+LABEL_UPDATE=Automatically find new updates at start-up and notify me
diff --git a/org.tizen.common/src/org/tizen/common/preferences/PreferenceMessages.java b/org.tizen.common/src/org/tizen/common/ui/page/preference/PreferenceMessages.java
index e095402de..0672b592b 100644
--- a/org.tizen.common/src/org/tizen/common/preferences/PreferenceMessages.java
+++ b/org.tizen.common/src/org/tizen/common/ui/page/preference/PreferenceMessages.java
@@ -22,7 +22,7 @@
* - S-Core Co., Ltd
*
*/
-package org.tizen.common.preferences;
+package org.tizen.common.ui.page.preference;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
diff --git a/org.tizen.common/src/org/tizen/common/ui/page/preference/PreferenceMessages.properties b/org.tizen.common/src/org/tizen/common/ui/page/preference/PreferenceMessages.properties
new file mode 100644
index 000000000..d91c289b8
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/ui/page/preference/PreferenceMessages.properties
@@ -0,0 +1,5 @@
+TizenPreferencePage.0=General settings
+TizenPreferencePage.1=SDK path
+TizenPreferencePage.2=Location:
+TizenPreferencePage.3=SDK update
+TizenPreferencePage.4=Automatically find new updates at start-up and notify me
diff --git a/org.tizen.common/src/org/tizen/common/preferences/TizenBasePreferencePage.java b/org.tizen.common/src/org/tizen/common/ui/page/preference/TizenBasePreferencePage.java
index c90b83721..040033f9a 100644
--- a/org.tizen.common/src/org/tizen/common/preferences/TizenBasePreferencePage.java
+++ b/org.tizen.common/src/org/tizen/common/ui/page/preference/TizenBasePreferencePage.java
@@ -23,7 +23,7 @@
*
*/
-package org.tizen.common.preferences;
+package org.tizen.common.ui.page.preference;
import org.eclipse.jface.preference.BooleanFieldEditor;
import org.eclipse.jface.preference.DirectoryFieldEditor;
@@ -39,21 +39,24 @@ import org.eclipse.ui.IWorkbenchPreferencePage;
import org.tizen.common.CommonPlugin;
-public class TizenBasePreferencePage extends FieldEditorPreferencePage implements
- IWorkbenchPreferencePage {
+public class
+TizenBasePreferencePage
+extends FieldEditorPreferencePage
+implements IWorkbenchPreferencePage
+{
public final static String TIZENSDK_PATH = CommonPlugin.PLUGIN_ID + ".TizenSDKBasePreferencePage"; //$NON-NLS-1$
public static final String KEY_SDKLOCATION = "sdkpath"; //$NON-NLS-1$
public static final String KEY_SDKUPDATE = "sdkupdate"; //$NON-NLS-1$
public static final String VALUE_SDKLOCATION_DEFAULT = null;;
- public static final boolean VALUE_SDKUPDATE_DEFAULT = true;
+ public static final boolean VALUE_SDKUPDATE_DEFAULT = false;
public TizenBasePreferencePage() {
//super(GRID);
setPreferenceStore( CommonPlugin.getDefault().getPreferenceStore() );
//getPreferenceStore().addPropertyChangeListener( getPropertyChangeListener() );
- setDescription( PreferenceMessages.getString( "TizenPreferencePage.0" ) );
+ setDescription( Messages.DESCRIPTION );
}
@@ -64,7 +67,6 @@ public class TizenBasePreferencePage extends FieldEditorPreferencePage impleme
@Override
protected void createFieldEditors() {
- // TODO Auto-generated method stub
Composite composite = getFieldEditorParent();
GridLayout layout = new GridLayout();
@@ -90,16 +92,16 @@ public class TizenBasePreferencePage extends FieldEditorPreferencePage impleme
}
private void createPathSettingPreferences( Composite parent ) {
- Composite comp = createGroup( parent, PreferenceMessages.getString( "TizenPreferencePage.1" ),1 ); //$NON-NLS-1$
+ Composite comp = createGroup( parent, Messages.GROUP1, 1 );
Composite formatComposite = createCompositeEx( comp, 1, GridData.FILL_HORIZONTAL);
- DirectoryFieldEditor mDirectoryField = new DirectoryFieldEditor(TizenBasePreferencePage.KEY_SDKLOCATION, PreferenceMessages.getString("TizenPreferencePage.2"), formatComposite);
+ DirectoryFieldEditor mDirectoryField = new DirectoryFieldEditor(KEY_SDKLOCATION, Messages.LABEL_LOCATION, formatComposite);
addField(mDirectoryField);
}
private void createUpdateSettingPreferences( Composite parent ) {
- Composite comp = createGroup( parent, PreferenceMessages.getString( "TizenPreferencePage.3" ),1 ); //$NON-NLS-1$
+ Composite comp = createGroup( parent, Messages.GROUP2, 1 );
Composite formatComposite = createCompositeEx( comp, 1, GridData.FILL_HORIZONTAL);
- BooleanFieldEditor startupCheckEditor = new BooleanFieldEditor(TizenBasePreferencePage.KEY_SDKUPDATE, PreferenceMessages.getString("TizenPreferencePage.4"), formatComposite);
+ BooleanFieldEditor startupCheckEditor = new BooleanFieldEditor(KEY_SDKUPDATE, Messages.LABEL_UPDATE, formatComposite);
addField(startupCheckEditor);
}
diff --git a/org.tizen.common/src/org/tizen/common/swt/TrayWizardPage.java b/org.tizen.common/src/org/tizen/common/ui/page/wizard/TrayWizardPage.java
index c5c328c9f..9d346fc8c 100644
--- a/org.tizen.common/src/org/tizen/common/swt/TrayWizardPage.java
+++ b/org.tizen.common/src/org/tizen/common/ui/page/wizard/TrayWizardPage.java
@@ -23,7 +23,7 @@
*
*/
-package org.tizen.common.swt;
+package org.tizen.common.ui.page.wizard;
import org.eclipse.jface.dialogs.DialogTray;
import org.eclipse.jface.dialogs.TrayDialog;
@@ -38,6 +38,7 @@ 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.tizen.common.ui.dialog.ClosableTray;
/**
diff --git a/org.tizen.common/src/org/tizen/common/console/AnsicodeAdapter.java b/org.tizen.common/src/org/tizen/common/ui/view/console/AnsicodeAdapter.java
index 73a32ad3b..822d5ea85 100644..100755
--- a/org.tizen.common/src/org/tizen/common/console/AnsicodeAdapter.java
+++ b/org.tizen.common/src/org/tizen/common/ui/view/console/AnsicodeAdapter.java
@@ -23,35 +23,58 @@
* - S-Core Co., Ltd
*
*/
-package org.tizen.common.console;
+package org.tizen.common.ui.view.console;
+
+import static org.tizen.common.util.SWTUtil.getDisplay;
import java.util.ArrayList;
+import java.util.Collections;
import java.util.List;
+import java.util.Map;
import org.eclipse.swt.graphics.Color;
-import org.eclipse.ui.PlatformUI;
+import org.tizen.common.util.MapUtil;
public class AnsicodeAdapter {
public static final char ESCAPE = '\033'; // ANSI Escape Character that starts commands
- public static final Color BLACK = new Color(PlatformUI.getWorkbench().getDisplay(), 0, 0, 0); //Display.getCurrent().getSystemColor(SWT.COLOR_BLACK);
- public static final Color RED = new Color(PlatformUI.getWorkbench().getDisplay(), 255, 0, 0); //Display.getCurrent().getSystemColor(SWT.COLOR_RED);
- public static final Color GREEN = new Color(PlatformUI.getWorkbench().getDisplay(), 0, 255, 0); //Display.getCurrent().getSystemColor(SWT.COLOR_GREEN);
- public static final Color YELLOW = new Color(PlatformUI.getWorkbench().getDisplay(), 255, 255, 0); //Display.getCurrent().getSystemColor(SWT.COLOR_YELLOW);
- public static final Color BLUE = new Color(PlatformUI.getWorkbench().getDisplay(), 0,0,255); //Display.getCurrent().getSystemColor(SWT.COLOR_BLUE);
- public static final Color MAGENTA = new Color(PlatformUI.getWorkbench().getDisplay(), 255, 0, 255); //Display.getCurrent().getSystemColor(SWT.COLOR_MAGENTA);
- public static final Color CYAN = new Color(PlatformUI.getWorkbench().getDisplay(), 0,255, 255); //Display.getCurrent().getSystemColor(SWT.COLOR_CYAN);
- public static final Color WHITE = new Color(PlatformUI.getWorkbench().getDisplay(), 255, 255, 255); //Display.getCurrent().getSystemColor(SWT.COLOR_WHITE);
-
- public static final Color INTENSE_BLACK = new Color(PlatformUI.getWorkbench().getDisplay(), 0, 0, 0); //Display.getCurrent().getSystemColor(SWT.COLOR_DARK_GRAY);
- public static final Color INTENSE_RED = new Color(PlatformUI.getWorkbench().getDisplay(), 139, 0, 0); //Display.getCurrent().getSystemColor(SWT.COLOR_DARK_RED);
- public static final Color INTENSE_GREEN = new Color(PlatformUI.getWorkbench().getDisplay(), 0, 100, 0);//Display.getCurrent().getSystemColor(SWT.COLOR_DARK_GREEN);
- public static final Color INTENSE_YELLOW = new Color(PlatformUI.getWorkbench().getDisplay(), 250,250,210);//Display.getCurrent().getSystemColor(SWT.COLOR_DARK_YELLOW);
- public static final Color INTENSE_BLUE = new Color(PlatformUI.getWorkbench().getDisplay(), 0,0,139);//Display.getCurrent().getSystemColor(SWT.COLOR_DARK_BLUE);
- public static final Color INTENSE_MAGENTA = new Color(PlatformUI.getWorkbench().getDisplay(), 139,0,139);//Display.getCurrent().getSystemColor(SWT.COLOR_DARK_MAGENTA);
- public static final Color INTENSE_CYAN = new Color(PlatformUI.getWorkbench().getDisplay(), 0, 139, 139);//Display.getCurrent().getSystemColor(SWT.COLOR_DARK_CYAN);
- public static final Color INTENSE_WHITE = new Color(PlatformUI.getWorkbench().getDisplay(), 245, 245, 245);//Display.getCurrent().getSystemColor(SWT.COLOR_WHITE);
+ public static final Color BLACK = new Color(getDisplay(), 0, 0, 0); //Display.getCurrent().getSystemColor(SWT.COLOR_BLACK);
+ public static final Color RED = new Color(getDisplay(), 255, 0, 0); //Display.getCurrent().getSystemColor(SWT.COLOR_RED);
+ public static final Color GREEN = new Color(getDisplay(), 0, 255, 0); //Display.getCurrent().getSystemColor(SWT.COLOR_GREEN);
+ public static final Color YELLOW = new Color(getDisplay(), 255, 255, 0); //Display.getCurrent().getSystemColor(SWT.COLOR_YELLOW);
+ public static final Color BLUE = new Color(getDisplay(), 0,0,255); //Display.getCurrent().getSystemColor(SWT.COLOR_BLUE);
+ public static final Color MAGENTA = new Color(getDisplay(), 255, 0, 255); //Display.getCurrent().getSystemColor(SWT.COLOR_MAGENTA);
+ public static final Color CYAN = new Color(getDisplay(), 0,255, 255); //Display.getCurrent().getSystemColor(SWT.COLOR_CYAN);
+ public static final Color WHITE = new Color(getDisplay(), 255, 255, 255); //Display.getCurrent().getSystemColor(SWT.COLOR_WHITE);
+ public static final Color INTENSE_BLACK = new Color(getDisplay(), 0, 0, 0); //Display.getCurrent().getSystemColor(SWT.COLOR_DARK_GRAY);
+ public static final Color INTENSE_RED = new Color(getDisplay(), 139, 0, 0); //Display.getCurrent().getSystemColor(SWT.COLOR_DARK_RED);
+ public static final Color INTENSE_GREEN = new Color(getDisplay(), 0, 100, 0);//Display.getCurrent().getSystemColor(SWT.COLOR_DARK_GREEN);
+ public static final Color INTENSE_YELLOW = new Color(getDisplay(), 250,250,210);//Display.getCurrent().getSystemColor(SWT.COLOR_DARK_YELLOW);
+ public static final Color INTENSE_BLUE = new Color(getDisplay(), 0,0,139);//Display.getCurrent().getSystemColor(SWT.COLOR_DARK_BLUE);
+ public static final Color INTENSE_MAGENTA = new Color(getDisplay(), 139,0,139);//Display.getCurrent().getSystemColor(SWT.COLOR_DARK_MAGENTA);
+ public static final Color INTENSE_CYAN = new Color(getDisplay(), 0, 139, 139);//Display.getCurrent().getSystemColor(SWT.COLOR_DARK_CYAN);
+ public static final Color INTENSE_WHITE = new Color(getDisplay(), 245, 245, 245);//Display.getCurrent().getSystemColor(SWT.COLOR_WHITE);
+
+ public static final Map<Integer, Color[]> CODE2COLOR = Collections.unmodifiableMap( MapUtil.<Integer, Color[]>asMap( new Object[][] {
+ new Object[] { 30, new Color[] { INTENSE_BLACK, BLACK } },
+ new Object[] { 31, new Color[] { INTENSE_RED, RED } },
+ new Object[] { 32, new Color[] { INTENSE_GREEN, GREEN } },
+ new Object[] { 33, new Color[] { INTENSE_YELLOW, YELLOW } },
+ new Object[] { 34, new Color[] { INTENSE_BLUE, BLUE } },
+ new Object[] { 35, new Color[] { INTENSE_MAGENTA, MAGENTA } },
+ new Object[] { 36, new Color[] { INTENSE_CYAN, CYAN } },
+ new Object[] { 37, new Color[] { INTENSE_WHITE, WHITE } },
+ new Object[] { 40, new Color[] { INTENSE_BLACK, BLACK } },
+ new Object[] { 41, new Color[] { INTENSE_RED, RED } },
+ new Object[] { 42, new Color[] { INTENSE_GREEN, GREEN } },
+ new Object[] { 43, new Color[] { INTENSE_YELLOW, YELLOW } },
+ new Object[] { 44, new Color[] { INTENSE_BLUE, BLUE } },
+ new Object[] { 45, new Color[] { INTENSE_MAGENTA, MAGENTA } },
+ new Object[] { 46, new Color[] { INTENSE_CYAN, CYAN } },
+ new Object[] { 47, new Color[] { INTENSE_WHITE, WHITE } },
+ } ) );
+
private static int[] commands = {'m','n'}; //SGR , DSR
private static List<TextStyle> parseAnsiString(String ansiString) {
@@ -148,59 +171,16 @@ public class AnsicodeAdapter {
}
return color;
}
+
+
+
private static Color getColorFromANSICode(int code, boolean brighter) {
- switch (code) {
- case 30:
- case 40:
- if (brighter)
- return INTENSE_BLACK;
- else
- return BLACK;
- case 31:
- case 41:
- if (brighter)
- return INTENSE_RED;
- else
- return RED;
- case 32:
- case 42:
- if (brighter)
- return INTENSE_GREEN;
- else
- return GREEN;
- case 33:
- case 43:
- if (brighter)
- return INTENSE_YELLOW;
- else
- return YELLOW;
- case 34:
- case 44:
- if (brighter)
- return INTENSE_BLUE;
- else
- return BLUE;
- case 35:
- case 45:
- if (brighter)
- return INTENSE_MAGENTA;
- else
- return MAGENTA;
- case 36:
- case 46:
- if (brighter)
- return INTENSE_CYAN;
- else
- return CYAN;
- case 37:
- case 47:
- if (brighter)
- return INTENSE_WHITE;
- else
- return WHITE;
- default:
- return null;
- }
+ final Color[] colorSet = CODE2COLOR.get( code );
+ if ( null == colorSet )
+ {
+ return null;
+ }
+ return colorSet[brighter?0:1];
}
public static String getStripAnsiString(String newLineStr) {
List<TextStyle> styles = parseAnsiString(newLineStr);
diff --git a/org.tizen.common/src/org/tizen/common/console/ConsoleManager.java b/org.tizen.common/src/org/tizen/common/ui/view/console/ConsoleManager.java
index 455d7dd7f..2c41b34f8 100644
--- a/org.tizen.common/src/org/tizen/common/console/ConsoleManager.java
+++ b/org.tizen.common/src/org/tizen/common/ui/view/console/ConsoleManager.java
@@ -23,7 +23,7 @@
* - S-Core Co., Ltd
*
*/
-package org.tizen.common.console;
+package org.tizen.common.ui.view.console;
import java.io.IOException;
import java.lang.reflect.Method;
@@ -48,6 +48,7 @@ import org.eclipse.ui.console.MessageConsoleStream;
* @author GyeongSeok Seo {@literal <gyeongseok.seo@samsung.com>} (S-Core)
*/
public class ConsoleManager
+implements IConsolePrinter
{
private IConsoleManager consoleManager;
private String consoleName;
@@ -248,10 +249,10 @@ public class ConsoleManager
IConsoleView view = null;
try {
view = (IConsoleView) page.showView(id);
+ view.display(getConsole());
} catch (PartInitException e) {
ConsolePlugin.log(e);
}
- view.display(getConsole());
}
};
Display.getDefault().syncExec(runnable);
diff --git a/org.tizen.common/src/org/tizen/common/ui/view/console/ConsoleManager2.java b/org.tizen.common/src/org/tizen/common/ui/view/console/ConsoleManager2.java
new file mode 100644
index 000000000..d9fa7f7d4
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/ui/view/console/ConsoleManager2.java
@@ -0,0 +1,411 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* Yoonki Park <yoonki.park@samsung.com>
+* Kangho Kim <kh5325.kim@samsung.com>
+* BonYong Lee<bonyong.lee@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+package org.tizen.common.ui.view.console;
+
+import static org.tizen.common.util.SWTUtil.asyncExec;
+import static org.tizen.common.util.SWTUtil.getActivePage;
+import static org.tizen.common.util.SWTUtil.syncExec;
+import static org.tizen.common.util.IOUtil.tryClose;
+
+import org.eclipse.jface.text.IDocument;
+import org.eclipse.swt.graphics.Color;
+import org.eclipse.ui.IWorkbenchPage;
+import org.eclipse.ui.PartInitException;
+import org.eclipse.ui.console.ConsolePlugin;
+import org.eclipse.ui.console.IConsole;
+import org.eclipse.ui.console.IConsoleConstants;
+import org.eclipse.ui.console.IConsoleManager;
+import org.eclipse.ui.console.IConsoleView;
+import org.eclipse.ui.console.MessageConsoleStream;
+
+/**
+ * ConsoleManager2.
+ *
+ * {@link MessageConsole}'s delegater
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ */
+public class
+ConsoleManager2
+implements IConsolePrinter, IHyperlinkManager
+{
+
+ /**
+ * MessageConsole to be delegated
+ */
+ protected final MessageConsoleSpy console;
+
+ /**
+ * Link manager
+ */
+ protected final HyperlinkManager hyperlinkManager;
+
+ /**
+ * console's name
+ *
+ * @see {@link IConsole#setName(String)}
+ */
+ private String consoleName;
+
+ /**
+ * document model's virtual length
+ */
+ protected int documentLength = 0;
+
+ /**
+ * Constructs a new console manager.
+ *
+ * @param consoleName - the key title
+ * @param focus - true if focus on console, false if not
+ */
+ public
+ ConsoleManager2(
+ final String consoleName,
+ final boolean focus
+ )
+ {
+ this.console = createMessageConsole();
+ this.hyperlinkManager = new HyperlinkManager( console );
+ this.console.getDocument().addDocumentListener( hyperlinkManager );
+
+ if ( focus )
+ {
+ getConsoleManager().showConsoleView(console);
+ }
+
+ setName( consoleName );
+ }
+
+ /**
+ * return {@link IConsoleManager} from {@link ConsolePlugin}
+ *
+ * @return {@link IConsoleManager}
+ *
+ * @see ConsolePlugin#getConsoleManager()
+ */
+ protected IConsoleManager getConsoleManager()
+ {
+ return ConsolePlugin.getDefault().getConsoleManager();
+ }
+
+ /**
+ * return <code>IConsole</code>s to be attached to {@link IConsoleManager}
+ *
+ * @return <code>IConsole</code>s
+ *
+ * @see #getConsoleManager()
+ * @see IConsoleManager#getConsoles()
+ */
+ protected IConsole[] getConsoles()
+ {
+ return getConsoleManager().getConsoles();
+ }
+
+
+ /**
+ * Change Console Name.
+ *
+ * @param newName - console Title. It shown console's tab bar.
+ * @author Gyeongseok.seo@samsung.com
+ */
+ public void
+ setName(
+ final String newName
+ )
+ {
+ if ( null == newName )
+ {
+ throw new NullPointerException();
+ }
+ this.consoleName = newName;
+ asyncExec( new Runnable()
+ {
+ public void run()
+ {
+ if ( null == console )
+ {
+ return ;
+ }
+ console.setName(newName);
+ }
+ } );
+ }
+
+ /**
+ * Create message console
+ *
+ * @return Message console for emulator
+ */
+ synchronized protected MessageConsoleSpy createMessageConsole()
+ {
+ // Delete Old Console from console view
+ final IConsole[] consoles = getConsoles();
+ for ( int i = 0, n = consoles.length ; i < n ; ++i )
+ {
+ if ( !this.consoleName.equals(consoles[i].getName() ) )
+ {
+ continue;
+ }
+ getConsoleManager().removeConsoles( new IConsole[] { console } );
+ }
+
+ final MessageConsoleSpy console = new MessageConsoleSpy( this.consoleName );
+ getConsoleManager().addConsoles( new IConsole[] { console } );
+
+ return console;
+ }
+
+ /**
+ * return {@link IConsole}
+ *
+ * @return {@link IConsole} to be managed
+ */
+ protected IConsole getConsole() {
+ return this.console;
+ }
+
+ /**
+ * print <code>line</code> out to {@link IConsole} with line separator
+ *
+ * @param line text to print
+ */
+ synchronized public void println(String line) {
+ final MessageConsoleStream output = createConsoleStream();
+
+ try
+ {
+ output.println( line );
+ documentLength += ( line.length() + 1 );
+
+ } finally
+ {
+ tryClose( output );
+ }
+ }
+
+ /**
+ * Print out using {@link Process}
+ * @param process
+ */
+ public void printProcessStreams( final Process process) {
+
+ clear();
+ // waitAndRead while process is running
+ ConsoleProcessClosure closure = new ConsoleProcessClosure(process, this);
+
+ closure.runBlocking(); // a blocking cal
+ }
+
+
+ /**
+ * Return configured <code>MessageConsoleStream</code>
+ *
+ * with <code>fontStyle</code> and <code>color</code>
+ *
+ * @param fontStyle SWT font style like {@link SWT#BOLD}, {@link SWT#ITALIC}, and etc.
+ * @param color color of message to be printed
+ *
+ * @return configured <code>MessageConsoleStream</code>
+ *
+ * @see #configureConsole(MessageConsoleStream, int, Color)
+ */
+ protected
+ MessageConsoleStream
+ getConsoleStream(
+ final int fontStyle,
+ final Color color
+ )
+ {
+ final MessageConsoleStream stream = createConsoleStream();
+
+ configureConsole( stream, fontStyle, color );
+
+ return stream;
+ }
+
+
+ /**
+ * Factory method for <code>MessageConsoleStream</code>
+ *
+ * @return <code>MessageConsoleStream</code> to be created
+ *
+ * @see MessageConsole#newMessageStream()
+ */
+ protected
+ MessageConsoleStream
+ createConsoleStream()
+ {
+ final MessageConsoleStream stream = console.newMessageStream();
+
+ return stream;
+ }
+
+ /**
+ * Configure <code>stream</code> with <code>fontStyle</code> and <code>color</code>
+ *
+ * @param stream <code>MessageConsoleStream</code> to configure
+ * @param fontStyle SWT font style
+ * @param color
+ *
+ * @see SWT#NORMAL
+ * @see SWT#BOLD
+ * @see SWT#ITALIC
+ */
+ protected void
+ configureConsole(
+ final MessageConsoleStream stream,
+ final int fontStyle,
+ final Color color
+ )
+ {
+ syncExec( new Runnable()
+ {
+ public void run()
+ {
+ // font setting
+ stream.setFontStyle( fontStyle );
+
+ // color setting
+ stream.setColor( color );
+ }
+ } );
+ }
+
+ /**
+ * print out <code>message</code> with <code>fontStyle</code> and <code>color</code>
+ *
+ * @param message message to print out
+ * @param fontStyle SWT font style
+ * @param color color of message
+ */
+ synchronized public
+ void
+ print(
+ final String message,
+ final int fontStyle,
+ final Color color
+ )
+ {
+ final MessageConsoleStream stream = getConsoleStream( fontStyle, color );
+ try
+ {
+ stream.print(message);
+ documentLength += (message.length() );
+ }
+ finally
+ {
+ tryClose( stream );
+ }
+ }
+
+ /**
+ * print out with line separator
+ *
+ * @param message message to print out
+ * @param fontStyle font style
+ * @param color color
+ *
+ * @see #print(String, int, Color)
+ */
+ public
+ void
+ println(
+ final String message,
+ final int fontStyle,
+ final Color color
+ )
+ {
+ print( message + "\n", fontStyle, color );
+ }
+
+ /**
+ * clear message console
+ */
+ synchronized public
+ void
+ clear()
+ {
+ syncExec(
+ new Runnable() {
+ public void run() {
+ IDocument document = console.getDocument();
+ if ( null == document )
+ {
+ return ;
+ }
+ document.set("");
+ }
+ }
+ );
+ documentLength = 0;
+ }
+
+ /**
+ * Activate console
+ */
+ public
+ void
+ show()
+ {
+ syncExec(
+ new Runnable() {
+ public void run() {
+ final IWorkbenchPage page = getActivePage();
+ if ( null == page )
+ {
+ // How to handle no active page( no view page )
+ throw new IllegalStateException();
+ }
+ try {
+ IConsoleView view = (IConsoleView) page.showView( IConsoleConstants.ID_CONSOLE_VIEW );
+ view.display(getConsole());
+ } catch (
+ final PartInitException e
+ )
+ {
+ ConsolePlugin.log(e);
+ }
+ }
+ }
+ );
+ }
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.console.IHyperlinkerManager#addLinker(org.tizen.common.console.LinkInfo)
+ */
+ @Override
+ public
+ void
+ addLinker(
+ final LinkInfo link
+ )
+ {
+ hyperlinkManager.addLinker( link );
+ }
+
+}
+
diff --git a/org.tizen.common/src/org/tizen/common/console/ConsoleProcessClosure.java b/org.tizen.common/src/org/tizen/common/ui/view/console/ConsoleProcessClosure.java
index a9fa6ed0f..c82224da6 100644
--- a/org.tizen.common/src/org/tizen/common/console/ConsoleProcessClosure.java
+++ b/org.tizen.common/src/org/tizen/common/ui/view/console/ConsoleProcessClosure.java
@@ -23,9 +23,12 @@
* - S-Core Co., Ltd
*
*/
-package org.tizen.common.console;
+package org.tizen.common.ui.view.console;
+
+import static org.tizen.common.util.IOUtil.tryClose;
import java.io.BufferedReader;
+import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
@@ -44,16 +47,18 @@ public class ConsoleProcessClosure {
* Thread which continuously reads from a input stream and pushes the read
* data to an output stream which is immediately flushed afterwards.
*/
- protected static class ReaderThread extends Thread {
+ protected static class ReaderThread
+ extends Thread
+ implements Closeable {
private InputStream fInputStream;
- private ConsoleManager fConsole;
+ private IConsolePrinter fConsole;
private boolean fFinished = false;
private String lineSeparator;
/*
* outputStream can be null
*/
- public ReaderThread(ThreadGroup group, String name, InputStream in, ConsoleManager out) {
+ public ReaderThread(ThreadGroup group, String name, InputStream in, IConsolePrinter out) {
super(group, name);
fConsole = out;
fInputStream = in;
@@ -82,11 +87,7 @@ public class ConsoleProcessClosure {
} catch (IOException x) {
// ignore
} finally {
- try {
- fInputStream.close();
- } catch (IOException e) {
- // ignore
- }
+ tryClose( fInputStream );
}
} finally {
complete();
@@ -124,7 +125,7 @@ public class ConsoleProcessClosure {
protected static int fCounter = 0;
protected Process fProcess;
- protected ConsoleManager fConsole;
+ protected IConsolePrinter fConsole;
protected ReaderThread fOutputReader;
protected ReaderThread fErrorReader;
@@ -140,7 +141,7 @@ public class ConsoleProcessClosure {
* prcess stderr is written to this stream. Can be
* <code>null</code>, if not interested in reading the output
*/
- public ConsoleProcessClosure(Process process, ConsoleManager console) {
+ public ConsoleProcessClosure(Process process, IConsolePrinter console) {
fProcess = process;
fConsole = console;
}
@@ -189,8 +190,7 @@ public class ConsoleProcessClosure {
fErrorReader.waitFor();
}
- fOutputReader.close();
- fErrorReader.close();
+ tryClose( fOutputReader, fErrorReader );
// it seems that thread termination and stream closing is working
// without
// any help
@@ -205,10 +205,7 @@ public class ConsoleProcessClosure {
return true;
}
fProcess = null;
- fOutputReader.close();
- fErrorReader.close();
- fOutputReader = null;
- fErrorReader = null;
+ tryClose( fOutputReader, fErrorReader );
}
return false;
}
@@ -241,10 +238,7 @@ public class ConsoleProcessClosure {
if (!fErrorReader.finished()) {
fErrorReader.waitFor();
}
- fOutputReader.close();
- fErrorReader.close();
- fOutputReader = null;
- fErrorReader = null;
+ tryClose( fOutputReader, fErrorReader );
}
}
diff --git a/org.tizen.common/src/org/tizen/common/ui/view/console/HyperlinkManager.java b/org.tizen.common/src/org/tizen/common/ui/view/console/HyperlinkManager.java
new file mode 100644
index 000000000..be32de9b1
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/ui/view/console/HyperlinkManager.java
@@ -0,0 +1,131 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* BonYong Lee <bonyong.lee@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+package org.tizen.common.ui.view.console;
+
+import java.util.Iterator;
+import java.util.TreeSet;
+
+import org.eclipse.jface.text.BadLocationException;
+import org.eclipse.jface.text.DocumentEvent;
+import org.eclipse.jface.text.IDocument;
+import org.eclipse.jface.text.IDocumentListener;
+import org.eclipse.ui.console.TextConsole;
+
+/**
+ * HyperlinkManager.
+ *
+ * Manage hyperlink.
+ *
+ * process deferedly because {@link TextConsole} is asynchronous.
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ */
+public class
+HyperlinkManager
+implements IHyperlinkManager, IDocumentListener
+{
+ /**
+ * {@link TextConsole} to connect link
+ */
+ protected TextConsole console;
+
+ /**
+ * unconnected links
+ */
+ protected final TreeSet<LinkInfo> dangledLinks = new TreeSet<LinkInfo>();
+
+ /**
+ * Constructor with {@link TextConsole} to connect link
+ *
+ * @param console {@link TextConsole} to connect link
+ */
+ public
+ HyperlinkManager(
+ final TextConsole console
+ )
+ {
+ this.console = console;
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.jface.text.IDocumentListener#documentAboutToBeChanged(org.eclipse.jface.text.DocumentEvent)
+ */
+ @Override
+ public
+ void
+ documentAboutToBeChanged(
+ final DocumentEvent event
+ )
+ {
+ // Not implement
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.jface.text.IDocumentListener#documentChanged(org.eclipse.jface.text.DocumentEvent)
+ */
+ @Override
+ public
+ void
+ documentChanged(
+ final DocumentEvent event
+ )
+ {
+ final IDocument doc = event.getDocument();
+ final int docLen = doc.getLength();
+
+ for ( final Iterator<LinkInfo> iter = dangledLinks.iterator() ; iter.hasNext() ; )
+ {
+ final LinkInfo info = iter.next();
+
+ if ( docLen < info.getEnd() )
+ {
+ return ;
+ }
+
+ try
+ {
+ this.console.addHyperlink( info.getLink(), info.getStart(), info.getLength() );
+ iter.remove();
+ } catch ( final BadLocationException e )
+ {
+ e.printStackTrace();
+ }
+ }
+ }
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.console.IHyperlinkerManager#addLinker(org.tizen.common.console.LinkInfo)
+ */
+ @Override
+ public
+ void
+ addLinker(
+ final LinkInfo link
+ )
+ {
+ dangledLinks.add( link );
+ }
+
+}
diff --git a/org.tizen.common/src/org/tizen/common/ui/view/console/IConsolePrinter.java b/org.tizen.common/src/org/tizen/common/ui/view/console/IConsolePrinter.java
new file mode 100644
index 000000000..efa154ac7
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/ui/view/console/IConsolePrinter.java
@@ -0,0 +1,46 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* BonYong Lee <bonyong.lee@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+package org.tizen.common.ui.view.console;
+
+import org.eclipse.swt.graphics.Color;
+
+/**
+ * IConsolePrinter.
+ *
+ * {@link IConsoleManager}'s adaptation interface
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ */
+public interface IConsolePrinter
+{
+ /**
+ * print line out to {@link IConsole}
+ *
+ * @param msg message to print out
+ * @param fontStyle font style flag
+ * @param color foreground color of <code>msg</code> to print out
+ */
+ void print( String msg, int fontStyle, Color color );
+}
diff --git a/org.tizen.common/src/org/tizen/common/model/ITableVO.java b/org.tizen.common/src/org/tizen/common/ui/view/console/IHyperlinkManager.java
index e8a4592f3..68d995e6f 100644
--- a/org.tizen.common/src/org/tizen/common/model/ITableVO.java
+++ b/org.tizen.common/src/org/tizen/common/ui/view/console/IHyperlinkManager.java
@@ -1,35 +1,46 @@
-/*
-* Common
-*
-* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
-*
-* Contact:
-* Kangho Kim <kh5325.kim@samsung.com>
-*
-* 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.
-*
-* Contributors:
-* - S-Core Co., Ltd
-*
-*/
-
-package org.tizen.common.model;
-
-public interface ITableVO extends IVO{
- public String[] getColumnNames();
- public Object getColumnValue(int index);
- public Object getColumnValue(String columnName);
- public int getColumnIndex(String columnName);
- public String getColumnName(int index);
- public void setColumnValue(int index, Object value);
-}
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* BonYong Lee <bonyong.lee@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+package org.tizen.common.ui.view.console;
+
+
+/**
+ * IHyperlinkerManager.
+ *
+ * Manage hyperlinks in asynchronous stream
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ */
+public interface
+IHyperlinkManager
+{
+ /**
+ * add <code>link</code> to IConsole
+ *
+ * @param link hyper link's info
+ *
+ * @see LinkInfo
+ */
+ void addLinker( LinkInfo link );
+}
diff --git a/org.tizen.common/src/org/tizen/common/ui/view/console/LinkInfo.java b/org.tizen.common/src/org/tizen/common/ui/view/console/LinkInfo.java
new file mode 100644
index 000000000..9eb0bbcaa
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/ui/view/console/LinkInfo.java
@@ -0,0 +1,151 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* BonYong Lee <bonyong.lee@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+package org.tizen.common.ui.view.console;
+
+import org.eclipse.ui.console.IHyperlink;
+
+/**
+ * LinkInfo.
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ */
+public class
+LinkInfo
+implements Comparable<LinkInfo>
+{
+ /**
+ * Link's start offset
+ */
+ protected final int offset;
+
+ /**
+ * Link's textual length
+ */
+ protected final int length;
+
+ /**
+ * <code>IHyperlink</code> to connect
+ */
+ protected final IHyperlink link;
+
+ /**
+ * Constructor with link's offset, length and hyperlink
+ *
+ * @param offset link's start offset
+ * @param length link's length
+ * @param link hyperlink
+ */
+ public LinkInfo(
+ final int offset,
+ final int length,
+ final IHyperlink link
+ )
+ {
+ this.offset = offset;
+ this.length = length;
+ this.link = link;
+ if ( length < 0 )
+ {
+ throw new IllegalArgumentException( "Link's length is negative :" + this );
+ }
+ }
+
+ /**
+ * Return link's start position in text
+ *
+ * @return link's start position
+ *
+ * @see #getEnd()
+ * @see #getLength()
+ */
+ public
+ int
+ getStart()
+ {
+ return this.offset;
+ }
+
+ /**
+ * Return link's end position in text
+ *
+ * @return link's end position
+ *
+ * @see #getStart()
+ * @see #getEnd()
+ */
+ public
+ int
+ getEnd()
+ {
+ return getStart() + getLength();
+ }
+
+ /**
+ * Return link's length
+ *
+ * @return link's length
+ *
+ * @see #getStart();
+ * @see #getEnd();
+ */
+ public
+ int
+ getLength()
+ {
+ return this.length;
+ }
+
+ /**
+ * return hyper link
+ * @return {@link IHyperlink}
+ */
+ public
+ IHyperlink
+ getLink()
+ {
+ return this.link;
+ }
+
+ /* (non-Javadoc)
+ * @see java.lang.Comparable#compareTo(java.lang.Object)
+ */
+ @Override
+ public
+ int
+ compareTo(LinkInfo o)
+ {
+ return getLength() - o.getLength();
+ }
+
+ /* (non-Javadoc)
+ * @see java.lang.Object#toString()
+ */
+ @Override
+ public
+ String
+ toString()
+ {
+ return "Link(" + getStart() + ":" + getEnd() + ")-" + link;
+ }
+}
diff --git a/org.tizen.common/src/org/tizen/common/ui/view/console/MessageConsoleSpy.java b/org.tizen.common/src/org/tizen/common/ui/view/console/MessageConsoleSpy.java
new file mode 100644
index 000000000..1a1a7dfd6
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/ui/view/console/MessageConsoleSpy.java
@@ -0,0 +1,55 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* BonYong Lee <bonyong.lee@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+package org.tizen.common.ui.view.console;
+
+import org.eclipse.ui.console.MessageConsole;
+
+public class
+MessageConsoleSpy
+extends MessageConsole
+{
+
+ /**
+ * Constructor with console name
+ *
+ * @param name console's key title
+ */
+ public MessageConsoleSpy( final String name )
+ {
+ super( name, null );
+ }
+
+ /**
+ * make {@link AbstractConsole#setName(String)} accessible
+ *
+ * @see org.eclipse.ui.console.AbstractConsole#setName(java.lang.String)
+ */
+ public void setName( final String name )
+ {
+ super.setName( name );
+ }
+
+
+}
diff --git a/org.tizen.common/src/org/tizen/common/console/TextStyle.java b/org.tizen.common/src/org/tizen/common/ui/view/console/TextStyle.java
index d068ef8bf..000c1b0ab 100644
--- a/org.tizen.common/src/org/tizen/common/console/TextStyle.java
+++ b/org.tizen.common/src/org/tizen/common/ui/view/console/TextStyle.java
@@ -23,7 +23,7 @@
* - S-Core Co., Ltd
*
*/
-package org.tizen.common.console;
+package org.tizen.common.ui.view.console;
import org.eclipse.swt.graphics.Color;
diff --git a/org.tizen.common/src/org/tizen/common/swt/PictureLabel.java b/org.tizen.common/src/org/tizen/common/ui/widget/PictureLabel.java
index 1cda75f87..c56ed6292 100644
--- a/org.tizen.common/src/org/tizen/common/swt/PictureLabel.java
+++ b/org.tizen.common/src/org/tizen/common/ui/widget/PictureLabel.java
@@ -23,7 +23,7 @@
*
*/
-package org.tizen.common.swt;
+package org.tizen.common.ui.widget;
import java.util.List;
import java.util.ArrayList;
@@ -191,6 +191,9 @@ public class PictureLabel extends Canvas {
}
class ImageClickedEvent extends java.util.EventObject {
+
+ private static final long serialVersionUID = 2923125560667763769L;
+
public int x, y;
public ImageClickedEvent(Object source, int x, int y) {
diff --git a/org.tizen.common/src/org/tizen/common/update/UpdateMessages.properties b/org.tizen.common/src/org/tizen/common/update/UpdateMessages.properties
deleted file mode 100644
index 06a30a973..000000000
--- a/org.tizen.common/src/org/tizen/common/update/UpdateMessages.properties
+++ /dev/null
@@ -1,3 +0,0 @@
-##
-message.dialogTitle = Tizen SDK
-message.askForUpdate = Updates are available for Tizen SDK. Do you want to install them? \ No newline at end of file
diff --git a/org.tizen.common/src/org/tizen/common/util/ArrayUtil.java b/org.tizen.common/src/org/tizen/common/util/ArrayUtil.java
new file mode 100755
index 000000000..ee1a5715d
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/util/ArrayUtil.java
@@ -0,0 +1,1124 @@
+/*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common.util;
+
+import java.lang.reflect.Array;
+import java.lang.reflect.InvocationTargetException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.ConcurrentModificationException;
+import java.util.Iterator;
+import java.util.NoSuchElementException;
+
+/**
+ * ArrayUtil.
+ *
+ * Helper related to array
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ */
+public class ArrayUtil
+{
+ /**
+ * Empty {@link Object} array
+ */
+ public static final Object[] EMPTY_OBJECT_ARRAY = new Object[0];
+
+
+ /**
+ * <p>
+ * check <code>collection</code> has no element.
+ *
+ * use without null check.
+ *
+ * Old style
+ *
+ * <pre>
+ * Object[] array = null;
+ * ...
+ * if ( null != array && 0 < array.length ) {
+ * ...
+ * }
+ * </pre>
+ *
+ * Usage :
+ * <p>
+ *
+ * <pre>
+ * Object[] array = null;
+ * ...
+ * if ( !ArrayUtil.isEmpty( array ) ) {
+ * ...
+ * }
+ * </pre>
+ *
+ * or "import static" style if you use JDK6
+ *
+ * </pre>
+ * import static org.tizen.common.util.CollectionUtil.isEmpty;
+ * ...
+ *
+ * Object[] array = null;
+ * ...
+ * if ( !isEmpty( array ) ) {
+ * ...
+ * }
+ * </pre>
+ *
+ * @param array {@link Collection} to check
+ *
+ * @return value if collection is empty
+ */
+ public static <T>
+ boolean
+ isEmpty(
+ final T[] array
+ )
+ {
+ if ( null == array )
+ {
+ return true;
+ }
+
+ return (0 == array.length);
+ }
+
+ /**
+ * <p>
+ * Return first element in <code>array</code><br>
+ *
+ * Return <code>null</code> if <code>array</code> is null or empty
+ * </p>
+ *
+ * @param <T> type of element in <code>array</code>
+ * @param array object array to check
+ *
+ * @return first elemtn in <code>array</code>
+ */
+ public static <T>
+ T
+ pickupFirst( T[] array )
+ {
+ if ( isEmpty( array ) )
+ {
+ return null;
+ }
+
+ return array[0];
+ }
+
+ /**
+ * <p>
+ * Return last element in <code>array</code><br>
+ *
+ * Return <code>null</code> if <code>array</code> is null or empty
+ * </p>
+ *
+ * @param <T> type of element in <code>array</code>
+ * @param array object array to check
+ *
+ * @return last elemtn in <code>array</code>
+ */
+ public static <T>
+ T
+ pickupLast( T[] array )
+ {
+ if ( isEmpty( array ) )
+ {
+ return null;
+ }
+
+ return array[array.length - 1];
+ }
+
+ /**
+ * Create array with <code>length</code>
+ *
+ * @param <T> type of element in array to create
+ * @param type {@link Class}
+ * @param length array size
+ *
+ * @return created array
+ */
+ @SuppressWarnings("unchecked")
+ public static <T>
+ T[] newArray( Class<? extends T> type, int length)
+ {
+ return (T[]) Array.newInstance( type, length);
+ }
+
+ /**
+ * {@link Iterator} for array
+ *
+ * @param <K> element type in array
+ */
+ public static class
+ ArrayIterator<K>
+ implements Iterator<K>
+ {
+ /**
+ * cloned array
+ */
+ protected final K[] objs;
+
+ /**
+ * original array
+ */
+ protected final K[] origin;
+
+ /**
+ * current element index
+ */
+ protected int index = 0;
+
+ /**
+ * Constructor with array
+ *
+ * @param objs array to iterate
+ */
+ public
+ ArrayIterator(
+ final K[] objs
+ )
+ {
+ this.origin = objs;
+
+ this.objs = ( null == origin )?null:origin.clone();
+ }
+
+ /* (non-Javadoc)
+ * @see java.util.Iterator#hasNext()
+ */
+ @Override
+ public
+ boolean
+ hasNext()
+ {
+ if ( null == this.objs )
+ {
+ return false;
+ }
+ return ( index < this.objs.length );
+ }
+
+ /* (non-Javadoc)
+ * @see java.util.Iterator#next()
+ */
+ @Override
+ public
+ K
+ next()
+ {
+ if ( null == this.objs )
+ {
+ throw new NoSuchElementException();
+ }
+ if ( this.objs.length <= index )
+ {
+ throw new NoSuchElementException();
+ }
+
+ if ( objs[index] != origin[index] ) {
+ throw new ConcurrentModificationException();
+ }
+ return this.objs[index++];
+ }
+
+ /* (non-Javadoc)
+ * @see java.util.Iterator#remove()
+ */
+ @Override
+ public
+ void
+ remove()
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ }
+
+ /**
+ * Create and return {@link Iterator} for <code>array</code>
+ *
+ * @param <T> iteraing element's type
+ * @param array array to iterate
+ *
+ * @return {@link Iterator} for <code>array</code>
+ */
+ public static <T> Iterator<T> iterator( final T[] array )
+ {
+ return new ArrayIterator<T>( array );
+ }
+
+ /**
+ * <p>
+ * run <code>runner</code> iterateing element of <code>array</code>.
+ *
+ * use without null-check for <code>array</code>
+ *
+ * delegate error handling to <code>array</code>
+ * </p>
+ *
+ * <pre>
+ *
+ * ArrayUtil.iterate(
+ * Arrays.asList( "hello", "Hello", "World", null, "Test" ),
+ * new IteratingRunner<String>() {
+ * public void run( String arg ) {
+ * ...
+ * }
+ * }
+ * );
+ *
+ * </pre>
+ *
+ * @param <T> type of element in <code>array</code>
+ * @param array array containing element
+ * @param runner {@link Runnable} to execute
+ *
+ * @throws InvocationTargetException when <code>runner</code>'s {@link Runnable#run()} throws exception
+ *
+ * @see {@link #iterate(Object[], IteratingRunner, boolean)}
+ * @see FilterIterator
+ */
+ public static <T>
+ void
+ iterate(
+ final T[] array,
+ final IteratingRunner<T> runner
+ )
+ {
+ try
+ {
+ iterate( array, runner, true );
+ } catch ( final InvocationTargetException e)
+ {
+ // Be never reached
+ throw new IllegalStateException( e );
+ }
+ }
+
+ /**
+ * <p>
+ * run <code>runner</code> iterateing element of <code>array</code>.
+ *
+ * use without null-check for <code>array</code>
+ *
+ * delegate error handling to <code>runner</code>
+ *
+ * </p>
+ * <pre>
+ *
+ * ArrayUtil.iterate(
+ * Arrays.asList( "hello", "Hello", "World", null, "Test" ),
+ * new IteratingRunner<String>() {
+ * public void run( String arg ) {
+ * ...
+ * }
+ * },
+ * true
+ * );
+ *
+ * </pre>
+ *
+ * @param <T> type of element in <code>array</code>
+ * @param array array containing element
+ * @param runner {@link Runnable} to execute
+ * @param bForceProcess flag to iterate continuously when exception occurs
+ *
+ * @throws InvocationTargetException when <code>runner</code>'s {@link Runnable#run()} throws exception
+ *
+ * @see FilterIterator
+ */
+ public static <T>
+ void
+ iterate(
+ final T[] array,
+ final IteratingRunner<T> runner,
+ final boolean bForceProcess
+ )
+ throws InvocationTargetException
+ {
+ if ( null == runner )
+ {
+ return ;
+ }
+
+ for ( final T arg : safe( array ) )
+ {
+ if ( null == arg && !bForceProcess )
+ {
+ continue ;
+ }
+ try
+ {
+ runner.run( arg );
+ } catch ( Throwable e )
+ {
+ if ( !bForceProcess )
+ {
+ throw new InvocationTargetException( e );
+ }
+ }
+ }
+ }
+
+ /**
+ * <p>
+ * Fiter <code>array</code> and return filtered array
+ *
+ * Ignore exception in filtering logic
+ * </p>
+ *
+ * @param <T> type of element in <code>array</code>
+ * @param array array to filter
+ * @param runner object to determine if filter
+ */
+ public static <T>
+ T[]
+ filter(
+ final T[] array,
+ final IteratingAcceptor<T> runner
+ )
+ {
+ try
+ {
+ return filter( array, runner, true );
+ } catch ( final InvocationTargetException e )
+ {
+ // Be never reached
+ throw new IllegalStateException( e );
+ }
+ }
+ /**
+ * <p>
+ * Fiter <code>array</code> and return filtered array
+ *
+ * determined if stop or keep going using <code>bForceProcess</code> in case of exception.
+ * </p>
+ *
+ * @param <T> type of element in <code>array</code>
+ * @param array array to filter
+ * @param runner object to determine if filter
+ * @param bForceProcess flag to keep going when exception occurs
+ *
+ * @throws InvocationTargetException when <code>runner</code>'s {@link IteratingAcceptor#accept(Object)} throws exception
+ */
+ @SuppressWarnings("unchecked")
+ public static <T>
+ T[]
+ filter(
+ final T[] array,
+ final IteratingAcceptor<T> runner,
+ final boolean bForceProcess
+ ) throws InvocationTargetException
+ {
+ final ArrayList<T> list = new ArrayList<T>();
+
+ for ( final T arg : safe( array ) )
+ {
+ if ( null == arg && !bForceProcess )
+ {
+ continue ;
+ }
+ try
+ {
+ if ( runner.accept( arg ) )
+ {
+ list.add( arg );
+ }
+ } catch ( Throwable e )
+ {
+ if ( !bForceProcess )
+ {
+ throw new InvocationTargetException( e );
+ }
+ }
+
+ }
+
+ return (T[]) list.toArray( newArray( array.getClass().getComponentType(), list.size() ) );
+ }
+
+
+ /**
+ * Convert <code>source</code> to {@link Object[]}
+ *
+ * throw {@link IllegalArgumentException} if source is not array type
+ *
+ * @param source object to convert
+ *
+ * @return object to converted
+ */
+ public static
+ Object[]
+ toObjectArray(
+ final Object source
+ )
+ {
+ if ( source instanceof Object[] )
+ {
+ return ( Object[] )source;
+ }
+
+ if ( null == source )
+ {
+ return EMPTY_OBJECT_ARRAY;
+ }
+
+ if ( !source.getClass().isArray() )
+ {
+ throw new IllegalArgumentException( "source must be an array");
+ }
+
+ final int length = Array.getLength( source );
+ if ( 0 == length )
+ {
+ return EMPTY_OBJECT_ARRAY;
+ }
+
+ Class<?> wrapperType = null;
+ for ( int i = 0 ; null == wrapperType && i < length ; ++i )
+ {
+ Object obj = Array.get( source, 0 );
+ if ( null == obj )
+ {
+ continue;
+ }
+ wrapperType = obj.getClass();
+ }
+ if ( null == wrapperType )
+ {
+ return (Object[]) source;
+ }
+
+ final Object[] newArray =
+ (Object[]) Array.newInstance( wrapperType, length );
+ for( int i=0 ; i<length ; ++i )
+ {
+ newArray[i] = Array.get( source, i );
+ }
+
+ return newArray;
+ }
+
+ /**
+ * Return size if object is array or {@link Collection}
+ *
+ * Return <code>0</code> in case of the other type
+ *
+ * @param obj object to check
+ *
+ * @return size
+ */
+ public static
+ int
+ size(
+ final Object obj
+ )
+ {
+ if ( obj instanceof Object[] )
+ {
+ return size( ( Object[] ) obj );
+ }
+ else if ( obj instanceof boolean[] )
+ {
+ return size( ( boolean[] ) obj );
+ }
+ else if ( obj instanceof byte[] )
+ {
+ return size( ( byte[] )obj );
+ }
+ else if ( obj instanceof char[] )
+ {
+ return size( ( char[] ) obj );
+ }
+ else if ( obj instanceof short[] )
+ {
+ return size( ( short[] )obj );
+ }
+ else if ( obj instanceof int[] )
+ {
+ return size( (int[] ) obj );
+ }
+ else if ( obj instanceof long[] )
+ {
+ return size( ( long[] ) obj );
+ }
+ else if ( obj instanceof float[] )
+ {
+ return size( (float[] ) obj );
+ }
+ else if ( obj instanceof double[] )
+ {
+ return size( ( double[] ) obj );
+ }
+ else if ( obj instanceof Collection )
+ {
+ return CollectionUtil.size( (Collection<?>) obj );
+ }
+ return 0;
+
+ }
+
+ /**
+ * Return <code>objs</code>'s length
+ *
+ * Return 0 if <code>objs</code> is null.
+ *
+ * @param objs boolean array object
+ *
+ * @return size of array
+ */
+ public static
+ int
+ size(
+ final boolean[] objs
+ ) {
+ if ( null == objs )
+ {
+ return 0;
+ }
+ return objs.length;
+ }
+
+ /**
+ * Return <code>objs</code>'s length
+ *
+ * Return 0 if <code>objs</code> is null.
+ *
+ * @param objs byte array object
+ *
+ * @return size of array
+ */
+ public static
+ int
+ size(
+ final byte[] objs
+ ) {
+ if ( null == objs )
+ {
+ return 0;
+ }
+ return objs.length;
+ }
+
+
+ /**
+ * Return <code>objs</code>'s length
+ *
+ * Return 0 if <code>objs</code> is null.
+ *
+ * @param objs char array object
+ *
+ * @return size of array
+ */
+ public static
+ int
+ size(
+ final char[] objs
+ ) {
+ if ( null == objs )
+ {
+ return 0;
+ }
+ return objs.length;
+ }
+
+ /**
+ * Return <code>objs</code>'s length
+ *
+ * Return 0 if <code>objs</code> is null.
+ *
+ * @param objs short array object
+ *
+ * @return size of array
+ */
+ public static
+ int
+ size(
+ final short[] objs
+ ) {
+ if ( null == objs )
+ {
+ return 0;
+ }
+ return objs.length;
+ }
+
+ /**
+ * Return <code>objs</code>'s length
+ *
+ * Return 0 if <code>objs</code> is null.
+ *
+ * @param objs int array object
+ *
+ * @return size of array
+ */
+ public static
+ int
+ size(
+ final int[] objs
+ ) {
+ if ( null == objs )
+ {
+ return 0;
+ }
+ return objs.length;
+ }
+
+ /**
+ * Return <code>objs</code>'s length
+ *
+ * Return 0 if <code>objs</code> is null.
+ *
+ * @param objs long array object
+ *
+ * @return size of array
+ */
+ public static
+ int
+ size(
+ final long[] objs
+ ) {
+ if ( null == objs )
+ {
+ return 0;
+ }
+ return objs.length;
+ }
+
+ /**
+ * Return <code>objs</code>'s length
+ *
+ * Return 0 if <code>objs</code> is null.
+ *
+ * @param objs float array object
+ *
+ * @return size of array
+ */
+ public static
+ int
+ size(
+ final float[] objs
+ ) {
+ if ( null == objs )
+ {
+ return 0;
+ }
+ return objs.length;
+ }
+
+ /**
+ * Return <code>objs</code>'s length
+ *
+ * Return 0 if <code>objs</code> is null.
+ *
+ * @param objs double array object
+ *
+ * @return size of array
+ */
+ public static
+ int
+ size(
+ final double[] objs
+ ) {
+ if ( null == objs )
+ {
+ return 0;
+ }
+ return objs.length;
+ }
+
+ /**
+ * Return <code>objs</code>'s length
+ *
+ * Return 0 if <code>objs</code> is null.
+ *
+ * @param <T> type of array
+ * @param objs T type array object
+ *
+ * @return size of array
+ */
+ public static <T>
+ int
+ size(
+ final T[] objs
+ ) {
+ if ( null == objs )
+ {
+ return 0;
+ }
+ return objs.length;
+ }
+
+ /**
+ * add <code>obj</code> to <code>array</code>
+ *
+ * Return array having only <code>obj</code> if <code>array</code> is <code>null</code>
+ *
+ * @param array array to add element
+ * @param obj new element to add
+ *
+ * @return added array
+ */
+ @SuppressWarnings("unchecked")
+ public static <T> T[]
+ add(
+ final T[] array,
+ final T obj
+ )
+ {
+ Class<?> compType = Object.class;
+ if ( null != array )
+ {
+ compType = array.getClass().getComponentType();
+ }
+ else if ( null != obj )
+ {
+ compType = obj.getClass();
+ }
+
+ final int newArrLength = size( array ) + 1;
+ final T[] newArr =
+ (T[]) Array.newInstance( compType, newArrLength );
+
+ if ( null != array )
+ {
+ System.arraycopy( array, 0, newArr, 0, array.length );
+ }
+ newArr[newArrLength - 1] = obj;
+ return newArr;
+ }
+
+ /**
+ * remove elements whose index is between <code>startIndex</code> and <code>endIndex</code>
+ *
+ * and return applied array
+ *
+ * @param <T> type of array element
+ * @param array array to remove elements
+ * @param startIndex start index of range to remove
+ * @param endIndex end index of range to remove
+ *
+ * @return change applied new array
+ *
+ * @throws ArrayIndexOutOfBoundsException
+ * if <code>startIndex</code> or <code>endIndex</code> is not in range of array
+ * @throws IllegalArgumentException
+ * if <code>startIndex</code> is greater than <code>endIndex</code>
+ */
+ @SuppressWarnings("unchecked")
+ public static <T> T[]
+ remove(
+ final Object[] array,
+ final int start,
+ final int end
+ )
+ {
+ if ( null == array )
+ {
+ throw new NullPointerException();
+ }
+ Assert.isTrue(
+ start <= end,
+ "start indnex(" + start + ") is greater than end index(" + end + ")"
+ );
+
+ int startIndex = Math.max( 0, start );
+ int endIndex = Math.min( array.length, end );
+ if ( endIndex <= startIndex )
+ {
+ return (T[]) array;
+ }
+
+ final Class<?> compType = array.getClass().getComponentType();
+
+ final int removeSize = endIndex - startIndex;
+
+ final int newArrLength = size( array ) - removeSize;
+
+ final Object[] newArr =
+ (Object[]) Array.newInstance( compType, newArrLength );
+
+ System.arraycopy( array, 0, newArr, 0, startIndex );
+ System.arraycopy( array, endIndex, newArr, startIndex, array.length-endIndex );
+
+ return (T[]) newArr;
+ }
+
+ /**
+ * remove elements whose index is <code>index</code>
+ *
+ * and return applied array
+ *
+ * @param <T> type of array element
+ * @param array array to remove elements
+ * @param index index to remove
+ *
+ * @return change applied new array
+ *
+ * @throws ArrayIndexOutOfBoundsException
+ * if <code>index</code> is not in range of array
+ */
+ public static <T> T[]
+ remove(
+ final Object[] array,
+ final int index
+ )
+ {
+ return remove( array, index, index + 1);
+ }
+
+ /**
+ * Check if <code>array</code> contains <code>element</code>
+ *
+ * @param array array to check
+ * @param element object to check
+ *
+ * @return <code>true</code> if <code>collection</code> contain <code>element</code>
+ */
+ public static <K, V>
+ boolean
+ contains(
+ final K[] array,
+ final V element
+ )
+ {
+ if ( null == array )
+ {
+ return false;
+ }
+
+ for ( final Object candidate : array )
+ {
+ if ( ObjectUtil.equals( candidate, element ) )
+ {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Return <code>index</code> th element in <code>collection</code>
+ *
+ * Return <code>null</code> if <code>index</code> is out of range
+ *
+ * @param <K> array type
+ * @param array array object to access
+ * @param index array index
+ * @return <code>index</code> th element in array
+ */
+ public static <K>
+ K
+ get(
+ final K[] array,
+ final int index
+ )
+ {
+ if ( null == array )
+ {
+ return null;
+ }
+ if ( index < 0 )
+ {
+ return null;
+ }
+ if ( array.length <= index )
+ {
+ return null;
+ }
+
+ return array[index];
+ }
+
+ /**
+ * Convert <code>array</code> to {@link Boolean[]}
+ *
+ * @param array array to convert
+ *
+ * @return converted array
+ */
+ public static Boolean[] convertToWrapper( final boolean[] array )
+ {
+ final int nArray = size( array );
+ final Boolean[] ret = new Boolean[nArray];
+
+ for ( int i = 0 ; i < nArray ; ++i )
+ {
+ ret[i] = array[i];
+ }
+
+ return ret;
+ }
+
+ /**
+ * Convert <code>array</code> to {@link Byte[]}
+ *
+ * @param array array to convert
+ *
+ * @return converted array
+ */
+ public static Byte[] convertToWrapper( final byte[] array )
+ {
+ final int nArray = size( array );
+ final Byte[] ret = new Byte[nArray];
+
+ for ( int i = 0 ; i < nArray ; ++i )
+ {
+ ret[i] = array[i];
+ }
+
+ return ret;
+ }
+
+ /**
+ * Convert <code>array</code> to {@link Character[]}
+ *
+ * @param array array to convert
+ *
+ * @return converted array
+ */
+ public static Character[] convertToWrapper( final char[] array )
+ {
+ final int nArray = size( array );
+ final Character[] ret = new Character[nArray];
+
+ for ( int i = 0 ; i < nArray ; ++i )
+ {
+ ret[i] = array[i];
+ }
+
+ return ret;
+ }
+
+
+ /**
+ * Convert <code>array</code> to {@link Short[]}
+ *
+ * @param array array to convert
+ *
+ * @return converted array
+ */
+ public static Short[] convertToWrapper( final short[] array )
+ {
+ final int nArray = size( array );
+ final Short[] ret = new Short[nArray];
+
+ for ( int i = 0 ; i < nArray ; ++i )
+ {
+ ret[i] = array[i];
+ }
+
+ return ret;
+ }
+
+ /**
+ * Convert <code>array</code> to {@link Integer[]}
+ *
+ * @param array array to convert
+ *
+ * @return converted array
+ */
+ public static Integer[] convertToWrapper( final int[] array )
+ {
+ final int nArray = size( array );
+ final Integer[] ret = new Integer[nArray];
+
+ for ( int i = 0 ; i < nArray ; ++i )
+ {
+ ret[i] = array[i];
+ }
+
+ return ret;
+ }
+
+ /**
+ * Convert <code>array</code> to {@link Long[]}
+ *
+ * @param array array to convert
+ *
+ * @return converted array
+ */
+ public static Long[] convertToWrapper( final long[] array )
+ {
+ final int nArray = size( array );
+ final Long[] ret = new Long[nArray];
+
+ for ( int i = 0 ; i < nArray ; ++i )
+ {
+ ret[i] = array[i];
+ }
+
+ return ret;
+ }
+
+ /**
+ * Convert <code>array</code> to {@link Float[]}
+ *
+ * @param array array to convert
+ *
+ * @return converted array
+ */
+ public static Float[] convertToWrapper( final float[] array )
+ {
+ final int nArray = size( array );
+ final Float[] ret = new Float[nArray];
+
+ for ( int i = 0 ; i < nArray ; ++i )
+ {
+ ret[i] = array[i];
+ }
+
+ return ret;
+ }
+
+ /**
+ * Convert <code>array</code> to {@link Double[]}
+ *
+ * @param array array to convert
+ *
+ * @return converted array
+ */
+ public static Double[] convertToWrapper( final double[] array )
+ {
+ final int nArray = size( array );
+ final Double[] ret = new Double[nArray];
+
+ for ( int i = 0 ; i < nArray ; ++i )
+ {
+ ret[i] = array[i];
+ }
+
+ return ret;
+ }
+
+ @SuppressWarnings("unchecked")
+ public static <T> T[] safe( T[] unsafe )
+ {
+ return (T[]) ObjectUtil.nvl( unsafe, EMPTY_OBJECT_ARRAY );
+ }
+}
diff --git a/org.tizen.common/src/org/tizen/common/util/Assert.java b/org.tizen.common/src/org/tizen/common/util/Assert.java
new file mode 100755
index 000000000..b9c4a0af7
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/util/Assert.java
@@ -0,0 +1,837 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* BonYong Lee <bonyong.lee@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+package org.tizen.common.util;
+
+import java.text.MessageFormat;
+import java.util.Collection;
+import java.util.Map;
+
+/**
+ * Assert
+ *
+ * Helper for assertion
+ *
+ * Assert following
+ * <ul>
+ * <li>boolean expression</li>
+ * <li>null object</li>
+ * <li>object equality</li>
+ * <li>string</li>
+ * <li>Collection</li>
+ * <li>Map</li>
+ * <li>object type</li>
+ * </ul>
+ */
+public class
+Assert
+{
+ protected Assert() { }
+
+ /**
+ * Encapsulated method in case of failure in assertion
+ *
+ * Throw {@link IllegalArgumentException} with <code>msg</code> message.
+ *
+ * @param msg exception's message to throw
+ */
+ public static
+ void
+ fail(
+ final Object msg
+ )
+ {
+ if ( msg instanceof String )
+ {
+ throw new IllegalArgumentException( (String) msg );
+ } else if ( null != msg )
+ {
+ throw new IllegalArgumentException( msg.toString() );
+ }
+ }
+
+ /**
+ * Assert that <code>exp</code> is <code>true</code>
+ *
+ * Throw {@link IllegalArgumentException} with <code>msg</code> message
+ *
+ * if <code>exp</code> is <code>false</code>
+ *
+ * @param exp boolean value to check
+ * @param msg exception's message to throw
+ *
+ * @see #fail(Object)
+ */
+ public static
+ void
+ isTrue(
+ final boolean exp,
+ final String msg
+ )
+ {
+ if ( exp )
+ {
+ return ;
+ }
+ fail( msg );
+ }
+
+ /**
+ * Assert that <code>exp</code> is <code>false</code>
+ *
+ * Throw {@link IllegalArgumentException} with <code>msg</code> message
+ *
+ * if <code>exp</code> is <code>true</code>
+ *
+ * @param exp boolean value to check
+ * @param msg exception's message to throw
+ *
+ * @see #fail(Object)
+ */
+ public static
+ void
+ isFalse(
+ final boolean exp,
+ final String msg
+ )
+ {
+ if ( !exp )
+ {
+ return ;
+ }
+ fail( msg );
+ }
+
+ /**
+ * Assert that <code>exp</code> is <code>true</code>
+ *
+ * Throw {@link IllegalArgumentException} with "Expression must be true" message
+ *
+ * if <code>exp</code> is <code>false</code>
+ *
+ * @param exp boolean value to check
+ *
+ * @see #isTrue(boolean, String)
+ */
+ public static void
+ isTrue(
+ final boolean exp
+ )
+ {
+ isTrue( exp, "Expression must be true" );
+ }
+
+ /**
+ * Assert that <code>exp</code> is <code>false</code>
+ *
+ * Throw {@link IllegalArgumentException} with "Expression must be false" message
+ *
+ * if <code>exp</code> is <code>true</code>
+ *
+ * @param exp boolean value to check
+ *
+ * @see #isFalse(boolean, String)
+ */
+ public static
+ void
+ isFalse(
+ final boolean exp
+ )
+ {
+ isFalse( exp, "Expression must be false" );
+ }
+
+ /**
+ * Assert that <code>obj</code> is <code>null</code>
+ *
+ * Throw {@link IllegalArgumentException} with <code>msg</code> message
+ *
+ * if <code>obj</code> is not <code>null</code>
+ *
+ * @param obj object to check
+ * @param msg exception's message to throw
+ *
+ * @see #isTrue(boolean, String)
+ */
+ public static
+ void
+ isNull(
+ final Object obj,
+ final String msg
+ )
+ {
+ isTrue( null == obj, msg );
+ }
+
+ /**
+ * Assert that <code>obj</code> is <code>null</code>
+ *
+ * Throw {@link IllegalArgumentException} with <code>msg</code> message
+ *
+ * if <code>obj</code> is <code>null</code>
+ *
+ * @param obj object to check
+ * @param msg exception's message to throw
+ *
+ * @see #isFalse(boolean, String)
+ */
+ public static
+ void
+ notNull(
+ final Object obj,
+ final String msg
+ )
+ {
+ isFalse( null == obj, msg );
+ }
+
+ /**
+ * Assert that <code>obj</code> is <code>null</code>
+ *
+ * Throw {@link IllegalArgumentException} with "Object must be null" message
+ *
+ * if <code>obj</code> is not <code>null</code>
+ *
+ * @param obj object to check
+ *
+ * @see #isNull(Object, String)
+ */
+ public static
+ void
+ isNull(
+ final Object obj
+ )
+ {
+ isNull( obj, "Object must be null" );
+ }
+
+ /**
+ * Assert that <code>obj</code> is not <code>null</code>
+ *
+ * Throw {@link IllegalArgumentException} with <code>msg</code> message
+ *
+ * if <code>obj</code> is <code>null</code>
+ *
+ * @param obj object to check
+ *
+ * @see #notNull(Object, Object)
+ */
+ public static
+ void
+ notNull(
+ final Object obj
+ )
+ {
+ notNull( obj, "Object must NOT be null" );
+ }
+
+
+ /**
+ * Assert that two objects( <code>obj1</code> and <code>obj2</code> ) is equal.
+ *
+ * Throw {@link IllegalArgumentException} with <code>msg</code> message
+ *
+ * if two objects is not equal
+ *
+ * @param obj1 first object to compare
+ * @param obj2 second object to compare
+ * @param msg exception's message to throw
+ *
+ * @see #fail(Object)
+ */
+ public static
+ void
+ isEqual(
+ final Object obj1,
+ final Object obj2,
+ final String message
+ )
+ {
+ if ( ObjectUtil.equals( obj1, obj2 ) )
+ {
+ return ;
+ }
+
+ fail( message );
+ }
+
+
+ /**
+ * Assert that two objects( <code>obj1</code> and <code>obj2</code> ) is equal.
+ *
+ * Throw {@link IllegalArgumentException} with "Objects are not equal" message
+ *
+ * if two objects is not equal
+ *
+ * @param obj1 first object to compare
+ * @param obj2 second object to compare
+ *
+ * @see #isEqual(Object, Object, String)
+ */
+ public static
+ void
+ isEqual(
+ final Object obj1,
+ final Object obj2
+ )
+ {
+ isEqual( obj1, obj2, "Objects are not equal" );
+ }
+
+ /**
+ * Assert that <code>text</code> has any readible character
+ *
+ * Throw {@link IllegalArgumentException} with <code>msg</code> message
+ *
+ * if <code>text</code> is <code>null</code> or empty string.
+ *
+ * @param text string to check
+ * @param msg exception's message to throw
+ *
+ * @see #fail(Object)
+ */
+ public static
+ void
+ hasLength(
+ final String text,
+ final String msg
+ )
+ {
+ if( StringUtil.hasLength( text ) )
+ {
+ return ;
+ }
+ fail( msg );
+ }
+ /**
+ * Assert that <code>text</code> has any readible character
+ *
+ * Throw {@link IllegalArgumentException} with "String argument must have length; it must not be null or empty" message
+ *
+ * if <code>text</code> is <code>null</code> or empty string.
+ *
+ * @param text string to check
+ *
+ * @see #hasLength(String, String)
+ */
+ public static
+ void
+ hasLength(
+ final String text
+ )
+ {
+ hasLength( text, "String argument must have length; it must not be null or empty" );
+ }
+
+
+ /**
+ * Assert that <code>text</code> has any readible character
+ *
+ * Throw {@link IllegalArgumentException} with <code>msg</code> message
+ *
+ * if <code>text</code> is <code>null</code>, empty string or string containing only unvisible character
+ *
+ * @param text string to check
+ * @param msg exception's message to throw
+ *
+ * @see #fail(Object)
+ */
+ public static
+ void
+ hasText(
+ final String text,
+ final String message
+ )
+ {
+ if ( StringUtil.hasText( text ) )
+ {
+ return ;
+ }
+ fail( message );
+ }
+
+ /**
+ * Assert that <code>text</code> has any readible character
+ *
+ * Throw {@link IllegalArgumentException} with "String argument must have text; it must not be null, empty, or blank" message
+ *
+ * if <code>text</code> is <code>null</code>, empty string or string containing only unvisible character
+ *
+ * @param text string to check
+ *
+ * @see #hasText(String, String)
+ */
+ public static
+ void
+ hasText(
+ final String text
+ )
+ {
+ hasText( text, "String argument must have text; it must not be null, empty, or blank" );
+ }
+
+ /**
+ * Assert that <code>textToSearch</code> does not have <code>substring</code> in part.
+ *
+ * Throw {@link IllegalArgumentException} with <code>msg</code> message
+ *
+ * if assertion is failure.
+ *
+ * Assertion is successful if <code>textToSearch</code> or <code>substring</code> is <code>null</code>.
+ *
+ * @param textToSearch search target string
+ * @param substring keyword to search
+ * @param msg exception's message to throw
+ *
+ * @see String#contains(CharSequence)
+ */
+ public static
+ void
+ doesNotContain(
+ final String textToSearch,
+ final String substring,
+ final String msg
+ )
+ {
+ if ( !StringUtil.hasLength( textToSearch ) )
+ {
+ return ;
+ }
+
+ if ( !StringUtil.hasLength( substring ) )
+ {
+ return ;
+ }
+
+ if ( !textToSearch.contains( substring ) )
+ {
+ return ;
+ }
+ fail( msg );
+ }
+
+ /**
+ * Assert that <code>textToSearch</code> does not have <code>substring</code> in part.
+ *
+ * Throw {@link IllegalArgumentException} with "String argument must not contain the substring [<code>substring</code>]" message
+ *
+ * if assertion is failure.
+ *
+ * Assertion is successful if <code>textToSearch</code> or <code>substring</code> is <code>null</code>.
+ *
+ * @param textToSearch search target string
+ * @param substring keyword to search
+ *
+ * @see #doesNotContain(String, String, String)
+ */
+ public static
+ void
+ doesNotContain(
+ final String textToSearch,
+ final String substring
+ )
+ {
+ doesNotContain(
+ textToSearch,
+ substring,
+ "String argument must not contain the substring [" + substring + "]"
+ );
+ }
+
+ /**
+ * Assert that <code>textToSearch</code> has <code>substring</code> in part.
+ *
+ * Throw {@link IllegalArgumentException} with <code>msg</code> message
+ *
+ * if assertion is failure.
+ *
+ * Assertion is successful if <code>textToSearch</code> or <code>substring</code> is <code>null</code>.
+ *
+ * @param textToSearch search target string
+ * @param substring keyword to search
+ * @param msg exception's message to throw
+ *
+ * @see String#contains(CharSequence)
+ */
+ public static
+ void
+ contains(
+ final String textToSearch,
+ final String substring,
+ final String msg
+ )
+ {
+ if ( !StringUtil.hasLength( textToSearch ) )
+ {
+ return ;
+ }
+ if ( !StringUtil.hasLength( substring ) )
+ {
+ return ;
+ }
+ if ( textToSearch.contains( substring ) )
+ {
+ return ;
+ }
+ fail( msg );
+ }
+
+ /**
+ * Assert that <code>textToSearch</code> does not have <code>substring</code> in part.
+ *
+ * Throw {@link IllegalArgumentException} with "String argument must contain the substring [<code>substring</code>]" message
+ *
+ * if assertion is failure.
+ *
+ * Assertion is successful if <code>textToSearch</code> or <code>substring</code> is <code>null</code>.
+ *
+ * @param textToSearch search target string
+ * @param substring keyword to search
+ *
+ * @see #doesContain(String, String, String)
+ */
+ public static
+ void
+ contains(
+ final String textToSearch,
+ final String substring
+ )
+ {
+ contains(
+ textToSearch,
+ substring,
+ "String argument must contain the substring [" + substring + "]"
+ );
+ }
+
+ /**
+ * Assert that <code>array</code> has a element at least.
+ *
+ * Throw {@link IllegalArgumentException} with <code>msg</code> message
+ *
+ * if <code>array</code> is null or empty array.
+ *
+ * @param <T> type of array elemtent
+ * @param array array object to check
+ * @param msg exception's message to throw
+ *
+ * @see ArrayUtil#isEmpty( Object[] )
+ */
+ public static <T>
+ void
+ notEmpty(
+ final T[] array,
+ final String message
+ )
+ {
+ if( ArrayUtil.isEmpty( array ) )
+ {
+ fail( message );
+ }
+ }
+
+ /**
+ * Assert that <code>array</code> has a element at least.
+ *
+ * Throw {@link IllegalArgumentException} with "Array must not be empty: it must contain at least 1 element" message
+ *
+ * if <code>array</code> is null or empty array.
+ *
+ * @param <T> type of array elemtent
+ * @param array array object to check
+ * @param msg exception's message to throw
+ *
+ * @see #notEmpty( Object[] )
+ */
+ public static
+ void
+ notEmpty(
+ final Object[] array
+ )
+ {
+ notEmpty( array, "Array must not be empty: it must contain at least 1 element" );
+ }
+
+ /**
+ * Assert that there is no <code>null</code> in array elements
+ *
+ * Throw {@link IllegalArgumentException} with <code>msg</code> message
+ *
+ * if <code>array</code> has null element.
+ *
+ * @param array array to check
+ * @param msg exception's message to throw
+ *
+ * @see #fail(Object)
+ */
+ public static
+ void
+ noNullElements(
+ final Object[] array,
+ final String msg
+ )
+ {
+
+ for ( int i=0, n=ArrayUtil.size( array ) ; i<n ; ++i )
+ {
+ if ( null != array[i] )
+ {
+ continue;
+ }
+
+ fail( msg );
+ }
+ }
+
+ /**
+ * Assert that there is no <code>null</code> in array elements
+ *
+ * Throw {@link IllegalArgumentException} with "Array must not contain any null elements" message
+ *
+ * if <code>array</code> has null element.
+ *
+ * @param array array to check
+ *
+ * @see #noNullElements(Object[], String)
+ */
+ public static
+ void
+ noNullElements(
+ final Object[] array
+ ) {
+ noNullElements( array, "Array must not contain any null elements" );
+ }
+
+
+ /**
+ * Assert that <code>collection</code>is not empty
+ *
+ * Throw {@link IllegalArgumentException} with <code>msg</code> message
+ *
+ * if <code>collection</code> has no element
+ *
+ * @param collection {@link Collection} to check
+ * @param msg exception's message to throw
+ *
+ * @see CollectionUtil#isEmpty( Collection )
+ * @see #fail(Object)
+ */
+ public static
+ void
+ notEmpty(
+ final Collection<?> collection,
+ final String msg
+ )
+ {
+ if( !CollectionUtil.isEmpty( collection ) )
+ {
+ return ;
+ }
+ fail( msg );
+ }
+
+ /**
+ * Assert that <code>collection</code>is not empty
+ *
+ * Throw {@link IllegalArgumentException} with "Collection must not be empty: it must contain at least 1 element" message
+ *
+ * if <code>collection</code> has no element
+ *
+ * @param collection {@link Collection} to check
+ *
+ * @see #notEmpty(Collection, String)
+ */
+ public static
+ void
+ notEmpty(
+ final Collection<?> collection
+ )
+ {
+ notEmpty( collection, "Collection must not be empty: it must contain at least 1 element" );
+ }
+
+ /**
+ * Assert that <code>map</code>is not empty
+ *
+ * Throw {@link IllegalArgumentException} with <code>msg</code> message
+ *
+ * if <code>map</code> has no element
+ *
+ * @param map {@link Map} to check
+ * @param msg exception's message to throw
+ *
+ * @see MapUtil#isEmpty( Map )
+ * @see #fail(Object)
+ */
+ public static
+ void
+ notEmpty(
+ final Map<?, ?> map,
+ final String msg
+ )
+ {
+ if ( !MapUtil.isEmpty( map ) )
+ {
+ return ;
+ }
+ fail( msg );
+ }
+
+ /**
+ * Assert that <code>map</code>is not empty
+ *
+ * Throw {@link IllegalArgumentException} with "Map must not be empty; it must contain at least one entry" message
+ *
+ * if <code>map</code> has no element
+ *
+ * @param map {@link Map} to check
+ *
+ * @see #notEmpty(Map, String)
+ */
+ public static
+ void
+ notEmpty(
+ final Map<?, ?> map
+ )
+ {
+ notEmpty( map, "Map must not be empty; it must contain at least one entry" );
+ }
+
+ /**
+ * Assert that <code>obj</code> is instance of <code>type</code>
+ *
+ * Throw {@link IllegalArgumentException} with <code>msg</code> message
+ *
+ * if <code>obj</code> is <code>null</code> or not instance of <code>type</code>
+ *
+ * @param type {@link Class} to check
+ * @param obj instance object to check
+ * @param msg exception's message to throw
+ *
+ * @see Class#isInstance(Object)
+ * @see #fail(Object)
+ */
+ public static
+ void
+ isInstanceOf(
+ final Class<?> type,
+ final Object obj,
+ final String msg
+ )
+ {
+ notNull( type, "Type to check against must not be null" );
+ if( type.isInstance( obj ) )
+ {
+ return ;
+ }
+
+ fail( MessageFormat.format(
+ "{0}, Object of class [{1}] must be aan instance of {2}",
+ msg,
+ (( null == obj ) ?"null":obj.getClass().getName()),
+ type
+ ) );
+ }
+
+ /**
+ * Assert that <code>obj</code> is instance of <code>type</code>
+ *
+ * Throw {@link IllegalArgumentException}
+ *
+ * if <code>obj</code> is <code>null</code> or not instance of <code>type</code>
+ *
+ * @param type {@link Class} to check
+ * @param obj instance object to check
+ *
+ * @see #isInstanceOf(Class, Object, String)
+ */
+ public static
+ void
+ isInstanceOf(
+ final Class<?> type,
+ final Object obj
+ )
+ {
+ isInstanceOf( type, obj, "" );
+ }
+
+ /**
+ * Assert that <code>superType</code> is assignable type from <code>subType</code> instance
+ *
+ * Throw {@link IllegalArgumentException} with <code>msg</code> message
+ *
+ * if <code>superType</code> or <code>subType</code> is <code>null</code> or if assertion is failure
+ *
+ * @param superType super type candidate
+ * @param subType subtype candidate
+ * @param msg exception's message to throw
+ *
+ * @see Class#isAssignableFrom(Class)
+ * @see #fail(Object)
+ */
+ public static
+ void
+ isAssignable(
+ final Class<?> superType,
+ final Class<?> subType,
+ final String msg
+ )
+ {
+ notNull( superType, "Type to check against must not be null" );
+ notNull( subType, "Type to assign must not be null" );
+ if( superType.isAssignableFrom( subType ) )
+ {
+ return ;
+ }
+ fail( MessageFormat.format(
+ "{0}, {1} is not assignable to {2}",
+ msg,
+ subType,
+ superType
+ ) );
+ }
+
+ /**
+ * Assert that <code>superType</code> is assignable type from <code>subType</code> instance
+ *
+ * Throw {@link IllegalArgumentException}
+ *
+ * if <code>superType</code> or <code>subType</code> is <code>null</code> or if assertion is failure
+ *
+ * @param superType super type candidate
+ * @param subType subtype candidate
+ *
+ * @see #isAssignable(Class, Class, String)
+ */
+ public static
+ void
+ isAssignable(
+ final Class<?> superType,
+ final Class<?> subType
+ )
+ {
+ isAssignable( superType, subType, "" );
+ }
+
+}
diff --git a/org.tizen.common/src/org/tizen/common/util/BrowserWrapper.java b/org.tizen.common/src/org/tizen/common/util/BrowserWrapper.java
index 87c370476..96111daa3 100644
--- a/org.tizen.common/src/org/tizen/common/util/BrowserWrapper.java
+++ b/org.tizen.common/src/org/tizen/common/util/BrowserWrapper.java
@@ -25,6 +25,8 @@
package org.tizen.common.util;
+import static org.tizen.common.util.SWTUtil.asyncExec;
+
import java.io.File;
import org.eclipse.swt.SWT;
@@ -52,8 +54,7 @@ public class BrowserWrapper {
}
public void setInput(final File f) {
- browser.getDisplay().asyncExec(new Runnable() {
- @Override
+ asyncExec(new Runnable() {
public void run() {
if (!browser.isDisposed()) {
browser.setUrl(f.getAbsolutePath());
diff --git a/org.tizen.common/src/org/tizen/common/util/CipherUtil.java b/org.tizen.common/src/org/tizen/common/util/CipherUtil.java
new file mode 100644
index 000000000..6bf9a91eb
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/util/CipherUtil.java
@@ -0,0 +1,97 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* Ho Namkoong <ho.namkoong@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+
+package org.tizen.common.util;
+
+import javax.crypto.Cipher;
+import javax.crypto.SecretKey;
+import javax.crypto.SecretKeyFactory;
+import javax.crypto.spec.DESedeKeySpec;
+
+import org.tizen.common.util.log.Logger;
+
+import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
+
+/**
+ * CipherUtil
+ *
+ * This is a util class for encrypting and decrypting plain texts.
+ *
+ * @author Ho Namkoong{@literal <ho.namkoong@samsung.com>} (S-Core)
+ */
+public class CipherUtil {
+
+ private static final String password = "KYANINYLhijklmnopqrstuvwx";
+ private static SecretKey SECRETE_KEY;
+ private static Cipher DES_CIPHER;
+ private static final String ALGORITHM = "DESede";
+
+ static {
+ try {
+ byte key[] = password.getBytes();
+ DESedeKeySpec desKeySpec = new DESedeKeySpec(key);
+ SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
+ SECRETE_KEY = keyFactory.generateSecret(desKeySpec);
+
+ DES_CIPHER = Cipher.getInstance(ALGORITHM + "/ECB/PKCS5Padding");
+ } catch (Throwable t) {
+ Logger.error("Exception occurred while creating secret key", t);
+ }
+ }
+
+ private static byte[] decryptByDES(byte[] bytes) throws Exception{
+ DES_CIPHER.init(Cipher.DECRYPT_MODE, SECRETE_KEY);
+
+ return DES_CIPHER.doFinal(bytes);
+ }
+
+ private static byte[] encryptByDES(String s) throws Exception {
+ DES_CIPHER.init(Cipher.ENCRYPT_MODE, SECRETE_KEY);
+
+ return DES_CIPHER.doFinal(s.getBytes());
+ }
+
+ /**
+ * Decrypt cipher message
+ *
+ * @param s cipher message which will be decrypted.
+ * @return decrypted plain text.
+ * @author Ho Namkoong {@literal <ho.namkoong@samsung.com>} (S-Core)
+ */
+ public static String getDecryptedString(String s) throws Exception {
+ return new String(decryptByDES(Base64.decode(s)));
+ }
+
+ /**
+ * Encrypt plain text
+ *
+ * @param s plain text which will be encrypted.
+ * @return encrypted cipher text.
+ * @author Ho Namkoong {@literal <ho.namkoong@samsung.com>} (S-Core)
+ */
+ public static String getEncryptedString(String s) throws Exception {
+ return new String(Base64.encode(encryptByDES(s)));
+ }
+} \ No newline at end of file
diff --git a/org.tizen.common/src/org/tizen/common/util/CollectionMap.java b/org.tizen.common/src/org/tizen/common/util/CollectionMap.java
new file mode 100644
index 000000000..903757962
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/util/CollectionMap.java
@@ -0,0 +1,232 @@
+/*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common.util;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+
+
+/**
+ * CollectionUtil.
+ *
+ * Helper related to collection( Set, List, etc )
+ *
+ * Characters for both {@link Collection} and {@link Map}
+ *
+ * You can add and remove not only key-value pair but also a set of key-value
+ *
+ * Replace key-value set to <code>null</code> if no values
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ *
+ * @param <K> key type
+ * @param <V> value type
+ */
+public class
+CollectionMap<K, V>
+{
+
+ /**
+ * Map to manage key-values
+ */
+ protected final HashMap<K, Collection<V>> map = new LinkedHashMap<K, Collection<V>>();
+
+
+ /**
+ * Create values container
+ *
+ * Determine a method for management of values
+ *
+ * Modify this method if you want to change value container
+ *
+ * @return value containing {@link Collection}
+ */
+ protected
+ Collection<V>
+ createValues()
+ {
+ return new ArrayList<V>();
+ }
+
+ /**
+ * Add key-value pair
+ *
+ * @param key key to add
+ * @param value value to add
+ */
+ public
+ void
+ put(
+ final K key,
+ final V value
+ )
+ {
+ Collection<V> values = map.get( key );
+ if ( null == values )
+ {
+ values = createValues();
+ map.put( key, values );
+ }
+
+ values.add( value );
+ }
+
+ /**
+ * Return keys
+ *
+ * @return {@link Collection} for key
+ *
+ * @see java.util.Map#keySet()
+ */
+ public
+ Collection<K>
+ keySet() {
+ return map.keySet();
+ }
+
+ /**
+ * Return values for <code>key</code>
+ *
+ * Return <code>null</code> if no values
+ *
+ * @param key key for values
+ *
+ * @return key related values
+ */
+ public
+ Collection<V>
+ get(
+ final K key
+ )
+ {
+ return map.get( key );
+ }
+
+ /**
+ * Replace a set of key-values
+ *
+ * @param key key for key-valeus
+ * @param values values for key-values
+ *
+ * @return old values for <code>key</code>
+ */
+ public
+ Collection<V>
+ set(
+ final K key,
+ final Collection<V> values
+ )
+ {
+ return map.put( key, values );
+ }
+
+ /**
+ * Remove a set of key-values
+ *
+ * @param key key for key-values
+ *
+ * @return values to be removed
+ */
+ public
+ Collection<V>
+ remove(
+ final K key
+ )
+ {
+ return map.remove( key );
+ }
+
+ /**
+ * Remove key-value pair from a set and return values after change
+ *
+ * Return <code>null</code> if no values
+ *
+ * @param key key for key-value
+ * @param value value for key-value
+ *
+ * @return values after change
+ */
+ public
+ Collection<V>
+ remove(
+ final K key,
+ final V value
+ )
+ {
+ final Collection<V> values = map.get( key );
+ values.remove( value );
+
+ if ( values.isEmpty() )
+ {
+ map.remove( key );
+ return null;
+ }
+
+ return values;
+ }
+
+ /**
+ * Remove all sets
+ */
+ public
+ void
+ clear()
+ {
+ map.clear();
+ }
+
+ /* (non-Javadoc)
+ * @see java.lang.Object#toString()
+ */
+ @Override
+ public
+ String
+ toString()
+ {
+ final StringBuilder buffer = new StringBuilder();
+
+ buffer.append( "CollectionMap[" );
+
+ boolean bInit = false;
+
+ for ( final K key : map.keySet() )
+ {
+ if ( bInit )
+ {
+ buffer.append( ", " );
+ }
+ bInit = true;
+ buffer.append( key );
+ buffer.append( '=' );
+ buffer.append( map.get( key ) );
+ }
+
+ buffer.append( "]" );
+
+ return buffer.toString();
+ }
+}
diff --git a/org.tizen.common/src/org/tizen/common/util/CollectionUtil.java b/org.tizen.common/src/org/tizen/common/util/CollectionUtil.java
new file mode 100644
index 000000000..2d5a024f4
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/util/CollectionUtil.java
@@ -0,0 +1,1890 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* BonYong Lee <bonyong.lee@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+package org.tizen.common.util;
+
+import static org.tizen.common.util.StringUtil.EMPTY_STRING;
+import static org.tizen.common.util.StringUtil.NULL_STRING;
+
+import java.lang.reflect.InvocationTargetException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.SortedMap;
+import java.util.SortedSet;
+import java.util.TreeMap;
+import java.util.TreeSet;
+
+import org.tizen.common.util.ArrayUtil.ArrayIterator;
+
+/**
+ * CollectionUtil.
+ *
+ * Helper related to collection( Set, List, etc )
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ */
+public class CollectionUtil
+{
+
+ /**
+ * Empty bytes
+ */
+ protected static final byte[] EMPTY_BYTE_ARRAY = new byte[0];
+ protected static final byte[] EMPTY_BYTES = EMPTY_BYTE_ARRAY;
+
+ private static final String ARRAY_START = "{";
+
+ private static final String ARRAY_END = "}";
+
+ private static final String EMPTY_ARRAY = ARRAY_START + ARRAY_END;
+
+ private static final String ARRAY_ELEMENT_SEPARATOR = ", ";
+
+ private static final Set<Class<?>> APPROXIMABLE_COLLECTION_TYPES =
+ Collections.unmodifiableSet( new HashSet<Class<?>>( Arrays.asList( new Class<?>[] {
+ Collection.class,
+ Set.class, HashSet.class, SortedSet.class, LinkedHashSet.class, TreeSet.class,
+ List.class, LinkedList.class, ArrayList.class
+ } ) ) );
+
+ private static final Set<Class<?>> APPROXIMABLE_MAP_TYPES =
+ Collections.unmodifiableSet( new HashSet<Class<?>>( Arrays.asList( new Class<?>[] {
+ Map.class, SortedMap.class, HashMap.class, LinkedHashMap.class, TreeMap.class
+ } ) ) );
+
+
+
+ /* Object */
+ /**
+ * Empty Collection
+ */
+ public static final Collection<Object> EMPTY_COLLECTION =
+ Collections.unmodifiableCollection( new ArrayList<Object>() );
+
+ /**
+ * protected constructor
+ */
+ protected CollectionUtil() {}
+
+ /**
+ * <p>
+ * check <code>collection</code> has no element.
+ *
+ * use without null check.
+ *
+ * Old style
+ *
+ * <code>
+ * List list = null;
+ * ...
+ * if ( null != list && !list.isEmpty() ) {
+ * ...
+ * }
+ * </code>
+ *
+ * Usage :
+ * <p>
+ *
+ * <code>
+ * List list = null;
+ * ...
+ * if ( !CollectionUtil.isEmpty( list ) ) {
+ * ...
+ * }
+ * </code>
+ *
+ * or "import static" style if you use JDK6
+ *
+ * </code>
+ * import static org.tizen.common.util.CollectionUtil.isEmpty;
+ *
+ * ...
+ * List list = null;
+ * ...
+ * if ( !isEmpty( list ) ) {
+ * ...
+ * }
+ * </code>
+ *
+ * @param collection {@link Collection} to check
+ *
+ * @return value if collection is empty
+ */
+ public static
+ boolean
+ isEmpty(
+ final Collection<?> collection
+ )
+ {
+ if ( null == collection )
+ {
+ return true;
+ }
+
+ return collection.isEmpty();
+ }
+
+ /**
+ * <p>
+ * Return <code>collection</code>'s size.
+ *
+ * use without null check.
+ *
+ * Return <code>0</code> if <code>collection</code> is <code>null</code>
+ *
+ * <p>
+ *
+ * Old style
+ * <code>
+ * if ( null != list ) {
+ * for ( int i = 0, n = list.size() ; i < n ; ++i ) {
+ * ...
+ * }
+ * }
+ * </code>
+ *
+ *
+ * <code>
+ * for ( int i = 0, n = CollectionUtil.size( list ) ; i < n ; ++i ) {
+ * ...
+ * }
+ *
+ * </code>
+ * or "import static" style if you use JDK6
+ *
+ * </code>
+ * import static org.tizen.common.util.CollectionUtil.isEmpty;
+ * ...
+ *
+ * for ( int i = 0, n = size( list ) ; i < n ; ++i ) {
+ * ...
+ * }
+ *
+ * </code>
+ *
+ * @param collection {@link Collection} to check
+ *
+ * @return size of <code>collection</code>
+ *
+ * @see Collection#size()
+ */
+ public static
+ int
+ size(
+ final Collection<?> collection
+ )
+ {
+ if ( null == collection )
+ {
+ return 0;
+ }
+
+ return collection.size();
+ }
+
+ /**
+ * <p>
+ * run <code>runner</code> iterateing element of <code>collection</code>.
+ *
+ * use without null-check for <code>collection</code>
+ *
+ * delegate error handling to <code>runner</code>
+ * </p>
+ *
+ * <code>
+ *
+ * CollectionUtil.iterate(
+ * new ArrayList<String>( Arrays.asList( "hello", "Hello", "World", null, "Test" ) ),
+ * new IteratingRunner<String>() {
+ * public void run( String arg ) {
+ * ...
+ * }
+ * }
+ * );
+ *
+ * </code>
+ *
+ * @param <T> type of element in <code>collection</code>
+ * @param collection {@link Collection} containing element
+ * @param runner {@link Runnable} to execute
+ *
+ * @throws InvocationTargetException when <code>runner</code>'s {@link Runnable#run()} throws exception
+ *
+ * @see {@link #iterate(Collection, IteratingRunner, boolean)}
+ * @see FilterIterator
+ */
+ public static <T>
+ void
+ iterate(
+ final Collection<? extends T> collection,
+ final IteratingRunner<T> runner
+ )
+ throws InvocationTargetException
+ {
+ iterate( collection, runner, false );
+ }
+
+ /**
+ * <p>
+ * run <code>runner</code> iterateing element of <code>collection</code>.
+ *
+ * use without null-check for <code>collection</code>
+ *
+ * delegate error handling to <code>runner</code>
+ *
+ * </p>
+ * <code>
+ *
+ * CollectionUtil.iterate(
+ * new ArrayList<String>( Arrays.asList( "hello", "Hello", "World", null, "Test" ) ),
+ * new IteratingRunner<String>() {
+ * public void run( String arg ) {
+ * ...
+ * }
+ * },
+ * true
+ * );
+ *
+ * </code>
+ *
+ * @param <T> type of element in <code>collection</code>
+ * @param collection {@link Collection} containing element
+ * @param runner {@link Runnable} to execute
+ * @param bForceProcess flag to iterate continuously when exception occurs
+ *
+ * @throws InvocationTargetException when <code>runner</code>'s {@link Runnable#run()} throws exception
+ *
+ * @see FilterIterator
+ */
+ public static <T>
+ void
+ iterate(
+ final Collection<? extends T> collection,
+ final IteratingRunner<T> runner,
+ final boolean bForceProcess
+ )
+ throws InvocationTargetException
+ {
+ if ( null == runner )
+ {
+ return ;
+ }
+ if ( isEmpty( collection ) )
+ {
+ return ;
+ }
+
+ for ( final T arg : collection )
+ {
+ if ( null == arg && !bForceProcess )
+ {
+ continue ;
+ }
+ try
+ {
+ runner.run( arg );
+ } catch ( Throwable e )
+ {
+ if ( !bForceProcess )
+ {
+ throw new InvocationTargetException( e );
+ }
+ }
+ }
+ }
+
+ /**
+ * <p>
+ * fiter <code>collection</code> to <code>result</code> using <code>runner</code>
+ *
+ * determined if stop or keep going using <code>bForceProcess</code> in case of exception.
+ * </p>
+ *
+ * @param <T> type of element in <code>collection</code>
+ * @param collection {@link Collection} to filter
+ * @param results collection to save result
+ * @param runner object to determine if filter
+ * @param bForceProcess flag to keep going when exception occurs
+ *
+ * @throws InvocationTargetException when <code>runner</code>'s {@link Runnable#run()} throws exception
+ */
+ public static <T>
+ void
+ filter(
+ final Collection<? extends T> collection,
+ final Collection<T> results,
+ final IteratingAcceptor<T> runner,
+ final boolean bForceProcess
+ ) throws InvocationTargetException
+ {
+ if ( null == results )
+ {
+ return ;
+ }
+ if ( isEmpty( collection ) )
+ {
+ return ;
+ }
+
+ for ( final T arg : collection )
+ {
+ if ( null == arg && !bForceProcess )
+ {
+ continue ;
+ }
+ try
+ {
+ if ( runner.accept( arg ) )
+ {
+ results.add( arg );
+ }
+ } catch ( Throwable e )
+ {
+ if ( !bForceProcess )
+ {
+ throw new InvocationTargetException( e );
+ }
+ }
+
+ }
+ }
+
+ /**
+ * <p>
+ * Return first element in <code>collection</code><br>
+ *
+ * Return <code>null</code> if <code>collection</code> is null or empty
+ * </p>
+ * @param <T> type of element in <code>collection</code>
+ * @param collection {@link Collection} to check
+ *
+ * @return first elemtn in <code>collection</code>
+ */
+ public static <T>
+ T
+ pickupFirst( final Collection<T> collection )
+ {
+ if ( isEmpty( collection ) )
+ {
+ return null;
+ }
+
+ final Iterator<T> iter = collection.iterator();
+ return (iter.hasNext())?(iter.next()):null;
+ }
+
+ /**
+ * <p>
+ * Extract and return first element in <code>collection</code><br>
+ *
+ * Return <code>null</code> if <code>collection</code> is null or empty
+ * </p>
+ * @param <T> type of element in <code>collection</code>
+ * @param collection {@link Collection} to check
+ *
+ * @return first elemtn in <code>collection</code>
+ */
+ public static <T>
+ T
+ removeFirst( final Collection<T> collection )
+ {
+ if ( isEmpty( collection ) )
+ {
+ return null;
+ }
+
+ final Iterator<T> iter = collection.iterator();
+ if ( iter.hasNext() )
+ {
+ T ret = iter.next();
+ iter.remove();
+ return ret;
+ }
+ return null;
+ }
+
+
+ /**
+ * <p>
+ * Return last element in <code>collection</code><br>
+ *
+ * Return <code>null</code> if <code>collection</code> is null or empty
+ *
+ * Don't use this in case of big data or looping algorithm
+ * </p>
+ * @param <T> type of element in <code>collection</code>
+ * @param collection {@link Collection} to check
+ *
+ * @return last elemtn in <code>collection</code>
+ */
+ public static <T>
+ T
+ pickupLast( final Collection<T> collection )
+ {
+ if ( isEmpty( collection ) )
+ {
+ return null;
+ }
+
+ final Iterator<T> iter = collection.iterator();
+
+ T temp = null;
+ while ( iter.hasNext() )
+ {
+ temp = iter.next();
+ }
+ return temp;
+ }
+
+ /**
+ * <p>
+ * Extract and return last element in <code>collection</code><br>
+ *
+ * Return <code>null</code> if <code>collection</code> is null or empty
+ *
+ * Don't use this in case of big data or looping algorithm
+ * </p>
+ * @param <T> type of element in <code>collection</code>
+ * @param collection {@link Collection} to check
+ *
+ * @return last elemtn in <code>collection</code>
+ */
+ public static <T>
+ T
+ removeLast( final Collection<T> collection )
+ {
+ if ( isEmpty( collection ) )
+ {
+ return null;
+ }
+
+ final Iterator<T> iter = collection.iterator();
+
+ T temp = null;
+ while ( iter.hasNext() )
+ {
+ temp = iter.next();
+ }
+ iter.remove();
+ return temp;
+ }
+
+ /**
+ * Convert {@link Enumeration} to {@link Iterator} using decoration pattern
+ *
+ * @param <K> element type to be handled by enumertaion
+ */
+ static class
+ EnumerationAdapter<K>
+ implements Iterator<K>
+ {
+ protected final Enumeration<K> enumeration;
+ /**
+ * Constructor with {@link Enumeration}
+ *
+ * @param enumeration {@link Enumeration} to convert
+ */
+ public
+ EnumerationAdapter(
+ final Enumeration<K> enumeration
+ )
+ {
+ if ( null == enumeration )
+ { // Fast fail
+ throw new NullPointerException();
+ }
+
+ this.enumeration = enumeration;
+ }
+
+ /* (non-Javadoc)
+ * @see java.util.Iterator#hasNext()
+ */
+ @Override
+ public
+ boolean
+ hasNext()
+ {
+ return enumeration.hasMoreElements();
+ }
+
+ /* (non-Javadoc)
+ * @see java.util.Iterator#next()
+ */
+ @Override
+ public
+ K
+ next()
+ {
+ return enumeration.nextElement();
+ }
+
+ /* (non-Javadoc)
+ * @see java.util.Iterator#remove()
+ */
+ @Override
+ public
+ void
+ remove()
+ {
+ throw new UnsupportedOperationException();
+ }
+ }
+
+ /**
+ *
+ * Return Iterator to be converted from <code>enumeration</code>
+ *
+ * @param <E> element type interating <code>enumeration</code>
+ * @param enumeration {@link Enumeration} object to be converted
+ *
+ * @return converted {@link Iterator}
+ */
+ public
+ static <E>
+ Iterator<E>
+ iterator(
+ final Enumeration<E> enumeration
+ ) {
+ return new EnumerationAdapter<E>( enumeration );
+ }
+
+
+ /**
+ * Convert array object to {@link List}
+ *
+ * @param source array candidate object
+ *
+ * @return converted {@link List}
+ */
+ public static
+ List<?>
+ asList(
+ final Object source
+ )
+ {
+ return Arrays.asList( ArrayUtil.toObjectArray( source ) );
+ }
+
+ /**
+ *
+ * Add array object to <code>collection</code>
+ *
+ * @param array array candidate object to be added
+ * @param collection {@link Collection} to add
+ *
+ * @see ArrayUtil#toObjectArray(Object)
+ */
+ public static
+ void
+ mergeArrayIntoCollection(
+ final Object array,
+ final Collection<Object> collection
+ )
+ {
+ if ( null == collection )
+ {
+ throw new NullPointerException();
+ }
+
+ final Object[] arr = ArrayUtil.toObjectArray( array );
+ for ( int i=0, n=arr.length ; i<n ; ++i )
+ {
+ collection.add( arr[i] );
+ }
+ }
+
+ /**
+ * Check if <code>iterator</code> meet <code>element</code> in iteration
+ *
+ * @param iterator iterating object
+ * @param element object to check
+ *
+ * @return <code>true</code> if <code>iterator</code> meet <code>element</code>
+ */
+ public static
+ boolean
+ contains(
+ final Iterator<Object> iterator,
+ final Object element
+ )
+ {
+ if ( null == iterator )
+ {
+ return false;
+ }
+
+ while ( iterator.hasNext() )
+ {
+ final Object candidate = iterator.next();
+ if ( ObjectUtil.equals( candidate, element ) )
+ {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Check if <code>enumeration</code> meet <code>element</code> in iteration
+ *
+ * @param enumeration iterating object
+ * @param element object to check
+ *
+ * @return <code>true</code> if <code>enumeration</code> meet <code>element</code>
+ */
+ public static
+ boolean
+ contains(
+ final Enumeration<Object> enumeration,
+ final Object element
+ )
+ {
+ if ( null == enumeration )
+ {
+ return false;
+ }
+ while( enumeration.hasMoreElements() )
+ {
+ final Object candidate = enumeration.nextElement();
+ if ( ObjectUtil.equals( candidate, element ) )
+ {
+ return true;
+ }
+ }
+ return false;
+ }
+
+
+
+ /**
+ * Check if <code>collection</code> contains <code>element</code>
+ *
+ * @param collection {@link Collection} to check
+ * @param element object to check
+ *
+ * @return <code>true</code> if <code>collection</code> contain <code>element</code>
+ */
+ public static
+ boolean
+ contains(
+ final Collection<Object> collection,
+ final Object element
+ )
+ {
+ if ( null == collection )
+ {
+ return false;
+ }
+ for ( final Object candidate : collection )
+ {
+ if ( ObjectUtil.equals( candidate, element ) )
+ {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Check and return if <code>source</code> contain any element of <code>candidates</code>
+ *
+ * @param source {@link Collection} to check
+ * @param candidates {@link Collection} whose element is expected in <code>source</code>
+ *
+ * @return <code>true</code> if <code>source</code> contain any elemnt of <code>candidates</code>
+ */
+ public static
+ boolean
+ containsAny(
+ final Collection<?> source,
+ final Collection<?> candidates
+ )
+ {
+ if ( isEmpty( source ) || isEmpty( candidates) )
+ {
+ return false;
+ }
+
+ for ( final Object candidate : candidates )
+ {
+ if ( source.contains( candidate ) )
+ {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Check <code>collectionType</code> is approximable collection type
+ *
+ * @param collectionType type to check
+ *
+ * @return <code>true</code> if <code>collectionType</code> is in {@link #APPROXIMABLE_COLLECTION_TYPES}
+ *
+ * @see #APPROXIMABLE_COLLECTION_TYPES
+ */
+ public static
+ boolean
+ isApproximableCollectionType(
+ final Class<?> collectionType
+ )
+ {
+ return APPROXIMABLE_COLLECTION_TYPES.contains( collectionType );
+ }
+
+ /**
+ * Check <code>mapType</code> is approximable map type
+ *
+ * @param mapType type to check
+ *
+ * @return <code>true</code> if <code>mapType</code> is in {@link #APPROXIMABLE_MAP_TYPES}
+ *
+ * @see #APPROXIMABLE_MAP_TYPES
+ */
+ public static
+ boolean
+ isApproximableMapType(
+ final Class<?> mapType
+ )
+ {
+ return APPROXIMABLE_MAP_TYPES.contains( mapType );
+ }
+
+ /**
+ * Create <code>collection</code> matched approximable collection
+ *
+ * @param <K> containing type
+ * @param collection {@link Collection} to convert
+ * @param initialCapacity initial size of created collection
+ *
+ * @return created approximable collection
+ */
+ public static <K>
+ Collection<K>
+ createApproximableCollection(
+ final Collection<K> collection,
+ final int initialCapacity
+ )
+ {
+ if ( collection instanceof LinkedList<?> )
+ {
+ return new LinkedList<K>();
+ }
+ else if ( collection instanceof List<?> )
+ {
+ return new ArrayList<K>( initialCapacity);
+ }
+ else if ( collection instanceof SortedSet<?> )
+ {
+ return new TreeSet<K>( ( (SortedSet<K>)collection).comparator() );
+ }
+ else
+ {
+ return new LinkedHashSet<K>( initialCapacity);
+ }
+ }
+
+ /**
+ * @param <K> Map's Key type
+ * @param <V> Map's Value type
+ * @param map Map argument
+ * @param initialCapacity initial argument for Map which will be created
+ *
+ * @return created ApproximableMap
+ */
+ public static <K, V>
+ Map<K, V>
+ createApproximableMap(
+ final Map<K, V> map,
+ final int initialCapacity
+ )
+ {
+ if ( map instanceof SortedMap<?, ?> )
+ {
+ return new TreeMap<K, V>( ( (SortedMap<K, V>) map).comparator() );
+ }
+ else
+ {
+ return new LinkedHashMap<K, V>( initialCapacity );
+ }
+ }
+
+ /* print */
+
+ /**
+ * Converts <code>obj</code> object to String.
+ *
+ * @param obj object to convert
+ *
+ * @return converted String
+ */
+ public static
+ String
+ toString(
+ final Object obj
+ )
+ {
+ if ( null == obj )
+ {
+ return NULL_STRING;
+ }
+
+ if ( obj instanceof String )
+ {
+ return (String) obj;
+ }
+ else if ( obj instanceof Object[] )
+ {
+ return toString( ( Object[] ) obj );
+ }
+ else if ( obj instanceof boolean[] )
+ {
+ return toString( ( boolean[] ) obj );
+ }
+ else if ( obj instanceof byte[] )
+ {
+ return toString( ( byte[] )obj );
+ }
+ else if ( obj instanceof char[] )
+ {
+ return toString( ( char[] ) obj );
+ }
+ else if ( obj instanceof double[] )
+ {
+ return toString( ( double[] ) obj );
+ }
+ else if ( obj instanceof float[] )
+ {
+ return toString( (float[] ) obj );
+ }
+ else if ( obj instanceof int[] )
+ {
+ return toString( (int[] ) obj );
+ }
+ else if ( obj instanceof long[] )
+ {
+ return toString( ( long[] ) obj );
+ }
+ else if ( obj instanceof short[] )
+ {
+ return toString( ( short[] )obj );
+ }
+ return ObjectUtil.nvl( obj.toString(), EMPTY_STRING );
+ }
+
+ /**
+ * Converts <code>array</code> boolean[] to String.
+ *
+ * @param array boolean[] to convert
+ *
+ * @return converted String
+ */
+ public static
+ String
+ toString(
+ final boolean[] array
+ )
+ {
+ if ( null == array )
+ {
+ return NULL_STRING;
+ }
+
+ final int length = array.length;
+
+ if ( 0 == length )
+ {
+ return EMPTY_ARRAY;
+ }
+
+ final StringBuilder buffer= new StringBuilder();
+
+ buffer.append( ARRAY_START);
+ for ( int i=0 ; i<length ; ++i )
+ {
+ if ( 0 != i ) {
+ buffer.append( ARRAY_ELEMENT_SEPARATOR );
+ }
+
+ buffer.append( toString( array[i] ) );
+ }
+ buffer.append( ARRAY_END );
+ return buffer.toString();
+ }
+
+ /**
+ * Converts <code>array</code> byte[] to String.
+ *
+ * @param array byte[] to convert
+ *
+ * @return converted String
+ */
+ public static
+ String
+ toString(
+ final byte[] array
+ )
+ {
+ if ( null == array )
+ {
+ return NULL_STRING;
+ }
+
+ final int length = array.length;
+
+ if ( 0 == length )
+ {
+ return EMPTY_ARRAY;
+ }
+
+ final StringBuilder buffer= new StringBuilder();
+
+ buffer.append( ARRAY_START);
+ for ( int i=0 ; i<length ; ++i )
+ {
+ if ( 0 != i ) {
+ buffer.append( ARRAY_ELEMENT_SEPARATOR );
+ }
+
+ buffer.append( toString( array[i] ) );
+ }
+ buffer.append( ARRAY_END );
+ return buffer.toString();
+ }
+
+ /**
+ * Converts <code>array</code> char[] to String.
+ *
+ * @param array char[] to convert
+ *
+ * @return converted String
+ */
+ public static
+ String
+ toString(
+ final char[] array
+ )
+ {
+ if ( null == array )
+ {
+ return NULL_STRING;
+ }
+
+ final int length = array.length;
+
+ if ( 0 == length )
+ {
+ return EMPTY_ARRAY;
+ }
+
+ final StringBuilder buffer= new StringBuilder();
+
+ buffer.append( ARRAY_START);
+ for ( int i=0 ; i<length ; ++i )
+ {
+ if ( 0 != i )
+ {
+ buffer.append( ARRAY_ELEMENT_SEPARATOR );
+ }
+
+ buffer.append( toString( array[i] ) );
+ }
+ buffer.append( ARRAY_END );
+ return buffer.toString();
+ }
+
+
+ /**
+ * Converts <code>array</code> short[] to String.
+ *
+ * @param array short[] to convert
+ *
+ * @return converted String
+ */
+ public static
+ String
+ toString(
+ final short[] array
+ )
+ {
+ if ( null == array )
+ {
+ return NULL_STRING;
+ }
+
+ final int length = array.length;
+
+ if ( 0 == length )
+ {
+ return EMPTY_ARRAY;
+ }
+
+ final StringBuilder buffer = new StringBuilder();
+ for( int i=0 ; i<length ; ++i )
+ {
+ if ( 0 == i )
+ {
+ buffer.append( ARRAY_START );
+ }
+ else
+ {
+ buffer.append( ARRAY_ELEMENT_SEPARATOR );
+ }
+
+ buffer.append( array[i] );
+ }
+ buffer.append( ARRAY_END );
+ return buffer.toString();
+ }
+
+ /**
+ * Converts <code>array</code> int[] to String.
+ *
+ * @param array int[] to String
+ *
+ * @return converted String
+ */
+ public static
+ String
+ toString(
+ final int[] array
+ )
+ {
+ if ( null == array )
+ {
+ return NULL_STRING;
+ }
+
+ final int length = array.length;
+
+ if ( 0 == length )
+ {
+ return EMPTY_ARRAY;
+ }
+
+ final StringBuilder buffer = new StringBuilder();
+ for( int i=0 ; i<length ; ++i )
+ {
+ if ( 0 == i )
+ {
+ buffer.append( ARRAY_START );
+ }
+ else
+ {
+ buffer.append( ARRAY_ELEMENT_SEPARATOR );
+ }
+
+ buffer.append( array[i] );
+ }
+ buffer.append( ARRAY_END );
+ return buffer.toString();
+ }
+
+ /**
+ * Converts <code>array</code> long[] to String.
+ *
+ * @param array long[] to convert
+ *
+ * @return converted String
+ */
+ public static
+ String
+ toString(
+ final long[] array
+ )
+ {
+ if ( null == array )
+ {
+ return NULL_STRING;
+ }
+
+ int length = array.length;
+
+ if ( 0 == length )
+ {
+ return EMPTY_ARRAY;
+ }
+
+ final StringBuilder buffer = new StringBuilder();
+ for( int i=0 ; i<length ; ++i)
+ {
+ if ( 0 == i )
+ {
+ buffer.append( ARRAY_START );
+ }
+ else
+ {
+ buffer.append( ARRAY_ELEMENT_SEPARATOR );
+ }
+
+ buffer.append( array[i] );
+ }
+ buffer.append( ARRAY_END );
+ return buffer.toString();
+ }
+
+ /**
+ * Converts <code>array</code> double[] to String.
+ *
+ * @param array double[] to convert
+ *
+ * @return converted String
+ */
+ public static
+ String
+ toString(
+ final double[] array
+ )
+ {
+ if ( null == array )
+ {
+ return NULL_STRING;
+ }
+
+ int length= array.length;
+
+ if ( 0 == length )
+ {
+ return EMPTY_ARRAY;
+ }
+
+ StringBuilder buffer = new StringBuilder();
+ for( int i=0 ; i<length ; ++i )
+ {
+ if ( 0 == i )
+ {
+ buffer.append( ARRAY_START);
+ }
+ else
+ {
+ buffer.append( ARRAY_ELEMENT_SEPARATOR);
+ }
+
+ buffer.append( array[i] );
+ }
+ buffer.append( ARRAY_END );
+ return buffer.toString();
+ }
+
+ /**
+ * Converts <code>array</code> float[] to String.
+ *
+ * @param array float[] to convert
+ *
+ * @return converted String
+ */
+ public static
+ String
+ toString(
+ final float[] array
+ )
+ {
+ if ( null == array )
+ {
+ return NULL_STRING;
+ }
+
+ int length = array.length;
+
+ if ( 0 == length )
+ {
+ return EMPTY_ARRAY;
+ }
+
+ final StringBuilder buffer = new StringBuilder();
+ for( int i=0 ; i < length ; ++i )
+ {
+ if ( 0 == i )
+ {
+ buffer.append( ARRAY_START );
+ }
+ else
+ {
+ buffer.append( ARRAY_ELEMENT_SEPARATOR );
+ }
+
+ buffer.append( array[i] );
+ }
+ buffer.append( ARRAY_END );
+ return buffer.toString();
+ }
+
+ /**
+ * Converts <code>array</code> Object[] to String.
+ *
+ * @param array Object[] to convert
+ *
+ * @return converted String
+ */
+ public static <T>
+ String
+ toString(
+ final T[] array
+ )
+ {
+ if ( null == array )
+ {
+ return NULL_STRING;
+ }
+
+ final int length = array.length;
+
+ if ( 0 == length )
+ {
+ return EMPTY_ARRAY;
+ }
+
+ final StringBuilder buffer= new StringBuilder();
+
+ buffer.append( ARRAY_START);
+ buffer.append( concatenate( array, ARRAY_ELEMENT_SEPARATOR ) );
+ buffer.append( ARRAY_END );
+ return buffer.toString();
+ }
+
+ /**
+ * Returns a String from <code>array</code> Object[] with String separator.
+ *
+ * @param array Object[] to combine
+ * @param separator the delimiter which is used when Object[] combined
+ *
+ * @return combined String
+ */
+ public static <E>
+ String
+ concatenate(
+ final E[] array,
+ final String separator
+ )
+ {
+ return concatenate( (null==array)?null:new ArrayIterator<E>( array ), separator );
+ }
+
+ /**
+ * Returns a String from col {@link Collection} with String separator.
+ *
+ * @param col {@link Collection} object to combine
+ * @param separator the delimiter which is used when {@link Collection} object combined
+ *
+ * @return combined String
+ */
+ public static <E>
+ String
+ concatenate(
+ final Collection<E> col,
+ final String separator
+ )
+ {
+ return concatenate( (null==col)?(null):col.iterator(), separator );
+ }
+
+ /**
+ * Returns a String from {@link Iterator} with String separator.
+ *
+ * @param iter {@link Iterator} to combine objects
+ * @param separator the delimiter which is used when {@link Iterator} combined
+ *
+ * @return combined String
+ */
+ public static <E>
+ String
+ concatenate(
+ Iterator<E> iter,
+ final String separator
+ )
+ {
+ if ( null == iter )
+ {
+ return NULL_STRING;
+ }
+
+ if ( !iter.hasNext() )
+ {
+ return EMPTY_ARRAY;
+ }
+
+ final StringBuilder buffer= new StringBuilder();
+ boolean bInit = false;
+
+ while ( iter.hasNext() )
+ {
+ Object obj = iter.next();
+ if ( bInit )
+ {
+ buffer.append( separator );
+ }
+ bInit = true;
+
+ buffer.append( toString( obj ) );
+ }
+ return buffer.toString();
+ }
+
+ /* Hash */
+ private static final int MULTIPLIER= 31;
+
+ private static final int INITIAL_HASH = 7;
+
+ /**
+ * Creates hash value about object.
+ * <br>
+ * In case of array, get hash value using object's hash value in the array.
+ *
+ * @param obj object to get hash value
+ *
+ * @return hash value
+ */
+ public static
+ int
+ hashCode(
+ final Object obj
+ )
+ {
+ if ( null == obj )
+ {
+ return 0;
+ }
+ if ( obj.getClass().isArray() )
+ {
+ if ( obj instanceof Object[] )
+ {
+ return hashCode( (Object[] )obj );
+ }
+ else if ( obj instanceof boolean[] )
+ {
+ return hashCode( (boolean[] )obj );
+ }
+ else if ( obj instanceof byte[] )
+ {
+ return hashCode( (byte[] )obj);
+ }
+ else if ( obj instanceof char[] )
+ {
+ return hashCode( (char[] )obj);
+ }
+ else if ( obj instanceof double[] )
+ {
+ return hashCode( (double[] )obj);
+ }
+ else if ( obj instanceof float[] )
+ {
+ return hashCode( (float[] )obj);
+ }
+ else if ( obj instanceof int[] )
+ {
+ return hashCode( (int[] )obj);
+ }
+ else if ( obj instanceof long[] )
+ {
+ return hashCode( (long[] )obj);
+ }
+ else if ( obj instanceof short[] )
+ {
+ return hashCode( (short[] )obj);
+ }
+ }
+
+ return obj.hashCode();
+ }
+
+ /**
+ * Returns hash value about <code>array</code> Object[].
+ *
+ * @param array Object[] to get hash value
+ *
+ * @return hash value
+ */
+ public static
+ int
+ hashCode(
+ final Object[] array
+ )
+ {
+ if ( null == array )
+ {
+ return 0;
+ }
+
+ int hash = INITIAL_HASH;
+ for( int i=0, arraySize=array.length ; i<arraySize ; ++i )
+ {
+ hash = MULTIPLIER * hash + hashCode( array[i] );
+ }
+
+ return hash;
+ }
+
+ /**
+ * Returns hash value about <code>array</code> boolean[].
+ *
+ * @param array boolean[] to get hash value
+ *
+ * @return hash value
+ */
+ public static
+ int
+ hashCode(
+ final boolean[] array
+ )
+ {
+ if ( null == array )
+ {
+ return 0;
+ }
+
+ int hash = INITIAL_HASH;
+ for( int i=0, arraySize=array.length ; i<arraySize ; ++i )
+ {
+ hash = MULTIPLIER * hash + hashCode( array[i] );
+ }
+
+ return hash;
+ }
+
+ /**
+ * Returns hash value about <code>array</code> int[].
+ *
+ * @param array int[] to get hash value
+ *
+ * @return hash value
+ */
+ public static int
+ hashCode(
+ final byte[] array
+ )
+ {
+ if ( null == array )
+ {
+ return 0;
+ }
+
+ int hash = INITIAL_HASH;
+ for( int i=0, arraySize=array.length ; i<arraySize ; ++i )
+ {
+ hash = MULTIPLIER * hash + array[i];
+ }
+
+ return hash;
+ }
+
+ /**
+ * Returns hash value about <code>array</code> char[].
+ *
+ * @param array char[] to get hash value
+ *
+ * @return hash value
+ */
+ public static
+ int
+ hashCode(
+ final char[] array
+ )
+ {
+ if ( null == array )
+ {
+ return 0;
+ }
+
+ int hash = INITIAL_HASH;
+ for( int i=0, arraySize=array.length ; i<arraySize ; ++i )
+ {
+ hash = MULTIPLIER * hash + hashCode( array[i] );
+ }
+
+ return hash;
+ }
+
+ /**
+ * Returns hash value about <code>array</code> double[].
+ *
+ * @param array double[] to get hash value
+ *
+ * @return hash value
+ */
+ public static
+ int
+ hashCode(
+ final double[] array
+ )
+ {
+ if ( null == array )
+ {
+ return 0;
+ }
+
+ int hash = INITIAL_HASH;
+ for( int i=0, arraySize=array.length ; i<arraySize ; ++i )
+ {
+ hash = MULTIPLIER * hash + hashCode( array[i] );
+ }
+
+ return hash;
+ }
+
+ /**
+ * Returns hash value about <code>array</code> float[].
+ *
+ * @param array float[] to get hash value
+ *
+ * @return hash value
+ */
+ public static
+ int
+ hashCode(
+ final float[] array
+ )
+ {
+ if ( null == array )
+ {
+ return 0;
+ }
+
+ int hash = INITIAL_HASH;
+ for( int i=0, arraySize=array.length ; i<arraySize ; ++i )
+ {
+ hash = MULTIPLIER * hash + hashCode( array[i] );
+ }
+
+ return hash;
+ }
+
+ /**
+ * Returns hash value about <code>array</code> int[].
+ *
+ * @param array int[] to get hash value
+ *
+ * @return hash value
+ */
+ public static
+ int
+ hashCode(
+ final int[] array
+ )
+ {
+ if ( null == array )
+ {
+ return 0;
+ }
+
+ int hash = INITIAL_HASH;
+ for( int i=0, arraySize=array.length ; i<arraySize ; ++i )
+ {
+ hash = MULTIPLIER * hash + hashCode( array[i] );
+ }
+
+ return hash;
+ }
+
+ /**
+ * Returns hash value about <code>array</code> long[].
+ *
+ * @param array long[] to get hash value
+ *
+ * @return hash value
+ */
+ public static
+ int
+ hashCode(
+ final long[] array
+ )
+ {
+ if ( null == array )
+ {
+ return 0;
+ }
+
+ int hash = INITIAL_HASH;
+ for( int i=0, arraySize=array.length ; i<arraySize ; ++i )
+ {
+ hash = MULTIPLIER * hash + hashCode( array[i] );
+ }
+
+ return hash;
+ }
+
+ /**
+ * Returns hash value about <code>array</code> short[].
+ *
+ * @param array short[] to get hash value
+ *
+ * @return hash value
+ */
+ public static
+ int
+ hashCode(
+ final short[] array
+ )
+ {
+ if ( null == array )
+ {
+ return 0;
+ }
+
+ int hash = INITIAL_HASH;
+ for( int i=0, arraySize=array.length ; i<arraySize ; ++i )
+ {
+ hash = MULTIPLIER * hash + hashCode( array[i] );
+ }
+
+ return hash;
+ }
+
+ /**
+ * Returns hash value about <code>bool</code> boolean.
+ *
+ * @param bool boolean type parameter to get hash value
+ *
+ * @return hash value
+ */
+ public static
+ int
+ hashCode(
+ final boolean bool
+ )
+ {
+ return bool ? 1231 : 1237;
+ }
+
+ /**
+ * Return hash value about <code>dbl</code> double.
+ *
+ * @param dbl double type parameter to get hash value
+ *
+ * @return hash value
+ */
+ public static
+ int
+ hashCode(
+ final double dbl
+ )
+ {
+ long bits = Double.doubleToLongBits( dbl );
+ return hashCode( bits );
+ }
+
+ /**
+ * Returns hash value about <code>flt</code> float.
+ *
+ * @param flt float type parameter to get hash value
+ *
+ * @return hash value
+ */
+ public static
+ int
+ hashCode(
+ float flt
+ )
+ {
+ return Float.floatToIntBits( flt );
+ }
+
+
+ /**
+ * Returns hash value about <code>lng</code> long.
+ *
+ * @param lng long type parameter to get hash value
+ *
+ * @return hash value
+ */
+ public static
+ int
+ hashCode(
+ final long lng
+ )
+ {
+ return (int) ( lng ^ ( lng >>> 32 ) );
+ }
+
+ /* Equals */
+ /**
+ * Returns whether it is same object type or not by comparing each column's type of {@link Collection} object.
+ *
+ * @param <K> object type about {@link Collection}
+ * @param cols {@link Collection} objects
+ *
+ * @return true if each column's type of the {@link Collection} object is same
+ */
+ @SuppressWarnings("unchecked")
+ public static <K>
+ boolean
+ equals(
+ final Collection<? extends K>... cols
+ )
+ {
+
+ // flag if collection is null
+ boolean bInit = false;
+ int size = 0;
+ for ( final Collection<? extends K> col : cols )
+ {
+ if ( !bInit )
+ {
+ if ( null == col )
+ {
+ size = -1;
+ }
+ else
+ {
+ size = col.size();
+ }
+ bInit = true;
+ }
+ if ( size < 0 )
+ {
+ if ( null != col )
+ {
+ return false;
+ }
+ }
+ else if ( null == col || col.size() != size )
+ {
+ return false;
+ }
+ }
+ if ( size < 0 )
+ {
+ return true;
+ }
+
+ final Iterator<? extends K>[] iters = new Iterator[cols.length];
+ for ( int i = 0, n = iters.length ; i<n ; ++i )
+ {
+ iters[i] = cols[i].iterator();
+ }
+
+ while ( iters[0].hasNext() )
+ {
+ final K obj = iters[0].next();
+ for ( int i = 1, n = iters.length ; i<n ; ++i )
+ {
+ final K other = iters[i].next();
+
+ if ( !ObjectUtil.equals( obj, other ) )
+ {
+ return false;
+ }
+ }
+ }
+
+ return true;
+ }
+
+ /**
+ * Returns whether it is same object type or not by comparing each column's type of Object[].
+ *
+ * @param objsVar target objects
+ *
+ * @return true if each column's type of the Object[] is same
+ *
+ */
+ public static
+ boolean
+ equals(
+ final Object[]... objsVar
+ )
+ {
+ // flag if collection is null
+ boolean bInit = false;
+ int size = 0;
+ for ( final Object[] objs : objsVar )
+ {
+ if ( !bInit )
+ {
+ if ( null == objs )
+ {
+ size = -1;
+ }
+ else
+ {
+ size = objs.length;
+ }
+ bInit = true;
+ }
+ if ( size < 0 )
+ {
+ if ( null != objs )
+ {
+ return false;
+ }
+ }
+ else if ( null == objs || objs.length != size )
+ {
+ return false;
+ }
+ }
+ if ( size < 0 )
+ {
+ return true;
+ }
+
+
+ for ( int i=1, n=objsVar.length ; i<n ; ++i )
+ {
+ for ( int j=0 ; j<size ; ++j )
+ {
+ if ( !ObjectUtil.equals( objsVar[0][j], objsVar[i][j] ) )
+ {
+ return false;
+ }
+ }
+ }
+ return true;
+
+ }
+
+ /**
+ * <p>
+ * Swaps <code><I>i</I></code>th object's location with <code><I>j</I></code>th object in <code>objs</code> Object[].
+ * </p>
+ * @param objs target
+ * @param i location of object to be swapped
+ * @param j location of object to be swapped
+ */
+ public static
+ void
+ swap(
+ final Object[] objs,
+ final int i,
+ final int j
+ )
+ {
+ Object temp = objs[i];
+ objs[i] = objs[j];
+ objs[j] = temp;
+ }
+}
diff --git a/org.tizen.common/src/org/tizen/common/util/ControlFileConfig.java b/org.tizen.common/src/org/tizen/common/util/ControlFileConfig.java
index c0cb6f545..8e7ddb603 100644
--- a/org.tizen.common/src/org/tizen/common/util/ControlFileConfig.java
+++ b/org.tizen.common/src/org/tizen/common/util/ControlFileConfig.java
@@ -75,8 +75,10 @@ public class ControlFileConfig {
public boolean store(){
File folder = new File(this.path).getParentFile();
- if(folder==null||!folder.exists())
+ if( !folder.exists() )
+ {
folder.mkdirs();
+ }
this.isExist = PropertyUtil.storeProperties(path, props);
return this.isExist;
diff --git a/org.tizen.common/src/org/tizen/common/util/DialogUtil.java b/org.tizen.common/src/org/tizen/common/util/DialogUtil.java
index 3335ba125..8961df713 100644
--- a/org.tizen.common/src/org/tizen/common/util/DialogUtil.java
+++ b/org.tizen.common/src/org/tizen/common/util/DialogUtil.java
@@ -26,7 +26,6 @@
package org.tizen.common.util;
import org.eclipse.swt.SWT;
-import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
@@ -48,7 +47,7 @@ public abstract class DialogUtil {
}
public static void openMessageDialog(final Shell shell, final String title, final String message) {
- Display.getDefault().syncExec(new Runnable() {
+ SWTUtil.syncExec(new Runnable() {
public void run() {
MessageBox dialog = new MessageBox(shell, SWT.OK | SWT.ICON_INFORMATION);
dialog.setText(title);
@@ -60,7 +59,7 @@ public abstract class DialogUtil {
public static void openProxyDialog(final String text, String message) {
final String msg = message;
- Display.getDefault().syncExec(new Runnable() {
+ SWTUtil.syncExec(new Runnable() {
public void run() {
MessageBox dialog = new MessageBox(new Shell(), SWT.ERROR | SWT.ICON_INFORMATION);
dialog.setText(text);
@@ -83,7 +82,7 @@ public abstract class DialogUtil {
}
public static void openErrorDialog(final Shell shell, final String title, final String message) {
- Display.getDefault().syncExec(new Runnable() {
+ SWTUtil.syncExec(new Runnable() {
public void run() {
MessageBox dialog = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR);
dialog.setText(title);
@@ -106,7 +105,7 @@ public abstract class DialogUtil {
public static int openQuestionDialog(String message) {
synchronized (lockQuestion) {
final String msg = message;
- Display.getDefault().syncExec(new Runnable() {
+ SWTUtil.syncExec(new Runnable() {
public void run() {
MessageBox dialog = new MessageBox(new Shell(), SWT.YES | SWT.NO | SWT.ICON_QUESTION);
dialog.setMessage(msg);
diff --git a/org.tizen.common/src/org/tizen/common/util/EFSUtil.java b/org.tizen.common/src/org/tizen/common/util/EFSUtil.java
new file mode 100755
index 000000000..47d33ea06
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/util/EFSUtil.java
@@ -0,0 +1,303 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* Jihoon Song <jihoon80.song@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+
+package org.tizen.common.util;
+
+import java.net.URI;
+
+import org.eclipse.core.filesystem.EFS;
+import org.eclipse.core.filesystem.IFileStore;
+import org.eclipse.core.filesystem.IFileSystem;
+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.jface.dialogs.MessageDialog;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.ui.internal.ide.dialogs.IDEResourceInfoUtils;
+import org.eclipse.ui.internal.ide.dialogs.IFileStoreFilter;
+import org.tizen.common.Surrogate;
+import org.tizen.common.core.application.Messages;
+
+/**
+ * EFSUtil.
+ *
+ * Helper related to Eclipse File System
+ *
+ * @author Jihoon Song{@literal <jihoon80.song@samsung.com>} (S-Core)
+ */
+public class EFSUtil {
+
+ public enum DialogChoicer {
+ YesToAll,
+ NoToAll,
+ Yes,
+ No,
+ Cancel;
+
+ /**
+ * Get DialogChoicer's all value
+ *
+ * @return String array with DialogChoicer's values
+ */
+ public static String[] toStringArray() {
+ DialogChoicer[] choicers = DialogChoicer.values();
+ String[] values = new String[choicers.length];
+ for (DialogChoicer choicer : choicers) {
+ values[choicer.ordinal()] = choicer.name();
+ }
+ return values;
+ }
+
+ public static DialogChoicer valueFromOrdinal(int ordinal) {
+ for (DialogChoicer choicer : values()) {
+ if (choicer.ordinal() == ordinal) {
+ return choicer;
+ }
+ }
+ return DialogChoicer.Cancel;
+ }
+ }
+
+ private static Surrogate<IFileSystem> fileSystemSurrogate = new Surrogate<IFileSystem>() {
+ @Override
+ public IFileSystem getAdapter() {
+ return EFS.getLocalFileSystem();
+ }
+ };
+
+ private static final String defaultTask = ""; //$NON-NLS-1$
+ private static final int defaultTicks = 100; // TODO : will add automatically calculate method
+
+ private static final IFileStoreFilter defaultFilter = new IFileStoreFilter() {
+ @Override
+ public boolean accept(IFileStore store) {
+ return true;
+ }
+ };
+
+
+ // Constructor
+ private EFSUtil() {}
+
+ public static void setFileSystemSurrogate(Surrogate<IFileSystem> surrogate) {
+ EFSUtil.fileSystemSurrogate = surrogate;
+ }
+
+ /**
+ * Get IFileSystem based on Surrogate<IFileSystem> for this class
+ *
+ * @return IFileStoreFilter
+ */
+ protected static IFileSystem getFileSystem() {
+ return fileSystemSurrogate.getAdapter();
+ }
+
+ /**
+ * Get a default IFileStoreFilter that always returns true
+ *
+ * @return IFileStoreFilter
+ */
+ public static IFileStoreFilter getDefaultFileStoreFilter() {
+ return defaultFilter;
+ }
+
+ /**
+ * Detect whether resource exist.
+ *
+ * @param fileURI
+ */
+ public static boolean isExistResource(URI fileURI) {
+ IFileStore fileStore = getFileSystem().getStore(fileURI);
+ return isExistResource(fileStore);
+ }
+
+ /**
+ * Detect whether resource exist.
+ *
+ * @param fileStore
+ */
+ public static boolean isExistResource(IFileStore fileStore) {
+ return (fileStore != null) ? fileStore.fetchInfo().exists() : false;
+ }
+
+ /**
+ * Detect whether resource exist. if exist this, open dialog
+ *
+ * @param parentShell dialog's parent shell
+ * @param title dialog title
+ * @param msg dialog message
+ * @param previousChoice previous DialogChoicer value
+ * @param fileStore
+ * @return in case of previousChoice is Yes or No, return user choice status. any else return previous status
+ */
+ public static DialogChoicer isExistResourceWithDialog(Shell parentShell,
+ String title, String msg, DialogChoicer previousChoice, IFileStore fileStore) {
+
+ Assert.notNull(parentShell);
+ Assert.notNull(msg);
+ Assert.notNull(previousChoice);
+ Assert.notNull(fileStore);
+
+ switch (previousChoice) {
+ case Yes :
+ case No :
+ break;
+ case YesToAll :
+ case NoToAll :
+ case Cancel :
+ default :
+ return previousChoice;
+ }
+
+ if (isExistResource( fileStore )) {
+ MessageDialog msgDialog = new MessageDialog(parentShell,
+ title, null, msg, MessageDialog.NONE, DialogChoicer.toStringArray(),
+ DialogChoicer.Cancel.ordinal());
+
+ int msgResult = msgDialog.open();
+
+ return DialogChoicer.valueFromOrdinal(msgResult);
+ }
+
+ return DialogChoicer.Yes;
+ }
+
+ /**
+ * Copy file or directory using Eclipse File System
+ *
+ * @param source the source URI of the copy. If null, NullPointerException occur.
+ * @param destination the destination URI of the copy. If null, NullPointerException occur.
+ * @param options bit-wise or of option flag constants ({@link EFS#OVERWRITE} or {@link EFS#SHALLOW}).
+ * @param monitor a progress monitor, or <code>null</code> if progress reporting and cancellation are not desired
+ *
+ * @author Jihoon Song {@literal <jihoon80.song@samsung.com>} (S-Core)
+ */
+ public static void copy(URI source, URI destination, int options,
+ IProgressMonitor monitor) throws CoreException {
+ Assert.notNull(source);
+ Assert.notNull(destination);
+
+ monitor = ObjectUtil.nvl(monitor, new NullProgressMonitor());
+
+ try {
+ monitor.beginTask(defaultTask, defaultTicks);
+
+ getFileSystem().getStore(source).copy(getFileSystem().getStore( destination ), options, monitor);
+ } finally {
+ monitor.done();
+ }
+ }
+
+ /**
+ * Copy file or directory using EFS with IFileStoreFilter.
+ * If file already exist, open selectable message dialog.
+ * If the user selected Cancel, OperationCanceledException occur
+ *
+ * @param source the source URI of the copy. If null, NullPointerException occur.
+ * @param destination the destination URI of the copy. If null, NullPointerException occur.
+ * @param fileFilter the child file filter in source, if <code>null</code>, the default file filter is used
+ * @param monitor a progress monitor, or <code>null</code> if progress reporting and cancellation are not desired
+ * @throws CoreException
+ */
+ public static DialogChoicer copyWithFilter(URI source, URI destination, IFileStoreFilter fileFilter,
+ IProgressMonitor monitor) throws CoreException {
+ return copyWithFilter(source, destination, fileFilter, DialogChoicer.Yes, monitor);
+ }
+
+ /**
+ * Copy file or directory using EFS with IFileStoreFilter.
+ * If file already exist, open selectable message dialog.
+ * If the user selected Cancel, OperationCanceledException occur
+ *
+ * @param source the source URI of the copy. If null, NullPointerException occur.
+ * @param destination the destination URI of the copy. If null, NullPointerException occur.
+ * @param fileFilter the child file filter in source, if <code>null</code>, the default file filter is used
+ * @param previousChoice apply user configuration. if YesToAll or NoToAll, don't ask your choice.
+ * @param monitor a progress monitor, or <code>null</code> if progress reporting and cancellation are not desired
+ * @throws CoreException
+ */
+ public static DialogChoicer copyWithFilter(URI source, URI destination, IFileStoreFilter fileFilter,
+ DialogChoicer previousChoice, IProgressMonitor monitor) throws CoreException {
+ Assert.notNull(source);
+ Assert.notNull(destination);
+
+ monitor = ObjectUtil.nvl(monitor, new NullProgressMonitor());
+
+ try {
+ monitor.beginTask(defaultTask, defaultTicks);
+
+ // fileFilter must be not null, because IDEResourceInfoUtils don't check null.
+ if (fileFilter == null) {
+ fileFilter = getDefaultFileStoreFilter();
+ }
+
+ return internalCopyWithFilter(getFileSystem().getStore( source ),
+ getFileSystem().getStore( destination ),
+ fileFilter, previousChoice, monitor);
+ } finally {
+ monitor.done();
+ }
+ }
+
+ private static DialogChoicer internalCopyWithFilter(IFileStore source, IFileStore destination,
+ IFileStoreFilter fileFilter, DialogChoicer previousChoice, IProgressMonitor monitor)
+ throws CoreException {
+ Assert.notNull(source);
+ Assert.notNull(destination);
+
+ previousChoice = isExistResourceWithDialog(
+ ViewUtil.getWorkbenchWindow().getShell(), Messages.FileExistDialogTitle,
+ Messages.bind( Messages.FileExistMsg, destination.getName() ),
+ previousChoice, destination);
+
+ switch (previousChoice) {
+ case YesToAll :
+ case Yes :
+ source.copy(destination, EFS.OVERWRITE | EFS.SHALLOW, monitor);
+ break;
+ case Cancel :
+ throw new OperationCanceledException();
+ case NoToAll :
+ case No :
+ break;
+ default:
+ break;
+ }
+ monitor.worked(1);
+
+ // traverse child resources
+ if (source.fetchInfo().isDirectory()) {
+ IFileStore[] childStores = IDEResourceInfoUtils.listFileStores(source, fileFilter, null);
+ for (IFileStore childStore : childStores) {
+ previousChoice = internalCopyWithFilter(childStore,
+ destination.getChild( childStore.getName() ),
+ fileFilter, previousChoice, monitor);
+ }
+ }
+
+ return previousChoice;
+ }
+}
diff --git a/org.tizen.common/src/org/tizen/common/util/FileUtil.java b/org.tizen.common/src/org/tizen/common/util/FileUtil.java
index eca82e5b4..59befe244 100644
--- a/org.tizen.common/src/org/tizen/common/util/FileUtil.java
+++ b/org.tizen.common/src/org/tizen/common/util/FileUtil.java
@@ -1,29 +1,31 @@
/*
-* Common
-*
-* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
-*
-* Contact:
-* Kangho Kim <kh5325.kim@samsung.com>
-*
-* 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.
-*
-* Contributors:
-* - S-Core Co., Ltd
-*
-*/
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * Kangho Kim <kh5325.kim@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
package org.tizen.common.util;
+import static org.tizen.common.util.IOUtil.tryClose;
+
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
@@ -36,49 +38,174 @@ import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
-import java.net.URI;
-
-import org.eclipse.core.filesystem.EFS;
-import org.eclipse.core.filesystem.IFileSystem;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
+import org.tizen.common.util.log.Logger;
/**
* @author Changhyun Lee {@literal <changhyun1.lee@samsung.com>} (S-Core)
*/
public class FileUtil {
- public static final String UTF_8 = "UTF-8"; //$NON-NLS-1$
-
private static final int BUFFER_SIZE = 8192;
/**
+ * Create directory.
+ * @param dir
+ * @return If directory couldn't be created, return false. Otherwise, return true.
+ */
+ public static boolean createDirectory(File dir) {
+ return dir.mkdirs();
+ }
+
+ /**
+ * Create directory.
+ * @param fullPath
+ * @return If directory couldn't be created, return false. Otherwise, return true.
+ */
+ public static boolean createDirectory(String fullPath) {
+ return createDirectory(new File(fullPath));
+ }
+
+ /**
+ * Create directory.
+ * @param dirName
+ * @param destDir If destDir is not set(null), then use user's current directory.
+ * @return If directory couldn't be created, return false. Otherwise, return true.
+ */
+ public static boolean createDirectory(String dirName, String destDir) {
+ if (dirName == null)
+ throw new NullPointerException();
+
+ if (destDir == null)
+ destDir = System.getProperty("user.dir");
+
+ String fullPath = FilenameUtil.addTailingPath(destDir, dirName);
+
+ return createDirectory(new File(fullPath));
+ }
+
+ /**
+ * Create text file.
+ *
+ * @param file
+ * @param text Input file's context.
+ * @param encoding If encoding is not set(null), then use system's default encoding.
+ *
+ * @return If file create fail, return false. Otherwise, return true.
+ *
+ * @throws IOException If creating file's directory does not exist, it throws IOException
+ */
+ public static boolean createTextFile(File file, String text, String encoding) throws IOException {
+ if (!file.createNewFile())
+ return false;
+
+ return writeTextFile(file, text, encoding);
+ }
+
+ /**
+ * Create text file.
+ *
+ * @param fullPath
+ * @param text Input file's context.
+ * @param encoding If encoding is not set(null), then use system's default encoding.
+ *
+ * @return If file create fail, return false. Otherwise, return true.
+ *
+ * @throws IOException If creating file's directory does not exist, it throws IOException
+ */
+ public static boolean createTextFile(String fullPath, String text, String encoding) throws IOException {
+ return createTextFile(new File(fullPath), text, encoding);
+ }
+
+ /**
+ * Create text file.
+ *
+ * @param fileName
+ * @param text Input file's context.
+ * @param destDir If destDir is not set(null), then use user's current directory.
+ * @param encoding If encoding is not set(null), then use system's default encoding.
+ *
+ * @return If file create fail, return false. Otherwise, return true.
+ *
+ * @throws IOException If creating file's directory does not exist, it throws IOException
+ */
+ public static boolean createTextFile(String fileName, String text, String destDir, String encoding) throws IOException {
+ if (fileName == null)
+ throw new NullPointerException();
+
+ if (destDir == null)
+ destDir = System.getProperty("user.dir");
+
+ String fullPath = FilenameUtil.addTailingPath(destDir, fileName);
+
+ return createTextFile(fullPath, text, encoding);
+ }
+
+ /**
* write text into given file
+ *
+ * @param file
+ * @param text Input context
+ * @param encoding If encoding is not set(null), then use system's default encoding.
+ *
+ * @return If file write success, return true.
+ *
+ * @throws IOException If don't write file, it throws IOException
*/
- public static void writeTextFile(File file, String text, String encoding) throws IOException {
- BufferedWriter out = null;
-
+ public static boolean writeTextFile(File file, String text, String encoding) throws IOException {
if (encoding == null) { // if encoding is not set then use default encoding
encoding = System.getProperty("file.encoding");
}
-
+
+ File parent = file.getParentFile();
+ if (!parent.exists()) {
+ if (!parent.mkdirs()) {
+ throw new IOException("File write error. Cannot create directory - " + parent.getAbsolutePath());
+ }
+ }
+
+ BufferedWriter out = null;
try {
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), encoding), BUFFER_SIZE);
out.write(text.toCharArray(), 0, text.length());
out.flush();
+ } catch (IOException e) {
+ throw e;
} finally {
if (out != null) {
out.close();
}
}
+
+ return true;
}
/**
- * read text from given file
+ * Read text from given file.
+ *
+ * @param file
+ * @param encoding
+ *
+ * @return content from file
+ *
+ * @throws IOException
*/
public static String readTextFile(File file, String encoding) throws IOException {
+ return readTextStream(new FileInputStream(file), encoding);
+ }
+
+ /**
+ * Read text from given inputStream.
+ *
+ * @param input
+ * @param encoding
+ *
+ * @return content from input
+ *
+ * @throws IOException
+ *
+ */
+ public static String readTextStream(InputStream input, String encoding) throws IOException {
StringBuilder text = new StringBuilder();
- char[] buffer = new char[BUFFER_SIZE];
BufferedReader in = null;
if (encoding == null) { // if encoding is not set then use default encoding
@@ -86,15 +213,10 @@ public class FileUtil {
}
try {
- in = new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding), BUFFER_SIZE);
- int nRead = 0;
- while ((nRead = in.read(buffer, 0, buffer.length)) > 0) {
- text.append(buffer, 0, nRead);
- }
+ in = new BufferedReader(new InputStreamReader(input, encoding), BUFFER_SIZE);
+ IOUtil.redirect( in, text );
} finally {
- if (in != null) {
- in.close();
- }
+ IOUtil.tryClose( in );
}
return text.toString();
@@ -126,7 +248,7 @@ public class FileUtil {
}
int k = fullName.lastIndexOf(".");
-
+
return (k != -1) ? fullName.substring(0, k) : fullName;
}
@@ -157,21 +279,6 @@ public class FileUtil {
}
/**
- * copy file or directory using Eclipse File System
- *
- * @param source The source URI of the copy.
- * @param destination The destination URI of the copy.
- * @param options bit-wise or of option flag constants ({@link EFS#OVERWRITE} or {@link EFS#SHALLOW}).
- * @param monitor a progress monitor, or <code>null</code> if progress reporting and cancellation are not desired
- *
- * @author Jihoon Song {@literal <jihoon80.song@samsung.com>} (S-Core)
- */
- public static void copyUsingEFS(URI source, URI destination, int options, IProgressMonitor monitor) throws CoreException {
- IFileSystem fileSystem = EFS.getLocalFileSystem();
- fileSystem.getStore(source).copy(fileSystem.getStore(destination), options, monitor);
- }
-
- /**
* redirect input stream to output stream
*/
public static void redirectStream(InputStream is, OutputStream os) throws IOException {
@@ -218,7 +325,8 @@ public class FileUtil {
}
// makes sure it is not the same file
- if (fromFile.getCanonicalPath().equals(toFile.getCanonicalPath())) {
+ if ( FilenameUtil.equals( fromFile, toFile ) )
+ {
throw new IOException("Unable to write file " + fromFile + " on itself.");
}
@@ -229,14 +337,80 @@ public class FileUtil {
in = new BufferedInputStream(new FileInputStream(fromFile), BUFFER_SIZE);
out = new BufferedOutputStream(new FileOutputStream(to, append), BUFFER_SIZE);
- byte[] bytes = new byte[BUFFER_SIZE];
- int nRead = 0;
- while ((nRead = in.read(bytes, 0, bytes.length)) > 0) {
- out.write(bytes, 0, nRead);
- }
+ IOUtil.redirect( in, out );
} finally {
- if (in != null) in.close();
- if (out != null) out.close();
+ tryClose( in, out );
}
}
+
+ /**
+ * Copy all the files in the source directory to the destination directory.
+ * If destination directory does not exist, it is created.
+ * If destination file already exists , it tries to overwrite it.
+ *
+ * @param from source directory path
+ * @param to destination directory path
+ * @throws IOException
+ */
+ public static void copyRecursively(String from, String to) throws IOException {
+ File fromDir = new File(from);
+ File toDir = new File(to);
+ if (fromDir.exists() == false) {
+ Logger.error("Directory " + fromDir.getCanonicalPath() + " does not exist.");
+ return;
+ }
+ checkDirectory(fromDir, toDir);
+ copyRecursivelyWithoutDirChecking(fromDir, toDir);
+ }
+
+ private static void checkDirectory(File fromDir, File toDir) throws IOException {
+ if (toDir.exists() == false) {
+ toDir.mkdirs();
+ } else if(toDir.isFile() == true) {
+ throw new IOException("destination directory " + toDir.toString() + " is a file.");
+ }
+
+ if (fromDir.exists() == false) {
+ throw new IOException("source directory " + fromDir.toString() + " does not exist.");
+ }
+
+ if (fromDir.isFile() == true) {
+ throw new IOException("source directory " + fromDir.toString() + " is a file.");
+ }
+ }
+
+ private static void copyRecursivelyWithoutDirChecking(File fromDir, File toDir) throws IOException {
+ for(File fromFile: fromDir.listFiles()) {
+ String newDestPath = toDir.getCanonicalPath();
+ if(newDestPath.endsWith(File.separator)) {
+ newDestPath = newDestPath + fromFile.getName();
+ } else {
+ newDestPath = newDestPath + File.separator + fromFile.getName();
+ }
+
+ File toFile = new File(newDestPath);
+ if(fromFile.isDirectory()) {
+ copyRecursivelyWithoutDirChecking(fromFile, toFile);
+ } else if(fromFile.isFile()){
+ copyTo(fromFile.getCanonicalPath(), newDestPath);
+ }
+ }
+ }
+
+ /**
+ * Compares the two files "file1" and "file2".
+ */
+ public static boolean equals(File file1, File file2) throws IOException {
+ if ( file1 == null || file2 == null) {
+ return false;
+ }
+ String strFile1 = file1.getCanonicalPath();
+ String strFile2 = file2.getCanonicalPath();
+
+ if ( strFile1 == null || strFile2 == null ) {
+ return false;
+ }
+
+ return strFile1.equals(strFile2);
+ }
}
diff --git a/org.tizen.common/src/org/tizen/common/util/FilenameUtil.java b/org.tizen.common/src/org/tizen/common/util/FilenameUtil.java
new file mode 100755
index 000000000..ef4d64843
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/util/FilenameUtil.java
@@ -0,0 +1,422 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* BonYong Lee <bonyong.lee@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+package org.tizen.common.util;
+
+import static org.tizen.common.util.ArrayUtil.size;
+import static org.tizen.common.util.StringUtil.trimLeadingCharacter;
+import static org.tizen.common.util.StringUtil.trimTrailingCharacter;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.regex.Pattern;
+
+/**
+ * FilenameUtil.
+ *
+ * Helper related to file name
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ */
+public class FilenameUtil
+{
+ public static final char SEPARATOR_DIRECTORY = '/';
+ public static final int IS_VALID_NAME = 0;
+ public static final int HAS_INVALID_CHARACTER = 1;
+ public static final int HAS_NO_NAME = 2;
+ public static final int IS_NULL = 3;
+
+ /**
+ * Separate path to directory name fragements
+ *
+ * @param path file path
+ *
+ * @return canonical path's fragements
+ */
+ public static
+ String[]
+ getCanonicalFragments( final String path )
+ {
+ final String safe = path.replace( File.separatorChar, SEPARATOR_DIRECTORY);
+ final ArrayList<String> ret = new ArrayList<String>();
+ for ( final String fragment : safe.split( "" + SEPARATOR_DIRECTORY ) )
+ {
+ if ( StringUtil.isEmpty( fragment ) )
+ {
+ continue;
+ }
+
+ ret.add( fragment );
+ }
+ return ret.toArray( new String[0] );
+ }
+
+ public static
+ String
+ getTailingPath(
+ final String path,
+ final int start
+ )
+ {
+ final String[] fragments = getCanonicalFragments( path );
+
+ final StringBuilder buffer = new StringBuilder();
+
+ for ( int i = Math.max( 0, size( fragments ) - start ), n = size( fragments ) ; i < n ; ++i )
+ {
+ buffer.append( fragments[i] );
+ if ( i < size( fragments ) - 1 )
+ {
+ buffer.append( SEPARATOR_DIRECTORY );
+ }
+ }
+
+ return buffer.toString();
+ }
+
+ public static
+ String
+ removeTailingPath(
+ final String path,
+ final int numberOfPath
+ )
+ {
+ final String[] fragments = getCanonicalFragments( path );
+
+ final StringBuilder buffer = new StringBuilder();
+
+ for ( int i = 0, n = Math.max( 0, size( fragments ) - numberOfPath ) ; i < n ; ++i )
+ {
+ buffer.append( SEPARATOR_DIRECTORY );
+ buffer.append( fragments[i] );
+ }
+
+ return buffer.toString();
+ }
+
+ public static
+ String
+ addTailingPath(
+ final String path,
+ final String pathToAdd
+ )
+ {
+ // TODO Verify canonical form
+ return trimTrailingCharacter( path, SEPARATOR_DIRECTORY ) + SEPARATOR_DIRECTORY + trimLeadingCharacter( pathToAdd, SEPARATOR_DIRECTORY );
+ }
+
+ public static
+ boolean
+ isAncestor( final String root, final String filePath )
+ {
+ final String[] rootFragments = FilenameUtil.getCanonicalFragments( root );
+ final String[] fileFragments = FilenameUtil.getCanonicalFragments( filePath );
+
+ if ( fileFragments.length < rootFragments.length )
+ {
+ return false;
+ }
+
+ for ( int i = 0, n = rootFragments.length ; i < n ; ++i )
+ {
+ if ( !ObjectUtil.equals( rootFragments[i], fileFragments[i] ) )
+ {
+ return false;
+ }
+ }
+
+
+ return true;
+ }
+
+ public static
+ String
+ getRelativePath(
+ final String root,
+ final String filePath
+ )
+ {
+ final String[] rootFragments = FilenameUtil.getCanonicalFragments( root );
+ final String[] fileFragments = FilenameUtil.getCanonicalFragments( filePath );
+
+ Assert.isTrue(
+ rootFragments.length < fileFragments.length,
+ "root must be ancestor[" + root + "] of path[" + filePath + "]"
+ );
+
+ for ( int i = 0, n = rootFragments.length ; i < n ; ++i )
+ {
+ Assert.isTrue( ObjectUtil.equals( rootFragments[i], fileFragments[i] ) );
+ }
+
+
+
+ final StringBuilder buffer = new StringBuilder();
+
+ for ( int i = rootFragments.length, n = fileFragments.length ; i < n ; ++i )
+ {
+ if ( rootFragments.length < i )
+ {
+ buffer.append( SEPARATOR_DIRECTORY );
+ }
+ buffer.append( fileFragments[i] );
+ }
+
+ return buffer.toString();
+ }
+
+
+ /**
+ * Create canonical form for file path
+ *
+ * @param file {@link File} with file path
+ *
+ * @return canonical path
+ *
+ * @throws IOException If file's path is illegal
+ */
+ public static
+ String
+ getCanonicalPath(
+ final File file
+ )
+ throws IOException
+ {
+ final String osCanonicalPath = file.getCanonicalPath();
+
+ return getCanonicalForm( osCanonicalPath );
+
+ }
+
+ /**
+ * Convert path to canonical form
+ *
+ * @param path file path
+ *
+ * @return canonical path
+ */
+ public static
+ String
+ getCanonicalForm(
+ final String path
+ )
+ {
+ if ( File.separatorChar == SEPARATOR_DIRECTORY )
+ {
+ return path;
+ }
+
+ return path.replace( File.separatorChar, SEPARATOR_DIRECTORY );
+ }
+
+ public static String getFilename( final String path )
+ {
+ return getTailingPath( path, 1 );
+ }
+
+ /**
+ * Returns an escaped name of the file name for linux.
+ *
+ * \ " $ => \\ \" \$
+ *
+ * @param fileName
+ */
+ public static String getEscapedName(String fileName)
+ {
+ Pattern sEscapePattern = Pattern.compile("([\\\\\"$])");
+ return sEscapePattern.matcher(fileName).replaceAll("\\\\$1");
+ }
+
+ /**
+ * Return validation check of filename
+ *
+ * Windows does not allow \ / : * ? " <> | for file name
+ *
+ * Linux does not allow / for file name
+ *
+ * @param fileName file name to check
+ *
+ * @param os os type from OSChecker
+ *
+ * @return validation check result
+ */
+ public static int isVaildName(String fileName, int os)
+ {
+ int result = IS_VALID_NAME;
+ if(fileName == null)
+ {
+ result = IS_NULL;
+ }
+
+ if(fileName.length() == 0)
+ {
+ result = HAS_NO_NAME;
+ }
+ else
+ {
+ Pattern invalidPattern;
+
+ switch(os)
+ {
+ case OSChecker.WINDOWS:
+ invalidPattern = Pattern.compile("([\\\\/:*?\"<>|])");
+ break;
+ case OSChecker.LINUX:
+ default:
+ invalidPattern = Pattern.compile("([/])");
+ }
+
+ if(invalidPattern.matcher(fileName).find())
+ {
+ result = HAS_INVALID_CHARACTER;
+ }
+ }
+ return result;
+ }
+
+ /**
+ * Return validation check of filename for host os
+ *
+ * @param fileName file name to check
+ *
+ * @return validation check result
+ */
+ public static boolean isVaildName(String fileName)
+ {
+ return isVaildName(fileName, OSChecker.getOSID()) == IS_VALID_NAME ? true : false;
+ }
+
+ /**
+ * Return invalid filename characters
+ *
+ * @param os os type from OSChecker
+ *
+ * @return validation check result
+ */
+ public static String getInvalidCharacters(int os)
+ {
+ switch(os)
+ {
+ case OSChecker.WINDOWS:
+ return "\\\\/:*?\"<>|";
+ case OSChecker.LINUX:
+ return "/";
+ default:
+ return "/";
+ }
+ }
+
+ /**
+ * Return invalid filename characters for host os
+ *
+ * @return validation check result
+ */
+ public static String getInvalidCharacters()
+ {
+ return getInvalidCharacters(OSChecker.getOSID());
+ }
+
+ public static String addDoubleQuote(String str)
+ {
+ return "\""+ str + "\"";
+ }
+
+ /**
+ * Extract file name without extension from full name
+ *
+ * @param nameWithExt file name with extension
+ *
+ * @return file name
+ */
+ public static String getName( final String nameWithExt )
+ {
+ if ( null == nameWithExt )
+ {
+ throw new NullPointerException();
+ }
+
+ final int index = nameWithExt.lastIndexOf( '.' );
+
+ if ( index < 0 )
+ {
+ return nameWithExt;
+ }
+
+ return nameWithExt.substring( 0, index );
+ }
+
+ /**
+ * Extract file extension from full name
+ *
+ * @param nameWithExt file name with extension
+ *
+ * @return file extension
+ */
+ public static String getExtension( final String nameWithExt )
+ {
+ if ( null == nameWithExt )
+ {
+ throw new NullPointerException();
+ }
+
+ final int index = nameWithExt.lastIndexOf( '.' );
+
+ if ( index < 0 )
+ {
+ return "";
+ }
+
+ return nameWithExt.substring( index + 1 );
+ }
+
+ /**
+ * Compare two file path with canonical
+ *
+ * @param file1 file1 to compare
+ * @param file2 file2 to compare
+ *
+ * @return <code>true</code> if <code>file1</code> and <code>file2</code> have equal path
+ */
+ public static boolean equals( final File file1, final File file2 )
+ {
+ try
+ {
+ return ObjectUtil.equals(
+ getCanonicalPath( file1 ),
+ getCanonicalPath( file2 )
+ );
+ } catch ( final IOException e )
+ {
+ throw new IllegalArgumentException();
+ }
+ }
+
+
+ public static boolean equals( final String path1, final String path2 )
+ {
+ return ObjectUtil.equals( path1, path2 );
+ }
+
+}
diff --git a/org.tizen.common/src/org/tizen/common/util/FilterIterator.java b/org.tizen.common/src/org/tizen/common/util/FilterIterator.java
new file mode 100644
index 000000000..100223520
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/util/FilterIterator.java
@@ -0,0 +1,158 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* BonYong Lee <bonyong.lee@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+package org.tizen.common.util;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.NoSuchElementException;
+
+/**
+ * FilterIterator.
+ *
+ * {@link Iterator} using filter method
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ *
+ * @param <E>
+ */
+public class
+FilterIterator<E>
+implements Iterator<E>
+{
+ /**
+ * Unfiltered iterator
+ */
+ protected final Iterator<? extends E> impl;
+
+ /**
+ * Acceptable element
+ */
+ protected E acceptableElement;
+
+ /**
+ * Constructor with array instance of type E
+ *
+ * @param array array to iterate
+ */
+ public
+ FilterIterator(
+ final E[] array
+ )
+ {
+ this( Arrays.asList( array ) );
+ }
+
+ /**
+ * Constructor with collection containing E object
+ *
+ * @param collection collection to iterate
+ */
+ public
+ FilterIterator(
+ final Collection<? extends E> collection
+ )
+ {
+ this.impl = ( null == collection )?null:collection.iterator();
+ }
+
+ /* (non-Javadoc)
+ * @see java.util.Iterator#hasNext()
+ */
+ @Override
+ public
+ boolean
+ hasNext()
+ {
+ if ( null == this.impl )
+ {
+ return false;
+ }
+
+ while ( this.impl.hasNext() )
+ {
+ final E element = this.impl.next();
+ if ( isAcceptable( element ) )
+ {
+ this.acceptableElement = element;
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /* (non-Javadoc)
+ * @see java.util.Iterator#next()
+ */
+ @Override
+ public
+ E
+ next()
+ {
+ if ( null == this.impl )
+ {
+ throw new NoSuchElementException();
+ }
+
+ return this.acceptableElement;
+ }
+
+ /* (non-Javadoc)
+ * @see java.util.Iterator#remove()
+ */
+ @Override
+ public
+ void
+ remove()
+ {
+ if ( null == this.impl )
+ {
+ throw new NoSuchElementException();
+ }
+ this.impl.remove();
+ }
+
+ /**
+ * Determine <code>element</code> is acceptable( not filtering )
+ *
+ * @param element object to check
+ *
+ * @return boolean value if <code>element is acceptable
+ */
+ protected
+ boolean
+ isAcceptable(
+ final E element
+ )
+ {
+ if ( null == element )
+ {
+ return false;
+ }
+
+ return true;
+ }
+
+}
diff --git a/org.tizen.common/src/org/tizen/common/util/FreeMarkerUtil.java b/org.tizen.common/src/org/tizen/common/util/FreeMarkerUtil.java
new file mode 100644
index 000000000..b43d60f9a
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/util/FreeMarkerUtil.java
@@ -0,0 +1,180 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* Jihoon Song <jihoon80.song@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+
+package org.tizen.common.util;
+
+import java.io.BufferedWriter;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.OutputStreamWriter;
+import java.io.Writer;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.URL;
+import java.util.Locale;
+import java.util.Map;
+
+import org.eclipse.core.runtime.FileLocator;
+import org.eclipse.ui.plugin.AbstractUIPlugin;
+
+import freemarker.template.Configuration;
+import freemarker.template.DefaultObjectWrapper;
+import freemarker.template.Template;
+import freemarker.template.TemplateException;
+
+/**
+ * FreeMarkerUtil.
+ *
+ * Helper related to FreeMarker
+ *
+ * @author Jihoon Song{@literal <jihoon80.song@samsung.com>} (S-Core)
+ */
+public class FreeMarkerUtil {
+
+ private final static String DEFAULT_ENCODING = "8859_1";
+
+ // Constructor
+ private FreeMarkerUtil() {}
+
+ /**
+ * Get default initialized template configuration.
+ *
+ * @return Configuration
+ */
+ public static Configuration getDefaultConfiguration() {
+ // initialize FreeMarker engine
+ Configuration cfg = new Configuration();
+ cfg.setEncoding(Locale.getDefault(), DEFAULT_ENCODING); //$NON-NLS-1$
+ cfg.setObjectWrapper(new DefaultObjectWrapper());
+
+ return cfg;
+ }
+
+ /**
+ * Get initialized template configuration.
+ *
+ * @param activator be used for Plug-in based relative path. If this value is null, throws NullPointerException.
+ * @param relativeParentPath relative template's parent path in Plug-in Bundle.
+ * @return Configuration
+ * @throws URISyntaxException
+ * @throws IOException
+ */
+ public static Configuration getConfiguration(AbstractUIPlugin activator, String relativeParentPath)
+ throws URISyntaxException, IOException {
+ Assert.notNull(activator);
+ Assert.notNull(relativeParentPath);
+
+ Configuration cfg = getDefaultConfiguration();
+
+ // set template location in plug-in
+ URL templateFolderURL = activator.getBundle().getEntry(relativeParentPath);
+ if (templateFolderURL == null) {
+ throw new FileNotFoundException();
+ }
+
+ URI templateFolderURI = FileLocator.toFileURL(templateFolderURL).toURI();
+ File templateFolder = new File(templateFolderURI);
+
+ cfg.setDirectoryForTemplateLoading(templateFolder);
+
+ return cfg;
+ }
+
+ /**
+ * Generate document using freemarker template.
+ *
+ * @param root template data model
+ * @param cfg template configuration instance
+ * @param templateFile template file
+ * @param destination output file name
+ * @throws IOException
+ * @throws TemplateException
+ */
+ public static void generateDocument(Map<String, Object> root, Configuration cfg, String templateFile, String destination)
+ throws IOException, TemplateException {
+ generateDocument(root, cfg, templateFile, new File( destination ));
+ }
+
+ /**
+ * Generate document using freemarker template.
+ *
+ * @param root template data model
+ * @param cfg template configuration instance
+ * @param templateFile template file
+ * @param destinationFile will be used for internal stream like FileOutputStream.
+ * @throws IOException
+ * @throws TemplateException
+ */
+ public static void generateDocument(Map<String, Object> root, Configuration cfg, String templateFile, File destinationFile)
+ throws IOException, TemplateException {
+ generateDocument(root, cfg, templateFile, new FileOutputStream( destinationFile ));
+ }
+
+ /**
+ * Generate document using freemarker template.
+ *
+ * @param root template data model
+ * @param cfg template configuration instance
+ * @param templateFile template file
+ * @param outputStream will be used for internal writer like BufferedWriter and OutputStreamWriter.
+ * @throws IOException
+ * @throws TemplateException
+ */
+ public static void generateDocument(Map<String, Object> root, Configuration cfg, String templateFile, OutputStream outputStream)
+ throws IOException, TemplateException {
+ generateDocument(root, cfg, templateFile, new BufferedWriter( new OutputStreamWriter( outputStream ) ));
+ }
+
+ /**
+ * Generate document using freemarker template.
+ *
+ * @param root template data model
+ * @param cfg template configuration instance
+ * @param templateFile template file
+ * @param writer output writer
+ * @throws IOException
+ * @throws TemplateException
+ */
+ public static void generateDocument(Map<String, Object> root, Configuration cfg, String templateFile, Writer writer)
+ throws IOException, TemplateException {
+ Assert.notNull(root);
+ Assert.notNull(cfg);
+ Assert.notNull(templateFile);
+ Assert.notNull(writer);
+
+ Template template = cfg.getTemplate(templateFile);
+
+ // generate document
+ try {
+ template.process(root, writer);
+ IOUtil.tryFlush(writer);
+ } finally {
+ IOUtil.tryClose(writer);
+ }
+ }
+}
diff --git a/org.tizen.common/src/org/tizen/common/util/HelpBrowser.java b/org.tizen.common/src/org/tizen/common/util/HelpBrowser.java
new file mode 100644
index 000000000..58db9e3a8
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/util/HelpBrowser.java
@@ -0,0 +1,120 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* Ho Namkoong <ho.namkoong@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+
+package org.tizen.common.util;
+
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.browser.Browser;
+import org.eclipse.swt.browser.LocationEvent;
+import org.eclipse.swt.browser.LocationListener;
+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.widgets.Composite;
+import org.eclipse.swt.widgets.ToolBar;
+import org.eclipse.swt.widgets.ToolItem;
+import org.eclipse.ui.PlatformUI;
+import org.eclipse.ui.help.IWorkbenchHelpSystem;
+import org.tizen.common.CommonPlugin;
+
+public class HelpBrowser {
+
+ private static final String HELP_PAGE_PREFIX = "help:/";
+ private static final String BACK_ICON = "icons/back.gif";
+ private static final String FORWARD_ICON = "icons/forward.gif";
+
+ private Browser browser;
+
+ public Browser getBrowser() {
+ return browser;
+ }
+
+ public HelpBrowser(Composite parent, int style) {
+ this(parent, style, false);
+ }
+
+ public HelpBrowser(Composite parent, int style, boolean hasToolbar) {
+ if(hasToolbar == true) {
+ generateToolBar(parent);
+ }
+ this.browser = new Browser(parent, style);
+ GridData gd = new GridData(GridData.FILL_BOTH);
+ this.browser.setLayoutData(gd);
+ enableHelpPage();
+ }
+
+ private void generateToolBar(Composite parent) {
+ ToolBar toolbar = new ToolBar(parent, SWT.None);
+
+ ToolItem backButton = new ToolItem(toolbar, SWT.PUSH);
+ Image backIcon = ImageUtil.getImage(CommonPlugin.PLUGIN_ID, BACK_ICON);
+ backButton.setImage(backIcon);
+
+ ToolItem forwardButton = new ToolItem(toolbar, SWT.PUSH);
+ Image forwardIcon = ImageUtil.getImage(CommonPlugin.PLUGIN_ID, FORWARD_ICON);
+ forwardButton.setImage(forwardIcon);
+
+ forwardButton.addSelectionListener(new SelectionListener() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ browser.forward();
+ }
+
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+ }
+ });
+
+ backButton.addSelectionListener(new SelectionListener() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ browser.back();
+ }
+
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+ }
+ });
+ }
+
+ private void enableHelpPage() {
+ this.getBrowser().addLocationListener(new LocationListener() {
+ @Override
+ public void changing(LocationEvent event) {
+ String url = event.location;
+ if(url.startsWith(HELP_PAGE_PREFIX)) {
+ Browser browser = ((Browser)event.widget);
+ String tempUrl = url.substring(HELP_PAGE_PREFIX.length(), url.length());
+ IWorkbenchHelpSystem helpSystem = PlatformUI.getWorkbench().getHelpSystem();
+ browser.setUrl(helpSystem.resolve(tempUrl, false).toString());
+ }
+ }
+ @Override
+ public void changed(LocationEvent event) {
+ }
+ });
+ }
+}
diff --git a/org.tizen.common/src/org/tizen/common/util/HostUtil.java b/org.tizen.common/src/org/tizen/common/util/HostUtil.java
index a2e1b6871..012a60c49 100644..100755
--- a/org.tizen.common/src/org/tizen/common/util/HostUtil.java
+++ b/org.tizen.common/src/org/tizen/common/util/HostUtil.java
@@ -24,356 +24,311 @@
*/
package org.tizen.common.util;
+import static org.tizen.common.util.IOUtil.tryClose;
+
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
-import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
-import java.io.IOException;
import java.io.InputStreamReader;
-import java.net.InetAddress;
import java.nio.channels.FileChannel;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.core.runtime.Platform;
-import org.tizen.common.console.ConsoleManager;
+import org.tizen.common.ui.view.console.ConsoleManager;
public abstract class HostUtil{
-
-// public static final String USER = System.getenv("USER");
-// public static final String USER_HOME = System.getenv("HOME");
- public static final String LINE_SEPARATOR = System.getProperty("line.separator"); //$NON-NLS-1$
- public static final String FILE_SEPARATOR = System.getProperty("file.separator"); //$NON-NLS-1$
-
- private static final String PROC_PATH = "/proc"; //$NON-NLS-1$
- private static final String SHELL_COMMAND_LINUX= "/bin/sh"; //$NON-NLS-1$
- private static final String SHELL_COMMAND_WINDOW= "cmd"; //$NON-NLS-1$
-
- public static boolean hasProcFile(String pid) {
- if(pid==null||pid.equals("")) //$NON-NLS-1$
- return false;
+
+ public static final String LINE_SEPARATOR = System.getProperty("line.separator"); //$NON-NLS-1$
+ public static final String FILE_SEPARATOR = System.getProperty("file.separator"); //$NON-NLS-1$
+
+ private static final String SHELL_COMMAND_LINUX= "/bin/sh"; //$NON-NLS-1$
+ private static final String SHELL_COMMAND_WINDOW= "cmd"; //$NON-NLS-1$
+
+ public static String getContents(String filePath) {
+ BufferedReader input = null;
+ StringBuilder contents = new StringBuilder();
+ String line = null;
+
+ try {
+ input = new BufferedReader(new FileReader(filePath));
+ while((line=input.readLine())!=null){
+ contents.append(line);
+ contents.append(LINE_SEPARATOR);
+ }
+ }catch(Exception e) {
+// e.printStackTrace();
+ return null;
+ }finally{
+ tryClose( input );
+ }
+
+ return contents.toString().trim();
+ }
- String pidFile = PROC_PATH+Path.SEPARATOR+pid;
- return exists(pidFile);
- }
- public static boolean isMenuReady(String pid) {
- if(pid==null||pid.equals("")) //$NON-NLS-1$
- return false;
+ public static boolean exists(String path) {
+ if( path == null || path.equals("") ) //$NON-NLS-1$
+ return false;
- String pidFile = PROC_PATH+Path.SEPARATOR+pid;
- return exists(pidFile);
- }
+ File file = new File( path );
-
- public static String getContents(String filePath) {
- BufferedReader input = null;
- StringBuilder contents = new StringBuilder();
- String line = null;
-
- try {
- input = new BufferedReader(new FileReader(filePath));
- while((line=input.readLine())!=null){
- contents.append(line);
- contents.append(LINE_SEPARATOR);
- }
- }catch(Exception e) {
-// e.printStackTrace();
- return null;
- }finally{
- if(input!=null)
- try {
- input.close();
- } catch (IOException e) {
- }
- }
-
- return contents.toString().trim();
- }
-
- public static boolean isReachable(String ip) {
- try {
- return InetAddress.getByName(ip).isReachable(100);
- } catch (Exception e) {
- e.printStackTrace();
- }
- return false;
- }
+ return file.exists();
+ }
- public static boolean exists(String path) {
- if(path==null||path.equals("")) //$NON-NLS-1$
- return false;
-
- IPath ipath = new Path(path);
- File file = ipath.toFile();
-
- if(file!=null&&file.exists())
- return true;
- else
- return false;
- }
-
- public static boolean execute(String command){
- Process proc = null;
- Runtime runtime = Runtime.getRuntime();
-
- String[] fullCommand = getCommand(command);
-
- int i = 0;
- try {
- proc= runtime.exec(fullCommand);
- i = proc.waitFor();
- } catch (Exception e) {
- e.printStackTrace();
- return false;
- } finally{
- System.out.println("HostUtil execute - exit value : " + i);
- if(proc!=null)
- proc.destroy();
- }
-
- return i==0;
- }
-
- public static boolean batchExecute(String command)
- {
- String[] fullCommand = getCommand(command);
+ public static boolean execute(String command){
+
+ if(command == null) {
+ return false;
+ }
+ Process proc = null;
+ Runtime runtime = Runtime.getRuntime();
+
+ String[] fullCommand = getCommand(command);
+
+ int i = 0;
+ try {
+ proc= runtime.exec(fullCommand);
+ i = proc.waitFor();
+ } catch (Exception e) {
+ e.printStackTrace();
+ return false;
+ } finally{
+ System.out.println("HostUtil execute - exit value : " + i);
+ if(proc!=null)
+ proc.destroy();
+ }
+
+ return i==0;
+ }
+
+ public static boolean batchExecute(String command)
+ {
+ if(command == null) {
+ return false;
+ }
+ String[] fullCommand = getCommand(command);
- Runtime run = Runtime.getRuntime();
- Process p = null;
-
- try{
- p = run.exec(fullCommand);
- StreamGobbler gb1 = new StreamGobbler(p.getInputStream());
- StreamGobbler gb2 = new StreamGobbler(p.getErrorStream());
- gb1.start();
- gb2.start();
- }catch(Exception e){
- e.printStackTrace();
- return false;
- }finally{
- }
- return true;
- }
+ Runtime run = Runtime.getRuntime();
+ Process p = null;
+
+ int i = 0;
+ try{
+ p = run.exec(fullCommand);
+ i = p.waitFor();
+ StreamGobbler gb1 = new StreamGobbler(p.getInputStream());
+ StreamGobbler gb2 = new StreamGobbler(p.getErrorStream());
+ gb1.start();
+ gb2.start();
+ }catch(Exception e){
+ e.printStackTrace();
+ return false;
+ }
+ return i == 0;
+ }
- /**
- * Don't need for emultor install registration.
- * using java.lang.Runtime.exec(String[] cmdarray, String[] envp, File dir)
- * @param command - array containing the command to call and its arguments.
- * @param envp - array of strings, each element of which has environment variable settings in format name=value.
- * @param dir - Emultor path.
- * @return success true, failed false.
- */
- public static boolean batchExecute(String command, String[] envp, File dir)
- {
- String[] fullCommand = getCommand(command);
+ /**
+ * Don't need for emultor install registration.
+ * using java.lang.Runtime.exec(String[] cmdarray, String[] envp, File dir)
+ * @param command - array containing the command to call and its arguments.
+ * @param envp - array of strings, each element of which has environment variable settings in format name=value.
+ * @param dir - Emultor path.
+ * @return success true, failed false.
+ */
+ public static boolean batchExecute(String command, String[] envp, File dir)
+ {
+ String[] fullCommand = getCommand(command);
- Runtime run = Runtime.getRuntime();
- Process p = null;
+ Runtime run = Runtime.getRuntime();
+ Process p = null;
- StreamGobbler gb1 = null;
- StreamGobbler gb2 = null;
- try{
- p = run.exec(fullCommand, envp, dir);
- gb1 = new StreamGobbler(p.getInputStream());
- gb2 = new StreamGobbler(p.getErrorStream());
- gb1.start();
- gb2.start();
- }catch(Exception e){
- e.printStackTrace();
- return false;
- }finally{
- System.out.println(gb1.getResult());
- System.out.println(gb2.getResult());
- }
- return true;
- }
+ StreamGobbler gb1 = null;
+ StreamGobbler gb2 = null;
+ try{
+ p = run.exec(fullCommand, envp, dir);
+ gb1 = new StreamGobbler(p.getInputStream());
+ gb2 = new StreamGobbler(p.getErrorStream());
+ gb1.start();
+ gb2.start();
+ }catch(Exception e){
+ e.printStackTrace();
+ return false;
+ }finally{
+ System.out.println(gb1.getResult());
+ System.out.println(gb2.getResult());
+ }
+ return true;
+ }
- public static String returnExecute(String command, String workingDir) {
- BufferedReader input = null;
- StringBuilder contents = new StringBuilder();
- String line = null;
-
- Process proc = null;
-
- String[] fullCommand = getCommand(command);
-
- try {
- ProcessBuilder pb = new ProcessBuilder();
- pb.command(fullCommand);
- if(workingDir != null) {
- pb.directory(new File(workingDir));
- }
- proc = pb.start();
- input = new BufferedReader(new InputStreamReader(proc.getInputStream()));
- while((line=input.readLine())!=null){
- contents.append(line);
- contents.append(LINE_SEPARATOR);
- }
- } catch (Exception e) {
- e.printStackTrace();
- return null;
- } finally{
- if(proc!=null)
- proc.destroy();
- if(input!=null)
- try {
- input.close();
- } catch (IOException e) {
- }
- }
-
- return contents.toString().trim();
-
- }
-
- /**
- * Show output messages while executes the command on console view
- * @param command - Command to execute.
- * @param viewName - View name showing messages while executes the command.
- */
- public static void executeWithConsole(String command, String viewName) throws Exception {
- BufferedReader input = null;
+ public static String returnExecute(String command, String workingDir) {
+
+ if(command == null) {
+ return null;
+ }
+ BufferedReader input = null;
+ StringBuilder contents = new StringBuilder();
+ String line = null;
+
+ Process proc = null;
+
+ String[] fullCommand = getCommand(command);
+
+ try {
+ ProcessBuilder pb = new ProcessBuilder();
+ pb.command(fullCommand);
+ if(workingDir != null) {
+ pb.directory(new File(workingDir));
+ }
+ proc = pb.start();
+ input = new BufferedReader(new InputStreamReader(proc.getInputStream()));
+ while((line=input.readLine())!=null){
+ contents.append(line);
+ contents.append(LINE_SEPARATOR);
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
+ return null;
+ } finally{
+ tryClose( input );
+ if(proc!=null)
+ {
+ proc.destroy();
+ }
+ }
+
+ return contents.toString().trim();
+
+ }
+
+ /**
+ * Show output messages while executes the command on console view
+ * @param command - Command to execute.
+ * @param viewName - View name showing messages while executes the command.
+ */
+ public static void executeWithConsole(String command, String viewName) throws Exception {
+ BufferedReader input = null;
- String line = null;
-
- Process proc = null;
-
- String[] fullCommand = getCommand(command);
-
- ConsoleManager cm = new ConsoleManager( viewName, true );
- cm.clear();
-
- try {
- ProcessBuilder pb = new ProcessBuilder();
- pb.redirectErrorStream(true);
- pb.command(fullCommand);
- proc = pb.start();
- input = new BufferedReader(new InputStreamReader(proc.getInputStream()));
- while((line=input.readLine())!=null){
- cm.println(line);
- }
- proc.waitFor();
- // abnormal termination
- if (proc.exitValue() != 0)
- throw new Exception("Failed to execute command: " + command);
- } finally {
- if(proc!=null)
- proc.destroy();
- if(input!=null)
- try {
- input.close();
- } catch (IOException e) {
- }
- }
- }
-
- public static String returnExecute(String command){
-
- return returnExecute(command, null);
- }
-
- public static String[] getCommand(String command){
-
- if(OSChecker.isWindows()){
- return new String[]{SHELL_COMMAND_WINDOW,"/c",command}; //$NON-NLS-1$
- }else
- {
- return new String[]{SHELL_COMMAND_LINUX,"-c",command}; //$NON-NLS-1$
- }
- }
-
-
- public static boolean createFile(String path, String contents) {
- BufferedWriter output = null;
- try {
- File file = new File(path);
-
- File folder = file.getParentFile();
- if(folder!=null)
- folder.mkdirs();
-
- file.createNewFile();
-
- output = new BufferedWriter(new FileWriter(file));
- output.write(contents);
- return true;
- } catch (Exception e) {
- e.printStackTrace();
- return false;
- }finally{
- if(output!=null)
- try {
- output.close();
- } catch (IOException e) {
- }
- }
- }
-
- public static boolean removeFile(String path) {
- File file = new File(path);
- if (!file.exists())
- return false;
- return file.delete();
- }
-
- /**
- * @deprecated Use {@link FileUtil#copyTo(String, String)} instead.
- */
- @Deprecated
- public static boolean copyFile(String src, String des) throws Exception {
- boolean canExecute = false;
- File srcFile=new File(src);
- File desFile=null;
- FileInputStream fis=null;
- FileOutputStream fos=null;
- FileChannel fcin=null;
- FileChannel fcout=null;
-
- canExecute = srcFile.canExecute();
-
- desFile= new File(des);
- File paths = new File(desFile.getAbsolutePath().substring(0, desFile.getAbsolutePath().lastIndexOf("/"))); //$NON-NLS-1$
- if (!paths.exists()) {
- paths.mkdirs();
- }
-
- try {
- fis= new FileInputStream(srcFile);
- fos= new FileOutputStream(desFile);
- fcin= fis.getChannel();
- fcout= fos.getChannel();
-
- long size= fcin.size();
- fcin.transferTo(0, size, fcout);
- desFile.setExecutable(canExecute);
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- throw e;
- } catch (IOException e) {
- e.printStackTrace();
- throw e;
- }finally{
- try {
- fcout.close();
- fcin.close();
- fos.close();
- fis.close();
- } catch (IOException e) {
- e.printStackTrace();
- throw e;
- }
- }
+ String line = null;
+
+ Process proc = null;
+
+ String[] fullCommand = getCommand(command);
+
+ ConsoleManager cm = new ConsoleManager( viewName, true );
+ cm.clear();
+
+ try {
+ ProcessBuilder pb = new ProcessBuilder();
+ pb.redirectErrorStream(true);
+ pb.command(fullCommand);
+ proc = pb.start();
+ input = new BufferedReader(new InputStreamReader(proc.getInputStream()));
+ while((line=input.readLine())!=null){
+ cm.println(line);
+ }
+ proc.waitFor();
+ // abnormal termination
+ if (proc.exitValue() != 0)
+ throw new Exception("Failed to execute command: " + command);
+ } finally {
+ tryClose( input );
+ if(proc!=null)
+ {
+ proc.destroy();
+ }
+ }
+ }
+
+ public static String returnExecute(String command){
+
+ return returnExecute(command, null);
+ }
+
+ public static String[] getCommand(String command){
+
+ if(OSChecker.isWindows()){
+ return new String[]{SHELL_COMMAND_WINDOW,"/c",command}; //$NON-NLS-1$
+ }else
+ {
+ return new String[]{SHELL_COMMAND_LINUX,"-c",command}; //$NON-NLS-1$
+ }
+ }
+
+ /**
+ * @deprecated Use {@link FileUtil#createFile(File)},
+ * {@link FileUtil#createFile(String)},
+ * {@link FileUtil#createFile(String, String)}
+ * or
+ * {@link FileUtil#createTextFile(File, String, String)},
+ * {@link FileUtil#createTextFile(String, String, String)},
+ * {@link FileUtil#createTextFile(String, String, String, String)}
+ * and
+ * {@link FileUtil#createDirectory(File)},
+ * {@link FileUtil#createDirectory(String)},
+ * {@link FileUtil#createDirectory(String, String)}
+ * instead.
+ */
+ @Deprecated
+ public static boolean createFile(String path, String contents) {
+ BufferedWriter output = null;
+ try {
+ File file = new File(path);
+
+ File folder = file.getParentFile();
+ if(folder!=null)
+ folder.mkdirs();
+
+ file.createNewFile();
+
+ output = new BufferedWriter(new FileWriter(file));
+ output.write(contents);
+ return true;
+ } catch (Exception e) {
+ e.printStackTrace();
+ return false;
+ }finally{
+ tryClose( output );
+ }
+ }
+
+
+ /**
+ * @deprecated Use {@link FileUtil#copyTo(String, String)} instead.
+ */
+ @Deprecated
+ public static boolean copyFile(String src, String des) throws Exception {
+ boolean canExecute = false;
+ File srcFile=new File(src);
+ File desFile=null;
+ FileInputStream fis=null;
+ FileOutputStream fos=null;
+ FileChannel fcin=null;
+ FileChannel fcout=null;
+
+ canExecute = srcFile.canExecute();
+
+ desFile= new File(des);
+ File paths = new File(desFile.getAbsolutePath().substring(0, desFile.getAbsolutePath().lastIndexOf("/"))); //$NON-NLS-1$
+ if (!paths.exists()) {
+ paths.mkdirs();
+ }
+
+ try {
+ fis= new FileInputStream(srcFile);
+ fos= new FileOutputStream(desFile);
+ fcin= fis.getChannel();
+ fcout= fos.getChannel();
+
+ long size= fcin.size();
+ fcin.transferTo(0, size, fcout);
+ desFile.setExecutable(canExecute);
+ }finally{
+ tryClose( fcout, fcin, fos, fis );
+ }
- return true;
- }
-
- public static boolean isLinux(){
- return Platform.getOS().equals(Platform.OS_LINUX);
- }
+ return true;
+ }
+
}
diff --git a/org.tizen.common/src/org/tizen/common/util/IOUtil.java b/org.tizen.common/src/org/tizen/common/util/IOUtil.java
index 0dce62006..9fbd2e06f 100644
--- a/org.tizen.common/src/org/tizen/common/util/IOUtil.java
+++ b/org.tizen.common/src/org/tizen/common/util/IOUtil.java
@@ -24,25 +24,361 @@
*/
package org.tizen.common.util;
+import java.io.ByteArrayOutputStream;
import java.io.Closeable;
+import java.io.Flushable;
import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
+import java.io.Reader;
+import java.io.Writer;
+import java.net.ServerSocket;
+import java.net.Socket;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* IOUtil
* @author Hyeongseok Heo {@literal<hyeongseok.heo@samsung.com>}
+ * BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ *
* @since Dec 9, 2011
*/
public class IOUtil {
- public static void close(Closeable closable) {
- if( null != closable) {
- try {
- closable.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
+ private static final int BUFFER_SIZE = 8192;
+
+ protected static final Logger logger = LoggerFactory.getLogger( IOUtil.class );
+
+ /**
+ * close closable objects.
+ *
+ * @param closeables object to be able to close
+ */
+ public static void tryClose( final Object... closeables )
+ {
+ if ( null == closeables )
+ {
+ return ;
+ }
+
+ for ( Object obj : closeables )
+ {
+ if ( null == obj )
+ {
+ continue;
+ }
+ try
+ {
+ if ( obj instanceof Closeable )
+ {
+ ((Closeable) obj).close();
+ }
+ else if ( obj instanceof Socket )
+ {
+ ((Socket) obj).close();
+ }
+ else if ( obj instanceof ServerSocket )
+ {
+ ((ServerSocket) obj).close();
+ }
+ }
+ catch ( final IOException e )
+ {
+ }
+ }
+ }
+
+ /**
+ * flush <code>Flushable</code>s
+ *
+ * @param flushables <code>Flushable</code>s to flush
+ */
+ public static void tryFlush( final Flushable... flushables )
+ {
+ if ( null == flushables )
+ {
+ return ;
+ }
+
+ for ( Flushable closeable : flushables )
+ {
+ if ( null == closeable )
+ {
+ continue;
+ }
+ try
+ {
+ closeable.flush();
+ }
+ catch ( final IOException e )
+ {
+ }
+ }
+
+ }
+
+ /**
+ * Redirect from <code>in</code> to <code>out</code>
+ *
+ * @param in {@link InputStream}
+ * @param out {@link OutputStream}
+ *
+ * @throws IOException occur exception when handling <code>in</code> or <code>out</code>
+ */
+ public static
+ void
+ redirect(
+ final InputStream in,
+ final OutputStream out
+ )
+ throws IOException
+ {
+ final byte[] buffer = new byte[BUFFER_SIZE];
+
+ int nRead = 0;
+ int totalBytes = 0;
+ while ( 0 < ( nRead = in.read( buffer ) ) )
+ {
+ out.write( buffer, 0, nRead );
+ totalBytes += nRead;
+ }
+
+ logger.trace( "{} byte(s) wrote", totalBytes );
+
+ tryFlush( out );
+ }
+
+ /**
+ * Redirect from <code>reader</code> to <code>writer</code>
+ *
+ * @param reader {@link Reader}
+ * @param writer {@link Writer}
+ *
+ * @throws IOException occur exception when handling <code>reader</code> or <code>writer</code>
+ */
+ public static
+ void
+ redirect(
+ final Reader reader,
+ final Writer writer
+ )
+ throws IOException
+ {
+ final char[] buffer = new char[BUFFER_SIZE];
+
+ int nRead = 0;
+ while ( 0 < ( nRead = reader.read( buffer ) ) )
+ {
+ writer.write( buffer, 0, nRead );
+ }
+ tryFlush( writer );
+ }
+
+ /**
+ * Redirect from <code>reader</code> to <code>writer</code>
+ *
+ * @param reader {@link Reader}
+ * @param writer {@link StringBuffer}
+ *
+ * @throws IOException occur exception when handling <code>reader</code> or <code>writer</code>
+ */
+ public static
+ void
+ redirect(
+ final Reader reader,
+ final StringBuffer writer
+ )
+ throws IOException
+ {
+ final char[] buffer = new char[BUFFER_SIZE];
+
+ int nRead = 0;
+ while ( 0 < ( nRead = reader.read( buffer ) ) )
+ {
+ writer.append( buffer, 0, nRead );
+ }
+ }
+
+ /**
+ * Redirect from <code>reader</code> to <code>writer</code>
+ *
+ * @param reader {@link Reader}
+ * @param writer {@link StringBuilder}
+ *
+ * @throws IOException occur exception when handling <code>reader</code> or <code>writer</code>
+ */
+ public static
+ void
+ redirect(
+ final Reader reader,
+ final StringBuilder writer
+ )
+ throws IOException
+ {
+ if ( null == reader )
+ {
+ return ;
+ }
+ final char[] buffer = new char[BUFFER_SIZE];
+
+ int nRead = 0;
+ while ( 0 < ( nRead = reader.read( buffer ) ) )
+ {
+ writer.append( buffer, 0, nRead );
+ }
+ }
+
+
+ /**
+ * Get and return byte array from {@link InputStream}
+ *
+ * @param in input stream to read byte array
+ *
+ * @return stored byte array
+ *
+ * @throws IOException If can't read byte from <code>in</code>
+ *
+ * @link {@link #getBytes(InputStream, boolean)}
+ */
+ public static
+ byte[] getBytes(
+ final InputStream in
+ )
+ throws IOException
+ {
+ return getBytes( in, false );
+ }
+
+ /**
+ * Get and return byte array from {@link InputStream}
+ *
+ * @param in input stream to read byte array
+ * @param bClose optional flag if close <code>in</code> after processing
+ *
+ * @return stored byte array
+ *
+ * @throws IOException If can't read byte from <code>in</code>
+ *
+ * @link {@link #redirect(InputStream, OutputStream)}
+ */
+ public static
+ byte[] getBytes(
+ final InputStream in,
+ final boolean bClose
+ ) throws IOException
+ {
+ final ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
+
+ try
+ {
+ redirect( in, byteOut );
+
+ if ( bClose )
+ {
+ tryClose( in );
}
+
+ return byteOut.toByteArray();
}
+ finally
+ {
+ tryClose( byteOut );
+ }
+
+ }
+
+ /**
+ * <p>
+ * Get and return string from {@link Reader}
+ *
+ * return empty string( "" ) if <code>reader</code> is <code>null</code>
+ * </p>
+ *
+ * @param reader reader to read string
+ * @return string to be accquired
+ *
+ * @throws IOException If can't read string from {@link Reader}
+ *
+ * @see #getString(Reader, boolean)
+ */
+ public static
+ String getString(
+ final Reader reader
+ )
+ throws IOException
+ {
+ return getString( reader, false );
+
}
-
+
+ /**
+ * <p>
+ * Get and return string from {@link Reader}
+ *
+ * Return empty string( "" ) if <code>reader</code> is <code>null</code>
+ * </p>
+ *
+ * @param reader reader to read string
+ * @param bClose optional flag if close <code>in</code> after processing
+ *
+ * @return string to be accquired
+ *
+ * @throws IOException If can't read string from {@link Reader}
+ *
+ * @see #redirect(Reader, StringBuilder)
+ */
+ public static
+ String
+ getString(
+ final Reader reader,
+ final boolean bClose
+ )
+ throws IOException
+ {
+ final StringBuilder writer = new StringBuilder();
+ try {
+ redirect( reader, writer );
+
+ if ( bClose )
+ {
+ tryClose( reader );
+ }
+
+ return writer.toString();
+ }
+ finally
+ {
+ tryClose( writer );
+ }
+
+ }
+
+ /**
+ * <p>
+ * Get and return string from {@link InputStream}
+ *
+ * Return empty string ( "" ) if <code>in</code> is <code>null</code>
+ *
+ * @param in {@link InputStream} to read
+ *
+ * @return string to be accquired
+ *
+ * @throws IOException If can't read anything from {@link InputStream}
+ *
+ * @see #getString(Reader)
+ */
+ public static
+ String
+ getString(
+ final InputStream in
+ )
+ throws IOException
+ {
+ return getString( new InputStreamReader( in ) );
+ }
+
+
}
diff --git a/org.tizen.common/src/org/tizen/common/util/ImageUtils.java b/org.tizen.common/src/org/tizen/common/util/ImageUtil.java
index c22fd7828..49d85e29f 100644
--- a/org.tizen.common/src/org/tizen/common/util/ImageUtils.java
+++ b/org.tizen.common/src/org/tizen/common/util/ImageUtil.java
@@ -31,19 +31,73 @@ import org.eclipse.core.runtime.Plugin;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
+import org.osgi.framework.Bundle;
+import org.tizen.common.SurrogateWithArgument;
-public class ImageUtils {
+public class ImageUtil {
+ public static class PlatformSurrogate {
+ public Bundle getBundle(String pluginID) {
+ return Platform.getBundle(pluginID);
+ }
+ }
+
+ public static class PluginSurrogate {
+ public Bundle getBundle(Plugin plugin) {
+ return plugin.getBundle();
+ }
+ }
+
+ public static final String[] supportedImageExtension = {
+ "*.gif;*.png;*.jpeg;*.jpg;*.tiff;*.tif;*.ico;*.bmp;*.rle", // all supported format in SWT //$NON-NLS-1$
+ "*.gif", // Graphics Interchange Format, including animated GIFs //$NON-NLS-1$
+ "*.png", // Portable Network Graphics //$NON-NLS-1$
+ "*.jpeg;*.jpg", // Joint Photographic Experts Group //$NON-NLS-1$
+ "*.tiff;*.tif", // Tagged Image File Format //$NON-NLS-1$
+ "*.ico", // Widows Icon //$NON-NLS-1$
+ "*.bmp", // Windows Bitmap //$NON-NLS-1$
+ "*.rle" // Windows Bitmap with run-length encoding //$NON-NLS-1$
+ };
+
+ /**
+ * load image descriptor from <code>bundle</code> with <code>filePath</code>
+ *
+ * @param bundle {@link Bundle}
+ * @param filePath image file path
+ *
+ * @return loaded {@link ImageDescriptor}
+ */
+ protected static
+ ImageDescriptor
+ getImageDescriptor(
+ final Bundle bundle,
+ final String filePath
+ )
+ {
+ final URL url = bundle.getEntry( filePath );
+ return ImageDescriptor.createFromURL( url );
+ }
+
+ protected static SurrogateWithArgument<Bundle, String> platformSurrogate = new SurrogateWithArgument<Bundle, String>() {
+ public Bundle getAdapter( final String pluginId )
+ {
+ return Platform.getBundle( pluginId );
+ }
+ };
+ protected static SurrogateWithArgument<Bundle, Plugin> pluginSurrogate = new SurrogateWithArgument<Bundle, Plugin>() {
+ public Bundle getAdapter(Plugin plugin) {
+ return plugin.getBundle();
+ }
+ };
+
// get ImageDescriptor from Plugin ID (ID -> ImageDescriptor)
public static ImageDescriptor getImageDescriptor(String pluginID, String filePath) {
- URL url = Platform.getBundle(pluginID).getEntry(filePath);
- return ImageDescriptor.createFromURL(url);
+ return getImageDescriptor( platformSurrogate.getAdapter(pluginID), filePath );
}
// get ImageDescriptor from Activator Plugin (Activator -> ImageDescriptor)
public static ImageDescriptor getImageDescriptor(Plugin plugin, String filePath) {
- URL url = plugin.getBundle().getEntry(filePath); // $NON-NLS-1$
- return ImageDescriptor.createFromURL(url);
+ return getImageDescriptor( pluginSurrogate.getAdapter(plugin), filePath );
}
// get Image from ImageDescriptor (ImageDescriptor -> Image)
@@ -79,4 +133,4 @@ public class ImageUtils {
ImageDescriptor descriptor = getImageDescriptor(pluginID, filePath);
return getImageData(descriptor);
}
-} \ No newline at end of file
+}
diff --git a/org.tizen.common/src/org/tizen/common/util/IteratingAcceptor.java b/org.tizen.common/src/org/tizen/common/util/IteratingAcceptor.java
new file mode 100644
index 000000000..bb8c3d1a0
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/util/IteratingAcceptor.java
@@ -0,0 +1,49 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* BonYong Lee <bonyong.lee@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+package org.tizen.common.util;
+
+import java.util.Collection;
+
+/**
+ * IteratingAcceptor.
+ *
+ * Filter logic containing iterface for {@link Collection} or array
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ *
+ * @param <T> arguement type
+ */
+public interface IteratingAcceptor<T>
+{
+ /**
+ * Check that <code>arg</code> is filtered or passed
+ *
+ * @param arg collection element
+ *
+ * @return <code>true</code> if <code>arg</code> is element to pass
+ */
+ boolean accept( T arg );
+
+}
diff --git a/org.tizen.common/src/org/tizen/common/util/IteratingAdapter.java b/org.tizen.common/src/org/tizen/common/util/IteratingAdapter.java
new file mode 100644
index 000000000..6c29b90fa
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/util/IteratingAdapter.java
@@ -0,0 +1,7 @@
+package org.tizen.common.util;
+
+import java.util.Iterator;
+
+public interface IteratingAdapter<T> {
+ public Iterator<T> adapt( T obj );
+}
diff --git a/org.tizen.common/src/org/tizen/common/model/ITreeModel.java b/org.tizen.common/src/org/tizen/common/util/IteratingRunner.java
index 50a7a1373..5136d99c4 100644
--- a/org.tizen.common/src/org/tizen/common/model/ITreeModel.java
+++ b/org.tizen.common/src/org/tizen/common/util/IteratingRunner.java
@@ -1,42 +1,47 @@
-/*
-* Common
-*
-* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
-*
-* Contact:
-* Kangho Kim <kh5325.kim@samsung.com>
-*
-* 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.
-*
-* Contributors:
-* - S-Core Co., Ltd
-*
-*/
-
-package org.tizen.common.model;
-
-import java.util.Collection;
-
-public interface ITreeModel
-{
- public void add(ITreeVO datas);
- public void add(Collection<ITreeVO> datas);
- public void remove(ITreeVO datas);
- public void remove(Collection<ITreeVO> datas);
- public ITreeVO[] getDatas();
- public void load(String fileName);
- public void save(String fileName);
- public void clear();
- public int size();
- public String getSourceName();
-}
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* BonYong Lee <bonyong.lee@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+package org.tizen.common.util;
+
+import java.util.Collection;
+
+/**
+ * IteratingRunner.
+ *
+ * Runner with argument for iteration of {@link Collection} or array
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ *
+ * @param <T> arguement type
+ */
+public interface IteratingRunner<T>
+{
+ /**
+ * Run with collection element <code>arg</code>
+ *
+ * @param arg collection element
+ */
+ public void run( T arg );
+
+}
diff --git a/org.tizen.common/src/org/tizen/common/util/IteratingUtil.java b/org.tizen.common/src/org/tizen/common/util/IteratingUtil.java
new file mode 100644
index 000000000..c01337000
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/util/IteratingUtil.java
@@ -0,0 +1,27 @@
+package org.tizen.common.util;
+
+import java.util.Iterator;
+
+public class IteratingUtil {
+ public static <T> void iterate( T obj, IteratingAdapter<T> adapter, IteratingRunner<T> runner )
+ {
+ if ( null == obj )
+ {
+ return ;
+ }
+
+ Iterator<T> iter = adapter.adapt( obj );
+ if ( null == iter )
+ {
+ return ;
+ }
+ while ( iter.hasNext() )
+ {
+ T child = iter.next();
+ runner.run( child );
+ iterate( child, adapter, runner );
+ }
+
+ }
+
+}
diff --git a/org.tizen.common/src/org/tizen/common/util/LocalPortChecker.java b/org.tizen.common/src/org/tizen/common/util/LocalPortChecker.java
index 68c3337ed..da15c1250 100644
--- a/org.tizen.common/src/org/tizen/common/util/LocalPortChecker.java
+++ b/org.tizen.common/src/org/tizen/common/util/LocalPortChecker.java
@@ -38,45 +38,52 @@ import java.net.ServerSocket;
* <li> added getAvailableLocalPort method.
* </ul>
*/
-public class LocalPortChecker {
- public static boolean isPortAvailable(int port) {
- if ((port < 0) && (port > 65535))
- return false;
+public class LocalPortChecker
+{
+
+ public static boolean isPortInRange( final int port )
+ {
+ return ( 0 <= port ) && ( port < 65536 );
+
+ }
+ public static boolean isPortAvailable( final int port )
+ {
+ if ( !isPortInRange( port ) )
+ {
+ return false;
+ }
ServerSocket socket = null;
- try {
- socket = new ServerSocket(port);
+ try
+ {
+ socket = new ServerSocket( port );
return true;
- } catch (IOException e) {
- return false;
- } finally {
- if (socket != null) {
- try {
- socket.close();
- } catch (IOException e) {
- // do nothing
- }
- }
- }
- }
-
- public static int getAvailableLocalPort(int inc,int portBase) {
- int port = portBase;
- if (isPortAvailable(port)) {
- return port;
}
-
- if ( (port+inc) > 65535) {
- return -1;
+ catch ( final IOException e )
+ {
+ return false;
}
-
- while ((port < 65535) && !isPortAvailable(port)) {
- port += inc;
+ finally
+ {
+ IOUtil.tryClose( socket );
}
-
- if (isPortAvailable(port))
- return port;
- else
- return -1;
+ }
+
+ public static int
+ getAvailableLocalPort(
+ final int inc,
+ final int portBase
+ )
+ {
+ for ( int port = portBase ; true ; port += inc )
+ {
+ if ( !isPortInRange( port) )
+ {
+ return -1;
+ }
+ if ( isPortAvailable( port ) ) {
+ return port;
+ }
+ }
}
}
diff --git a/org.tizen.common/src/org/tizen/common/util/MapUtil.java b/org.tizen.common/src/org/tizen/common/util/MapUtil.java
new file mode 100644
index 000000000..f721875af
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/util/MapUtil.java
@@ -0,0 +1,219 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* BonYong Lee <bonyong.lee@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+package org.tizen.common.util;
+
+import static org.tizen.common.util.StringUtil.NULL_STRING;
+
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Properties;
+
+/**
+ * MapUtil.
+ *
+ * Helper related to {@link Map}
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ */
+public class MapUtil
+{
+ /**
+ * protected constructor
+ */
+ protected MapUtil() {}
+
+ /**
+ * Return <code>map</code>'s size
+ *
+ * Return <code>0</code>, if <code>map</code> is <code>null</code>
+ *
+ * @param map {@link Map} to count elements
+ *
+ * @return the number of element in <code>map</code>
+ */
+ public static
+ int
+ length(
+ final Map<?, ?> map
+ )
+ {
+ if ( null == map )
+ {
+ return 0;
+ }
+ return map.size();
+ }
+
+
+ /**
+ * Check if <code>map</code> is empty
+ *
+ * Return <code>true</code>, if <code>map</code> is <code>null</code> or has no element
+ *
+ * @param map {@link Map} to check
+ *
+ * @return if map is empty
+ */
+ public static
+ boolean
+ isEmpty(
+ final Map<?, ?> map
+ )
+ {
+ return ( 0 == length( map ) );
+ }
+
+ /**
+ * Return {@link Map} for <code>keys</code> and <code>values</code>
+ *
+ * add i th object of <code>values</code> with i th object of <code>keys</code> as key
+ *
+ * @param <K> key type
+ * @param <V> value type
+ * @param keys keys to add
+ * @param values values to add
+ *
+ * @return {@link Map} containing <code>keys</code> - <code>values</code> pairs
+ */
+ public static <K, V>
+ Map<K, V>
+ asMap(
+ final K[] keys,
+ final V[] values
+ )
+ {
+ final HashMap<K, V> map = new HashMap<K, V>();
+ if ( null == keys || null == values )
+ {
+ return map;
+ }
+
+ for ( int i=0, n=Math.min( keys.length, values.length ) ; i<n ; ++i )
+ {
+ map.put( keys[i], values[i] );
+ }
+ return map;
+ }
+
+
+ /**
+ * Return {@link Map} for <code>objs</code>
+ *
+ * <code>objs</code> is {@link Object[]} that each element is key-value pair.
+ *
+ * @param <A> key type
+ * @param <B> value type
+ * @param objs key-value pairs to add
+ *
+ * @return created {@link Map}
+ */
+ @SuppressWarnings("unchecked")
+ public static <A extends Object, B extends Object>
+ Map<A, B>
+ asMap(
+ final Object[][] objs
+ )
+ {
+ final HashMap<A, B> map = new HashMap<A, B>();
+ for ( int i=0, n=ArrayUtil.size( objs ) ; i<n ; ++i )
+ {
+ if ( 2 != objs[i].length )
+ {
+ continue;
+ }
+ map.put( (A) objs[i][0], (B) objs[i][1] );
+ }
+ return map;
+ }
+
+ /**
+ * Add {@link Properties}'s key-value pairs to <code>map</code>
+ *
+ * @param props {@link Properties} to provide key-value pairs
+ * @param map {@link Map} to be added
+ */
+ public static
+ void
+ mergePropertiesIntoMap(
+ final Properties props,
+ final Map<Object, Object> map
+ )
+ {
+ if ( null == map )
+ {
+ throw new NullPointerException();
+ }
+ if ( null == props )
+ {
+ return ;
+ }
+
+ final Enumeration<?> en = props.propertyNames();
+ while ( en.hasMoreElements() )
+ {
+ final String key = (String) en.nextElement();
+ map.put( key, props.getProperty( key ) );
+ }
+ }
+
+ /**
+ * Return string to present {@link Map} for human
+ *
+ * @param map {@link Map} to print out
+ *
+ * @return string of presentation
+ */
+ public static
+ String
+ toString(
+ final Map<?, ?> map
+ )
+ {
+ if ( null == map )
+ {
+ return NULL_STRING;
+ }
+
+ final StringBuilder buffer = new StringBuilder();
+ buffer.append( "{" );
+
+ if ( !map.isEmpty() )
+ {
+ buffer.append( "\n" );
+ for ( final Object key : map.keySet() )
+ {
+ buffer.append( "\t" );
+ buffer.append( key.toString() );
+ buffer.append( "=" );
+ buffer.append( map.get( key ) );
+ buffer.append( "\n" );
+ }
+ }
+ buffer.append( "}" );
+ return buffer.toString();
+ }
+
+}
diff --git a/org.tizen.common/src/org/tizen/common/util/NotificationType.java b/org.tizen.common/src/org/tizen/common/util/NotificationType.java
index 3e8d5a8a7..ede8c87f5 100644
--- a/org.tizen.common/src/org/tizen/common/util/NotificationType.java
+++ b/org.tizen.common/src/org/tizen/common/util/NotificationType.java
@@ -25,7 +25,7 @@
package org.tizen.common.util;
import org.eclipse.swt.graphics.Image;
-import org.tizen.common.cache.ImageCache;
+import org.tizen.common.util.cache.ImageCache;
public enum NotificationType {
diff --git a/org.tizen.common/src/org/tizen/common/util/NotifierDialog.java b/org.tizen.common/src/org/tizen/common/util/NotifierDialog.java
index 047425327..3944a1954 100644
--- a/org.tizen.common/src/org/tizen/common/util/NotifierDialog.java
+++ b/org.tizen.common/src/org/tizen/common/util/NotifierDialog.java
@@ -41,14 +41,13 @@ 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.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.ui.PlatformUI;
-import org.tizen.common.cache.ColorCache;
-import org.tizen.common.cache.FontCache;
+import org.tizen.common.util.cache.ColorCache;
+import org.tizen.common.util.cache.FontCache;
public class NotifierDialog {
@@ -133,7 +132,7 @@ public class NotifierDialog {
// get the size of the drawing area
Rectangle rect = _shell.getClientArea();
// create a new image with that size
- Image newImage = new Image(Display.getDefault(), Math.max(1, rect.width), rect.height);
+ Image newImage = new Image(SWTUtil.getDisplay(), Math.max(1, rect.width), rect.height);
// create a GC object we can use to draw with
GC gc = new GC(newImage);
@@ -315,14 +314,14 @@ public class NotifierDialog {
}
_shell.setAlpha(cur);
- Display.getDefault().timerExec(FADE_TIMER, this);
+ SWTUtil.getDisplay().timerExec(FADE_TIMER, this);
} catch (Exception err) {
err.printStackTrace();
}
}
};
- Display.getDefault().timerExec(FADE_TIMER, run);
+ SWTUtil.getDisplay().timerExec(FADE_TIMER, run);
}
private static void startTimer(final Shell _shell) {
@@ -340,7 +339,7 @@ public class NotifierDialog {
}
};
- Display.getDefault().timerExec(DISPLAY_TIME, run);
+ SWTUtil.getDisplay().timerExec(DISPLAY_TIME, run);
}
@@ -367,7 +366,7 @@ public class NotifierDialog {
_shell.setAlpha(cur);
- Display.getDefault().timerExec(FADE_TIMER, this);
+ SWTUtil.getDisplay().timerExec(FADE_TIMER, this);
} catch (Exception err) {
err.printStackTrace();
@@ -375,7 +374,7 @@ public class NotifierDialog {
}
};
- Display.getDefault().timerExec(FADE_TIMER, run);
+ SWTUtil.getDisplay().timerExec(FADE_TIMER, run);
}
}
diff --git a/org.tizen.common/src/org/tizen/common/util/OSChecker.java b/org.tizen.common/src/org/tizen/common/util/OSChecker.java
index 3331a46ac..9890ab0c6 100644
--- a/org.tizen.common/src/org/tizen/common/util/OSChecker.java
+++ b/org.tizen.common/src/org/tizen/common/util/OSChecker.java
@@ -26,6 +26,7 @@ package org.tizen.common.util;
/**
* @author Changhyun Lee {@literal <changhyun1.lee@samsung.com>} (S-Core)
+ * @author Gyeongseok Seo {@literal <gyeongseok.seo@samsung.com>} (S-Core)
* <ul>
* <li> initial creation
* <li> thanks to Yoon Kyung Koo
@@ -35,12 +36,14 @@ public class OSChecker {
//
// OS ID constants
//
- public final static int WINDOWS = 0x0001;
- public final static int MAC = 0x0002;
- public final static int LINUX = 0x0004;
- public final static int UNIX = 0x0008;
- public final static int AIX = 0x0010;
- public final static int SOLARIS = 0x0020;
+ public final static int WINDOWS = 0x0100;
+ public final static int WINDOWSXP = 0x0101;
+ public final static int WINDOWS7 = 0x0102;
+ public final static int MAC = 0x0200;
+ public final static int LINUX = 0x0400;
+ public final static int UNIX = 0x0800;
+ public final static int AIX = 0x1000;
+ public final static int SOLARIS = 0x2000;
//
// Vendor constants
@@ -71,6 +74,11 @@ public class OSChecker {
if (osName.indexOf("WINDOWS") >= 0) {
osID |= OSChecker.WINDOWS;
+ if ( ObjectUtil.equals(osName, "WINDOWS XP") ) {
+ osID |= OSChecker.WINDOWSXP;
+ } else if ( ObjectUtil.equals(osName, "WINDOWS 7") ) {
+ osID |= OSChecker.WINDOWS7;
+ }
} else if (osName.indexOf("MAC") >= 0) {
osID |= OSChecker.MAC;
} else if (osName.indexOf("LINUX") >= 0) {
@@ -108,6 +116,13 @@ public class OSChecker {
return ((osID & OSChecker.WINDOWS) > 0);
}
+ public static boolean isWindowsXP() {
+ return (osID == OSChecker.WINDOWSXP);
+ }
+ public static boolean isWindows7() {
+ return (osID == OSChecker.WINDOWS7);
+ }
+
public static boolean isMAC() {
return ((osID & OSChecker.MAC) > 0);
}
@@ -157,4 +172,14 @@ public class OSChecker {
return (vendorID == 0);
}
+ /* querying arch */
+ public static boolean is64bit() {
+ boolean is64bit = false;
+ if ( OSChecker.isWindows() ) {
+ is64bit = (System.getenv("ProgramFiles(x86)") != null);
+ } else {
+ is64bit = (System.getProperty("os.arch").indexOf("64") != -1);
+ }
+ return is64bit;
+ }
}
diff --git a/org.tizen.common/src/org/tizen/common/util/ObjectUtil.java b/org.tizen.common/src/org/tizen/common/util/ObjectUtil.java
new file mode 100644
index 000000000..3c0f2f8e6
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/util/ObjectUtil.java
@@ -0,0 +1,411 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* BonYong Lee <bonyong.lee@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+package org.tizen.common.util;
+
+import static org.tizen.common.util.StringUtil.NULL_STRING;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.security.SecureRandom;
+import java.util.Arrays;
+import java.util.Collection;
+
+/**
+ * ObjectUtil.
+ *
+ * Helper related to <code>Object</code> or generic logic
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ */
+public class ObjectUtil {
+
+ /**
+ * protected constructor
+ */
+ protected ObjectUtil() {}
+
+ /**
+ * Returns first non-null element in args
+ * <br>
+ * Returns null if no non-null element
+ *
+ * @param <T> arguments' type
+ * @param args arguments to check
+ *
+ * @return non-null element in <code>args</code>
+ */
+ public static <T> T nvl( T... args )
+ {
+ if ( null == args )
+ {
+ return null;
+ }
+
+ for ( final T arg : args )
+ {
+ if ( null != arg )
+ {
+ return arg;
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Hexadecimal IP
+ */
+ private static String hexServerIP = null;
+
+ /**
+ * Seed generator for GUID
+ */
+ private static final SecureRandom SEEDER = new SecureRandom();
+
+ /**
+ * Compares two objects.
+ * <br>
+ * {@link Object#equals(Object)} is used for equality but this needs null check.
+ * <br>
+ * two object are equal if both are <code>null</code>
+ * <br>
+ * <pre>
+ * if ( null == obj1 ) {
+ * if ( obj1 == obj2 ) {
+ * ...
+ * }
+ * } else if ( obj1.equals( obj2 ) ) {
+ * ...
+ * }
+ * </pre>
+ * If you use this method
+ * <pre>
+ * if ( ObjectUtils.equals( obj1, obj2 ) ) {
+ * ...
+ * }
+ * </pre>
+ * Recursively compre if object is {@link Collection} or array
+ * <br>
+ *
+ * @param obj1 object1 to compare
+ * @param obj2 object2 to compare
+ *
+ * @return <code>true</code> if two object are equal
+ */
+ @SuppressWarnings({
+ "unchecked", "rawtypes"
+ })
+ public static
+ boolean
+ equals(
+ final Object obj1,
+ final Object obj2
+ )
+ {
+ if ( obj1 == obj2 )
+ {
+ return true;
+ }
+ if ( null == obj1 || null == obj2 )
+ {
+ return false;
+ }
+
+ if ( !obj1.getClass().isArray() || !obj2.getClass().isArray() )
+ {
+ return obj1.equals( obj2 );
+ }
+
+ // in case of array
+ if ( obj1 instanceof boolean[] && obj2 instanceof boolean[] )
+ {
+ return Arrays.equals( ( boolean[] ) obj1, ( boolean[] ) obj2 );
+ }
+ else if ( obj1 instanceof byte[] && obj2 instanceof byte[] )
+ {
+ return Arrays.equals( ( byte[] ) obj1, ( byte[] ) obj2 );
+ }
+ else if ( obj1 instanceof char[] && obj2 instanceof char[] )
+ {
+ return Arrays.equals( ( char[] ) obj1, ( char[] ) obj2 );
+ }
+ else if ( obj1 instanceof double[] && obj2 instanceof double[] )
+ {
+ return Arrays.equals( ( double[] ) obj1, ( double[] ) obj2 );
+ }
+ else if ( obj1 instanceof float[] && obj2 instanceof float[] )
+ {
+ return Arrays.equals( ( float[] ) obj1, ( float[] ) obj2 );
+ }
+ else if ( obj1 instanceof int[] && obj2 instanceof int[] )
+ {
+ return Arrays.equals( ( int[] ) obj1, ( int[] ) obj2 );
+ }
+ else if ( obj1 instanceof long[] && obj2 instanceof long[] )
+ {
+ return Arrays.equals( ( long[] ) obj1, ( long[] ) obj2 );
+ }
+ else if ( obj1 instanceof short[] && obj2 instanceof short[] )
+ {
+ return Arrays.equals( ( short[] ) obj1, ( short[] ) obj2 );
+ }
+ else if ( obj1 instanceof Collection && obj2 instanceof Collection )
+ {
+ return CollectionUtil.equals( (Collection) obj1, (Collection) obj2 );
+ }
+ else if ( obj1 instanceof Object[] && obj2 instanceof Object[] )
+ {
+ return CollectionUtil.equals( (Object[]) obj1, (Object[]) obj2 );
+ }
+ return false;
+ }
+
+ /**
+ * Convert byte[] to integer
+ *
+ * @param bytes byte array to convert
+ *
+ * @return converted integer
+ */
+ public static
+ int
+ getInt(
+ final byte bytes[]
+ )
+ {
+ int i= 0;
+ int j= 24;
+ for( int k=0 ; 0<=j ; ++k )
+ {
+ int l = bytes[k] & 0xff;
+ i += l << j;
+ j -= 8;
+ }
+ return i;
+ }
+
+ /**
+ * Pad <code>str</code> to string with <code>length</code> length
+ *
+ * Return <code>str</code> if string's length is greater than <code>length</code>
+ *
+ * The padding character is '0'
+ *
+ * @param str string to pad
+ * @param length length to pad
+ *
+ * @return padded string
+ */
+ private static
+ String
+ padHex(
+ final String str,
+ final int length
+ )
+ {
+ final StringBuilder buffer = new StringBuilder();
+ for( int j=0, n=length-str.length() ; j<n ; ++j )
+ {
+ buffer.append( '0' );
+ }
+ buffer.append( str );
+ return buffer.toString();
+ }
+
+ /**
+ * Convert <code>i</code> to hexadecimal with <code>j</code> length
+ *
+ * @param i decimal to convert
+ * @param j hexadecimal's length
+ *
+ * @return converted hexadecimal
+ */
+ public static
+ String
+ hexFormat(
+ final int i,
+ final int j
+ )
+ {
+ final String s = Integer.toHexString( i );
+ return padHex( s, j );
+ }
+
+
+ /**
+ * Create GUID with 32 bytes
+ *
+ * GUID is used for system( programe ) not human
+ *
+ * Structure
+ * +-----------------+--------------+----------------------+------------------+
+ * | Current Time(8) | Server IP(8) | Object Hash Value(8) | Random Number(8) |
+ * +-----------------+--------------+----------------------+------------------+
+ *
+ * @param obj object to hash
+ * @return create guid
+ */
+ public static final
+ String
+ generateGUID(
+ final Object obj
+ )
+ {
+ final StringBuilder guid = new StringBuilder( 32 );
+
+ // time
+ long timeNow = System.currentTimeMillis();
+ int timeLow = (int) timeNow& 0xFFFFFFFF;
+ guid.append( hexFormat( timeLow, 8 ) );
+
+ // server IP
+ if ( null == hexServerIP )
+ {
+ InetAddress localInetAddress = null;
+ try
+ {
+ // get the inet address
+ localInetAddress = InetAddress.getLocalHost();
+ }
+ catch( final UnknownHostException uhe )
+ {
+ try
+ {
+ localInetAddress = InetAddress.getByName( "localhost" );
+ }
+ catch ( final UnknownHostException e )
+ {
+ e.printStackTrace();
+ return null;
+ }
+ }
+
+ byte serverIP[] = localInetAddress.getAddress();
+
+ hexServerIP = hexFormat( getInt( serverIP ), 8 );
+ }
+ guid.append( hexServerIP );
+
+ // object hash
+ guid.append( hexFormat( System.identityHashCode( obj ), 8 ) );
+
+ // random number
+ int node= -1;
+ synchronized( SEEDER )
+ {
+ node = SEEDER.nextInt();
+ }
+ guid.append( hexFormat( node, 8 ) );
+ return guid.toString();
+ }
+
+ /* Serialize / Deserialize */
+ /**
+ * Serialize object
+ *
+ * @param obj object to serialize
+ *
+ * @return serialized byte array
+ *
+ * @throws IOException If serialization is fail
+ *
+ * @see ObjectOutputStream#writeObject( Object )
+ */
+ public static
+ byte[]
+ serialize(
+ final Object obj
+ )
+ throws IOException
+ {
+ final ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
+ final ObjectOutputStream objOut = new ObjectOutputStream( byteOut );
+ objOut.writeObject( obj );
+ return byteOut.toByteArray();
+ }
+
+ /**
+ * Deserialize byte array
+ *
+ * @param bytes bytes to deserialize
+ *
+ * @return Deserialized object
+ *
+ * @throws IOException If deserialization is fail
+ *
+ * @throws ClassNotFoundException If No class
+ *
+ * @see ObjectInputStream#readObject()
+ */
+ public static
+ Object
+ deserialize(
+ final byte[] bytes
+ )
+ throws IOException, ClassNotFoundException
+ {
+ Assert.notNull( bytes, "bytes must not be null" );
+ final ByteArrayInputStream byteIn = new ByteArrayInputStream( bytes );
+ final ObjectInputStream objIn = new ObjectInputStream( byteIn );
+ return objIn.readObject();
+ }
+
+ /**
+ * Create and return object's simple name
+ *
+ * Use 4 hash value instead of 8 hash value
+ *
+ * @param obj object to convert
+ *
+ * @return textual string for <code>obj</code>
+ */
+ public static
+ String
+ toString(
+ final Object obj
+ )
+ {
+ if ( null == obj )
+ {
+ return NULL_STRING;
+ }
+ final StringBuilder builder = new StringBuilder();
+ builder.append( obj.getClass().getSimpleName() );
+ builder.append( '@' );
+ int hash = obj.hashCode();
+
+ for ( int i = 8 ; i>=0 ; i-=8 )
+ {
+ StringUtil.appendHexa( builder, 0xFF & ( hash >> i ) );
+ }
+
+
+ return builder.toString();
+ }
+}
diff --git a/org.tizen.common/src/org/tizen/common/util/ParsingUtil.java b/org.tizen.common/src/org/tizen/common/util/ParsingUtil.java
new file mode 100644
index 000000000..6d91b9430
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/util/ParsingUtil.java
@@ -0,0 +1,183 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* BonYong Lee <bonyong.lee@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+package org.tizen.common.util;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashSet;
+
+/**
+ * ParsingUtil.
+ *
+ * Helper related to parsing of textual implication
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ */
+public class ParsingUtil
+{
+
+ /**
+ * semantic <code>true</code>
+ */
+ protected static final Collection<String> BOOLEAN_TRUE =
+ Collections.unmodifiableCollection( new HashSet<String>( Arrays.asList(
+ "1", "yes", "y", "true", "t"
+ ) ) );
+
+ /**
+ * sematic <code>false</code>
+ */
+ protected static final Collection<String> BOOLEAN_FALSE =
+ Collections.unmodifiableCollection( new HashSet<String>( Arrays.asList(
+ "no, n", "false", "f", "0"
+ ) ) );
+
+ /**
+ * parse text and convert to <code>boolean</code>
+ *
+ * return <code>defaultValue</code> if can't parse or convert
+ *
+ * @param value string to parse
+ * @param defaultValue default value when exception case
+ *
+ * @return converted <code>boolean</code> value
+ */
+ public static
+ boolean
+ parseBoolean(
+ final String value,
+ final boolean defaultValue
+ )
+ {
+ if ( null == value )
+ {
+ return defaultValue;
+ }
+
+ final String safe = StringUtil.trim( value ).toLowerCase();
+ return ((defaultValue)?BOOLEAN_FALSE:BOOLEAN_TRUE).contains( safe ) ^ defaultValue;
+
+ }
+
+ /**
+ * parse text and convert to <code>int</code>
+ *
+ * return <code>defaultValue</code> if can't parse or convert
+ *
+ * @param value string to parse
+ * @param defaultValue default value when exception case
+ *
+ * @return converted <code>int</code> value
+ */
+ public static
+ int parseInt(
+ final String value,
+ final int defaultValue
+ )
+ {
+ if ( null == value )
+ {
+ return defaultValue;
+ }
+
+ final String trimmed = StringUtil.trim( value );
+ try
+ {
+ return Integer.decode( trimmed );
+ } catch ( final Throwable e )
+ {
+ return defaultValue;
+ }
+ }
+
+ /**
+ * parse text and convert to <code>long</code>
+ *
+ * return <code>defaultValue</code> if can't parse or convert
+ *
+ * @param value string to parse
+ * @param defaultValue default value when exception case
+ *
+ * @return converted <code>long</code> value
+ */
+ public static
+ long
+ parseLong(
+ final String value,
+ final long defaultValue
+ )
+ {
+ if ( null == value )
+ {
+ return defaultValue;
+ }
+
+ final String trimmed = StringUtil.trim( value );
+ try
+ {
+ return Long.decode( trimmed );
+ } catch ( final Throwable e )
+ {
+ return defaultValue;
+ }
+
+ }
+
+ /**
+ * parse text and convert to <code>double</code>
+ *
+ * return <code>defaultValue</code> if can't parse or convert
+ *
+ * @param value string to parse
+ * @param defaultValue default value when exception case
+ *
+ * @return converted <code>double</code> value
+ */
+ public static
+ double
+ parseDouble(
+ final String value,
+ final double defaultValue
+ )
+ {
+ if ( null == value )
+ {
+ return defaultValue;
+ }
+
+ final String trimmed = StringUtil.trim( value );
+ try
+ {
+ return Double.valueOf( trimmed );
+ }
+ catch( final Throwable e )
+ {
+ return defaultValue;
+ }
+
+ }
+
+}
diff --git a/org.tizen.common/src/org/tizen/common/util/PluginUtil.java b/org.tizen.common/src/org/tizen/common/util/PluginUtil.java
new file mode 100644
index 000000000..a451c4877
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/util/PluginUtil.java
@@ -0,0 +1,105 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* Kangho Kim <kh5325.kim@samsung.com>
+* Ho Namkoong <ho.namkoong@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+
+package org.tizen.common.util;
+
+import java.util.ArrayList;
+import java.util.List;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IConfigurationElement;
+import org.eclipse.core.runtime.IExtension;
+import org.eclipse.core.runtime.IExtensionPoint;
+import org.eclipse.core.runtime.IExtensionRegistry;
+import org.eclipse.core.runtime.Platform;
+import org.tizen.common.Surrogate;
+
+/**
+ * PluginUtil
+ *
+ * This is a util class for handle extension points of the plugins.
+ *
+ * @author Ho Namkoong{@literal <ho.namkoong@samsung.com>} (S-Core)
+ */
+public class PluginUtil {
+
+ protected static Surrogate<IExtensionRegistry> platformSurrogate = new Surrogate<IExtensionRegistry>() {
+ public IExtensionRegistry getAdapter()
+ {
+ return Platform.getExtensionRegistry();
+ }
+ };
+
+ /**
+ * Return classes of specific extension point id.
+ * @param extPointId - extension point id.
+ * @return object array of classes of extPointId.
+ */
+ public static Object[] loadClasses(String extPointId) throws CoreException {
+ IExtensionRegistry registry = platformSurrogate.getAdapter();
+ IExtensionPoint ep = registry.getExtensionPoint(extPointId );
+ IExtension[] exts = ep.getExtensions();
+ List<Object> classList = new ArrayList<Object>();
+
+ for ( IExtension ext : exts )
+ {
+ IConfigurationElement[] configs = ext.getConfigurationElements();
+
+ for ( final IConfigurationElement config : configs )
+ {
+ Object cls = (Object) config.createExecutableExtension( "class" );
+ classList.add(cls);
+ }
+ }
+
+ return classList.toArray();
+ }
+
+ /**
+ * Return class of specific class id which extends specific extension point id.
+ * @param extPointId - extension point id.
+ * @param classId - class id.
+ * @return object class of specific class id which extends specific extension point id.
+ */
+ public static Object loadClass(String extPointId, String classId) throws CoreException {
+ IExtensionRegistry registry = platformSurrogate.getAdapter();
+ IExtensionPoint ep = registry.getExtensionPoint(extPointId );
+ IExtension[] exts = ep.getExtensions();
+
+ for ( IExtension ext : exts )
+ {
+ IConfigurationElement[] configs = ext.getConfigurationElements();
+
+ for ( final IConfigurationElement config : configs )
+ {
+ String id = config.getAttribute("id");
+ if(id != null && id.equals(classId)) {
+ return (Object) config.createExecutableExtension( "class" );
+ }
+ }
+ }
+ return null;
+ }
+}
diff --git a/org.tizen.common/src/org/tizen/common/util/ProjectUtil.java b/org.tizen.common/src/org/tizen/common/util/ProjectUtil.java
new file mode 100644
index 000000000..31acf7d30
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/util/ProjectUtil.java
@@ -0,0 +1,199 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* Jihoon Song <jihoon80.song@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+
+package org.tizen.common.util;
+
+import java.util.Map;
+
+import org.eclipse.core.resources.ICommand;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IProjectDescription;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.tizen.common.util.log.Logger;
+
+/**
+ * ProjectUtil.
+ *
+ * Helper related to the Eclipse Project (.project)
+ *
+ * @author Jihoon Song{@literal <jihoon80.song@samsung.com>} (S-Core)
+ */
+public class ProjectUtil {
+
+ /**
+ * Null safety project description getter. If project is null, return null.
+ * @param project
+ * @return IProjectDescription
+ * @throws CoreException
+ */
+ public static IProjectDescription getDescription(IProject project) throws CoreException {
+ return (project != null) ? project.getDescription() : null;
+ }
+
+ /**
+ * Null safety project build specification getter
+ * @param project
+ * @return ICommand[]
+ * @throws CoreException
+ */
+ public static ICommand[] getBuildSpec(IProject project) throws CoreException {
+ IProjectDescription description = getDescription( project );
+ return (description != null) ? description.getBuildSpec() : new ICommand[0];
+ }
+
+ /**
+ * Build specification setter
+ * @param project
+ * @param commands
+ * @param monitor a progress monitor, or <code>null</code> if progress reporting is not desired
+ * @throws CoreException
+ */
+ public static void setBuildSpec(IProject project, ICommand[] commands, IProgressMonitor monitor)
+ throws CoreException {
+ IProjectDescription description = getDescription( project );
+ if ( description != null ) { // if project or project description is not null
+ description.setBuildSpec( commands );
+ project.setDescription( description, monitor );
+ }
+ }
+
+ /**
+ * Null safety build command adder
+ * @param oldCommands
+ * @param newCommand
+ * @return ICommand[]
+ */
+ public static ICommand[] addCommand(ICommand[] oldCommands, ICommand newCommand) {
+ // if newCommand is Null
+ if ( newCommand == null ) {
+ if ( oldCommands == null ) { // if argument is Null both, return 0-based array
+ return new ICommand[0];
+ } else {
+ return oldCommands;
+ }
+ }
+
+ // create expanded commands
+ ICommand[] newCommands;
+ if ( oldCommands != null ) {
+ newCommands = new ICommand[ oldCommands.length + 1 ];
+ System.arraycopy( oldCommands, 0, newCommands, 0, oldCommands.length );
+ } else {
+ newCommands = new ICommand[ 1 ];
+ }
+
+ // add new command to last index
+ newCommands[ newCommands.length - 1 ] = newCommand;
+
+ return newCommands;
+ }
+
+ /**
+ * Null safety build command finder. If not found, return null.
+ * @param commands
+ * @param builderID
+ * @return ICommand
+ */
+ public static ICommand findCommand(ICommand[] commands, String builderID) {
+ if ( commands != null ) {
+ for (ICommand command : commands) {
+ String builderName = command.getBuilderName();
+ if ( builderName != null && builderName.equals( builderID ) ){
+ return command;
+ }
+ }
+ }
+
+ return null;
+ }
+
+ /**
+ * Null safety build command creater. If project or project description is null, return null.
+ * @param project
+ * @return ICommand
+ * @throws CoreException
+ */
+ public static ICommand newCommand(IProject project) throws CoreException {
+ IProjectDescription description = getDescription( project );
+ return (description != null) ? description.newCommand() : null;
+ }
+
+ /**
+ * Specific build command adder with arguments. If builder ID already exist or is null, ignore this process.
+ * @param project
+ * @param builderID a builder name
+ * @param args a table of command arguments (keys and values must both be of type <code>String</code>), or <code>null</code>
+ * @param monitor a progress monitor, or <code>null</code> if progress reporting is not desired
+ */
+ public static void setBuildCommandWithArgument(IProject project, String builderID,
+ Map<String, String> args, IProgressMonitor monitor) {
+ if ( builderID == null ) { // If builder ID is null
+ return ;
+ }
+
+ try {
+ ICommand[] commands = getBuildSpec( project );
+
+ ICommand findedCommand = findCommand( commands, builderID );
+ if ( findedCommand != null ) { // If builder ID already exist
+ return;
+ }
+
+ ICommand command = newCommand( project );
+ if ( command == null ) {
+ return;
+ }
+
+ command.setBuilderName( builderID );
+ command.setArguments( args );
+
+ ICommand[] newCommands = addCommand( commands, command );
+ setBuildSpec( project, newCommands, monitor );
+ } catch (CoreException e) {
+ Logger.log(e);
+ }
+ }
+
+ /**
+ * Arguments getter in specific build command. If not found, return null.
+ * @param project
+ * @param builderID
+ * @return a table of command arguments (key type : <code>String</code> value type : <code>String</code>), or <code>null</code>
+ */
+ public static Map<String, String> getBuildCommandArgument(IProject project, String builderID) {
+ try {
+ ICommand[] commands = getBuildSpec( project );
+ ICommand command = findCommand( commands, builderID );
+ if ( command != null ) {
+ return command.getArguments();
+ }
+ } catch (CoreException e) {
+ Logger.log(e);
+ }
+
+ return null;
+ }
+}
diff --git a/org.tizen.common/src/org/tizen/common/util/PropertyUtil.java b/org.tizen.common/src/org/tizen/common/util/PropertyUtil.java
index 2f7ac97b4..9e338c3ca 100644
--- a/org.tizen.common/src/org/tizen/common/util/PropertyUtil.java
+++ b/org.tizen.common/src/org/tizen/common/util/PropertyUtil.java
@@ -24,11 +24,12 @@
*/
package org.tizen.common.util;
+import static org.tizen.common.util.IOUtil.tryClose;
+
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
-import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
@@ -52,11 +53,7 @@ public abstract class PropertyUtil {
} catch (Exception e) {
e.printStackTrace();
} finally {
- if (reader != null)
- try {
- reader.close();
- } catch (IOException e) {
- }
+ tryClose( reader );
}
return props;
}
@@ -68,11 +65,7 @@ public abstract class PropertyUtil {
} catch (Exception e) {
e.printStackTrace();
} finally {
- if (inputStream != null)
- try {
- inputStream.close();
- } catch (IOException e) {
- }
+ tryClose( inputStream );
}
return props;
}
@@ -84,11 +77,7 @@ public abstract class PropertyUtil {
e.printStackTrace();
return false;
} finally {
- if (outputStream != null)
- try {
- outputStream.close();
- } catch (IOException e) {
- }
+ tryClose( outputStream );
}
return true;
}
@@ -103,11 +92,7 @@ public abstract class PropertyUtil {
e.printStackTrace();
return false;
} finally {
- if (writer != null)
- try {
- writer.close();
- } catch (IOException e) {
- }
+ tryClose( writer );
}
return true;
}
diff --git a/org.tizen.common/src/org/tizen/common/util/SWTRunner.java b/org.tizen.common/src/org/tizen/common/util/SWTRunner.java
new file mode 100755
index 000000000..ed2868242
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/util/SWTRunner.java
@@ -0,0 +1,44 @@
+package org.tizen.common.util;
+
+import org.tizen.common.Cabinet;
+
+abstract public class
+SWTRunner<T>
+implements Runnable, Cabinet<T>
+{
+ protected T data;
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.Cabinet#getData()
+ */
+ @Override
+ public
+ T
+ getData()
+ {
+ return data;
+ }
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.Cabinet#setData(java.lang.Object)
+ */
+ @Override
+ public
+ void
+ setData(
+ final T data
+ )
+ {
+ this.data = data;
+ }
+
+ @Override
+ public void run()
+ {
+ setData( process() );
+ }
+
+ abstract protected T process();
+
+
+}
diff --git a/org.tizen.common/src/org/tizen/common/util/SWTUtil.java b/org.tizen.common/src/org/tizen/common/util/SWTUtil.java
index e9c6f1981..4ee8c7893 100644..100755
--- a/org.tizen.common/src/org/tizen/common/util/SWTUtil.java
+++ b/org.tizen.common/src/org/tizen/common/util/SWTUtil.java
@@ -26,29 +26,206 @@ package org.tizen.common.util;
import java.awt.Dimension;
import java.awt.Toolkit;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Stack;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IStatus;
+import org.eclipse.core.runtime.MultiStatus;
+import org.eclipse.core.runtime.Status;
+import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.events.VerifyEvent;
import org.eclipse.swt.events.VerifyListener;
+import org.eclipse.swt.graphics.Resource;
import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.Text;
+import org.eclipse.swt.widgets.Tree;
+import org.eclipse.swt.widgets.TreeItem;
+import org.eclipse.swt.widgets.Widget;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorReference;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.internal.ide.IDEWorkbenchPlugin;
+import org.tizen.common.Cabinet;
+import org.tizen.common.ui.TableToolTipListener;
+@SuppressWarnings("restriction")
public class SWTUtil {
+
+ private SWTUtil() {}
+ // 2012-04-25
+ @Deprecated
public static final String HTML_EXTENSIONS[] = { "html", "htm", "shtml", "shtm", "xhtml"};
+
+ protected static final Collection<?> HTML_EXTENSIONS2 =
+ Collections.unmodifiableCollection( new HashSet<Object>( Arrays.asList( HTML_EXTENSIONS ) ) );
+
+ /**
+ * return {@link Display} in context
+ *
+ * return new {@link Display} if no {@link Display} in context
+ *
+ * @return SWT {@link Display} simply
+ *
+ * @see Display#getCurrent()
+ * @see Display#getDefault();
+ */
+ public static Display getDisplay()
+ {
+ Display dp = Display.getCurrent();
+ if ( null != dp )
+ {
+ return dp;
+ }
+
+ return Display.getDefault();
+ }
+
+ /**
+ * <p>
+ * Return active {@link Shell} in context
+ * </p>
+ * @return active {@link Shell}
+ *
+ * @see #getDisplay()
+ */
+ public static Shell getActiveShell()
+ {
+ final Display dp = getDisplay();
+ if ( null == dp )
+ {
+ return null;
+ }
+
+ return dp.getActiveShell();
+ }
+
+ /**
+ * execute {@link Cabinet#run()} and reeturn the result
+ *
+ * @param runnable object to execute
+ *
+ * @return result to execute
+ */
+ public static
+ <T>
+ T
+ exec(
+ final Cabinet<T> runnable
+ )
+ {
+ syncExec( (Runnable) runnable );
+
+ return runnable.getData();
+ }
+
+ /**
+ * execute {@link Runnable} in SWT thread synchronously
+ *
+ * @param runnable object to execute
+ */
+ public static void syncExec( final Runnable runnable )
+ {
+ syncExec( getDisplay(), runnable );
+ }
+
+ /**
+ * execute {@link Runnable} in SWT thread synchronously
+ *
+ * @param dp SWT <code>Display</code>
+ * @param runnable object to execute
+ */
+ public static void syncExec( final Display dp, final Runnable runnable )
+ {
+ dp.syncExec( runnable );
+ }
+
+ /**
+ * execute {@link Runnable} in SWT thread asynchronously
+ *
+ * @param runnable object to execute
+ */
+ public static void asyncExec( final Runnable runnable )
+ {
+ asyncExec( getDisplay(), runnable );
+ }
+
+ /**
+ * execute {@link Runnable} in SWT thread asynchronously
+ *
+ * @param dp SWT <code>Display</code>
+ * @param runnable object to execute
+ */
+ public static void asyncExec( final Display dp, final Runnable runnable )
+ {
+ dp.asyncExec( runnable );
+ }
+
+ /**
+ * dispose {@link Widget}s
+ *
+ * @param disposables {@link Widget}s to dispose
+ */
+ public static void tryDispose( final Widget... disposables )
+ {
+ if ( null == disposables )
+ {
+ return ;
+ }
+
+ for ( final Widget disposable : disposables )
+ {
+ if ( null == disposable || disposable.isDisposed() )
+ {
+ continue;
+ }
+
+ disposable.dispose();
+ }
+ }
+
+ /**
+ * dispose {@link Resource}s
+ *
+ * @param disposables {@link Resource}s to dispose
+ */
+ public static void tryDispose( final Resource... disposables )
+ {
+ if ( null == disposables )
+ {
+ return ;
+ }
+
+ for ( final Resource disposable : disposables )
+ {
+ if ( null == disposable || disposable.isDisposed() )
+ {
+ continue;
+ }
+
+ disposable.dispose();
+ }
+ }
/**
* Creates SWT <code>Text</code> for input limited digit.
@@ -80,6 +257,7 @@ public class SWTUtil {
/**
* Creates SWT <code>ScrolledComposite</code>.
+ *
* @param width the minimum width or 0 for default width (0 is screen width)
* @param height the minimum height or 0 for default height (0 is screen height)
* @return <code>ScrolledComposite</code>
@@ -103,6 +281,24 @@ public class SWTUtil {
return sc;
}
+
+ /**
+ * Get current active page.
+ *
+ * return null if no active page
+ *
+ * @return active page
+ */
+ public static IWorkbenchPage getActivePage()
+ {
+ final IWorkbenchWindow window = ViewUtil.getWorkbenchWindow();
+
+ if ( null == window )
+ {
+ return null;
+ }
+ return window.getActivePage();
+ }
/**
* Get current active editor.
@@ -111,21 +307,15 @@ public class SWTUtil {
* @author Changhyun Lee {@literal <changhyun1.lee@samsung.com>} (S-Core)
*/
public static IEditorPart getActiveEditor() {
- IWorkbenchWindow window = ViewUtil.getWorkbenchWindow();
- IWorkbenchPage page = window.getActivePage();
-
- if(page == null){
- return null;
- }
-
- IEditorPart editor = page.getActiveEditor();
- if(editor == null){
+ final IWorkbenchPage page = getActivePage();
+ if(page == null )
+ {
return null;
}
- return editor;
+ return page.getActiveEditor();
}
-
+
/**
* Get editor of file extension.
*
@@ -175,17 +365,9 @@ public class SWTUtil {
* @author Changhyun Lee {@literal <changhyun1.lee@samsung.com>} (S-Core)
*/
public static boolean isHtmlFile(String fullName) {
- String fileExt = FileUtil.getFileExtension(fullName);
- if (fileExt == null) {
- return false;
- }
+ String fileExt = StringUtil.nvl( FileUtil.getFileExtension(fullName) );
- for (String htmlExt : HTML_EXTENSIONS) {
- if (htmlExt.equalsIgnoreCase(fileExt)) {
- return true;
- }
- }
- return false;
+ return HTML_EXTENSIONS2.contains( fileExt.toLowerCase() );
}
/**
@@ -239,4 +421,72 @@ public class SWTUtil {
return projectPath;
}
-} \ No newline at end of file
+
+ public static void addTableToolTipListener(Table table, TableToolTipListener listener) {
+ listener.setTable(table);
+ table.addListener(SWT.MouseMove, listener);
+ table.addListener(SWT.MouseWheel, listener);
+ table.addListener(SWT.Dispose, listener);
+ table.addListener(SWT.MouseHover, listener);
+ }
+
+ /**
+ * Expands tree and its sub treeitems.
+ *
+ * @param tree target tree to expand.
+ * @author Ho Namkoong {@literal <ho.namkoong@samsung.com>} (S-Core)
+ */
+ public static void expandTree(Tree tree) {
+ if(tree == null) {
+ return;
+ }
+ for(TreeItem treeitem: tree.getItems()) {
+ expandTreeItem(treeitem);
+ }
+ }
+
+ private static void expandTreeItem(TreeItem treeItem) {
+ Stack<TreeItem> treeStack = new Stack<TreeItem>();
+ treeStack.add(treeItem);
+ TreeItem selectedItem = null;
+
+ do {
+ selectedItem = treeStack.pop();
+ selectedItem.setExpanded(true);
+
+ if(selectedItem.getItems() != null && selectedItem.getItemCount() != 0) {
+ for (TreeItem childItem : selectedItem.getItems()) {
+ treeStack.add(childItem);
+ }
+ }
+ } while (!treeStack.isEmpty());
+ }
+
+ /**
+ * Make error dialog which prints stack trace of the throwable
+ *
+ * @param title title of the dialog
+ * @param msg message of the dialog
+ * @param t throwable diaog prints out
+ * @param shell parent shell of this dialog
+ * @author Ho Namkoong {@literal <ho.namkoong@samsung.com>} (S-Core)
+ */
+ public static void errorDialogWithStackTrace(String title, String msg, Throwable t, String pluginId, Shell shell) {
+
+ StringWriter sw = new StringWriter();
+ PrintWriter pw = new PrintWriter(sw);
+ t.printStackTrace(pw);
+
+ final String trace = sw.toString();
+
+ List<Status> childStatuses = new ArrayList<Status>();
+
+ for(String line: trace.split("\n")) {
+ childStatuses.add(new Status(IStatus.ERROR, pluginId, line));
+ }
+
+ MultiStatus ms = new MultiStatus(pluginId, IStatus.ERROR, childStatuses.toArray(new Status[] {}), t.getLocalizedMessage(), t);
+
+ ErrorDialog.openError(shell, "Error Dialog", msg, ms);
+ }
+}
diff --git a/org.tizen.common/src/org/tizen/common/util/SdbCommandUtil.java b/org.tizen.common/src/org/tizen/common/util/SdbCommandUtil.java
new file mode 100644
index 000000000..4e2545632
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/util/SdbCommandUtil.java
@@ -0,0 +1,76 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* Gun Kim <gune.kim@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+
+package org.tizen.common.util;
+
+import java.io.File;
+
+import org.tizen.common.core.application.InstallPathConfig;
+import org.tizen.sdblib.IDevice;
+
+/**
+ * SdbCommandUtil.
+ *
+ * sdb helper
+ *
+ * @author Gun Kim{@literal <gune.kim@samsung.com>} (S-Core)
+ */
+public class SdbCommandUtil {
+
+ /**
+ * push file to device
+ *
+ * @param device
+ *
+ * @param source source file path
+ *
+ * @param dest destination file path
+ */
+ public static boolean filePush(IDevice device, String source, String dest){
+ final String command_format = InstallPathConfig.getSDBPath() + " -s %s push %s %s ";
+ if ( device == null ) {
+ return false;
+ }
+
+ if ( !(new File(source).exists()) ) {
+ return false;
+ }
+
+ String command = String.format(command_format, device.getSerialNumber(), source, dest);
+ if (OSChecker.isUnix() ) {
+ command += "1>/dev/null";
+ }
+ else if (OSChecker.isWindows() ) {
+ command += "1>NUL";
+ }
+ String command_result = HostUtil.returnExecute(command);
+
+ if ( "".equals(command_result)) {
+ return true;
+ }
+
+ return false;
+ }
+} \ No newline at end of file
diff --git a/org.tizen.common/src/org/tizen/common/util/StreamGobbler.java b/org.tizen.common/src/org/tizen/common/util/StreamGobbler.java
index deae67722..da2532407 100644..100755
--- a/org.tizen.common/src/org/tizen/common/util/StreamGobbler.java
+++ b/org.tizen.common/src/org/tizen/common/util/StreamGobbler.java
@@ -24,6 +24,8 @@
*/
package org.tizen.common.util;
+import static org.tizen.common.util.IOUtil.tryClose;
+
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
@@ -50,23 +52,26 @@ public class StreamGobbler extends Thread
public void run()
{
StringBuffer buffer = new StringBuffer();
+ BufferedReader br = null;
try {
synchronized (synchronizer) {
- BufferedReader br = new BufferedReader(new InputStreamReader(is));
+ br = new BufferedReader(new InputStreamReader(is));
String line;
while ( (line = br.readLine()) != null) {
buffer.append(line);
buffer.append("\n");
if ( os != null )
+ {
os.write( (line + "\n").getBytes());
+ }
}
- br.close();
}
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
result = buffer.toString();
+ tryClose( br );
}
}
public String getResult() {
diff --git a/org.tizen.common/src/org/tizen/common/util/StringUtil.java b/org.tizen.common/src/org/tizen/common/util/StringUtil.java
index c7ccee27e..8b97822af 100644..100755
--- a/org.tizen.common/src/org/tizen/common/util/StringUtil.java
+++ b/org.tizen.common/src/org/tizen/common/util/StringUtil.java
@@ -28,10 +28,14 @@ import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
+import java.io.StringReader;
+import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
+import org.tizen.common.util.log.Logger;
+
/**
* @author Changhyun Lee {@literal <changhyun1.lee@samsung.com>} (S-Core)
* <ul>
@@ -41,57 +45,170 @@ import java.util.StringTokenizer;
* @author gyeongseok.seo@samsung.com, S-Core Inc.
* <ul>
* <li> added split method.
+ * <li> added removeStart method.
* </ul>
*/
-public class StringUtil {
- public static String trimToNull(String s) {
- return trimToNull(s, null);
- }
+public class StringUtil
+{
+ /**
+ * Empty String
+ */
+ public static final String EMPTY_STRING = "";
- public static String trimToNull(String s, String def) {
- if (s == null) {
- return def;
- }
+ /**
+ * Textual string for <code>null</code>
+ */
+ public static final String NULL_STRING = "<<null>>";
- String t = s.trim();
- if (t.length() == 0) {
- return def;
- }
+ /**
+ * Textual string for empty byte array
+ */
+ public static final String EMPTY_BYTES_STRING = "<<EMPTY BYTES>>";
+
+ /**
+ * Line separator string
+ */
+ public static final String LINE_SEPARATOR = System.getProperty( "line.separator" );
+
+ /**
+ * TAB string
+ */
+ public static final String TAB = "\t";
+
+ /* Dump Format */
+ protected static char CONTROL_CHARS_SHOWER = '.';
+
+ /**
+ * Hexa decimal conversion map
+ */
+ protected static final char[] HEXA_CHARS = new char[] {
+ '0', '1', '2', '3', '4', '5', '6', '7',
+ '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
+ };
+ /**
+ * The number how many bytes is in int
+ */
+ protected static final int N_INT_BY_BYTE = 4;
+
+ /**
+ * The number how many characters is print out in a line
+ */
+ protected static final int WIDTH_PER_LINE = 16;
+
+ /**
+ * Character to express for control( Human can't control character and control character break log format )
+ */
+ protected static char TWO_BYTES_CHARS_SHOWER = '?';
+
+ /**
+ * Return meaningful value of <code>str</code>
+ *
+ * Return <code>null</code> if <code>str</code> has no implication
+ *
+ * @param str string to check
+ *
+ * @return meaningful string
+ *
+ * @see #trimToNull(String, String)
+ */
+ public static
+ String
+ trimToNull(
+ final String str
+ )
+ {
+ return trimToNull(str, null);
+ }
- return t;
+ /**
+ * Return meaningful value of <code>str</code>
+ *
+ * Return <code>def</code> if <code>str</code> has no implication
+ *
+ * @param str string to check
+ *
+ * @return meaningful string
+ *
+ * @see #getMeaningful(String)
+ * @see #isEmpty(CharSequence)
+ */
+ public static String trimToNull(String str, String def) {
+ final String meaningful = getMeaningful( str );
+ return isEmpty( meaningful )?def:meaningful;
}
- public static InputStream stringToInputStream(String src) {
- if (src == null) {
+ /**
+ * Convert <code>src</code> to {@link InputStream}
+ *
+ * @param src string to convert
+ *
+ * @return {@link InputStream} containing <code>src</code>
+ */
+ public static
+ InputStream
+ toInputStream(
+ final String src
+ )
+ {
+ if ( null == src )
+ {
return null;
}
- return new ByteArrayInputStream(src.getBytes());
+ return new ByteArrayInputStream( src.getBytes() );
}
- public static String[] split(String s, String delim) {
- List<String> list = new ArrayList<String>();
- StringTokenizer st = new StringTokenizer(s, delim);
- while (st.hasMoreTokens()) {
- list.add(st.nextToken());
+ /**
+ * Split <code>str</code> with <code>delimiters</code>
+ *
+ * @param str string to split
+ * @param delimiters delimiters to split with
+ *
+ * @return strings to be split
+ */
+ public static
+ String[] split(
+ final String str,
+ final String delimiters
+ )
+ {
+ final List<String> list = new ArrayList<String>();
+ final StringTokenizer tokenizer = new StringTokenizer( str, delimiters );
+ while ( tokenizer.hasMoreTokens() )
+ {
+ list.add( tokenizer.nextToken() );
}
return (String[]) list.toArray(new String[0]);
}
- public static String getOnlyNumerics(String str) {
- if (str == null) {
+ /**
+ * @param str
+ * @return
+ */
+ public static String getOnlyNumerics(
+ final String str
+ )
+ {
+ if ( null == str )
+ {
return null;
}
- char c;
- StringBuilder sb = new StringBuilder();
+ final StringBuilder sb = new StringBuilder();
- for (int i = 0; i < str.length() ; i++) {
- c = str.charAt(i);
- if (Character.isDigit(c)) {
- sb.append(c);
+ ArrayUtil.iterate(
+ ArrayUtil.convertToWrapper( str.toCharArray() ),
+ new IteratingRunner<Character>()
+ {
+ public void run( Character arg )
+ {
+ if (Character.isDigit( arg )) {
+ sb.append( arg );
+ }
+ }
}
- }
+ );
+
return sb.toString();
}
@@ -104,12 +221,12 @@ public class StringUtil {
return sb.toString();
}
public static String asString(InputStream is) throws IOException{
- StringBuffer out = new StringBuffer();
- byte[] b = new byte[4096];
-
- for (int n; (n = is.read(b)) != -1;)
- out.append(new String(b,0,n));
- return out.toString();
+ StringBuffer out = new StringBuffer();
+ byte[] b = new byte[4096];
+
+ for (int n; (n = is.read(b)) != -1;)
+ out.append(new String(b,0,n));
+ return out.toString();
}
public static String removeEnd(String str, String remove) {
@@ -122,7 +239,886 @@ public class StringUtil {
return str;
}
- public static boolean isEmpty(CharSequence cs) {
- return cs == null || cs.length() == 0;
+ /**
+ * remove string in target string
+ * if target is empty or remove word is empty then just return target string
+ *
+ * @param str - target string
+ * @param remove - remove string
+ * @return removed target string
+ */
+ public static String removeStart(String str, String remove) {
+ if (isEmpty(str) || isEmpty(remove) ) {
+ return str;
+ }
+ if (str.startsWith(remove)){
+ return str.substring(remove.length());
+ }
+ return str;
+ }
+
+ /* Logging */
+ /**
+ * </p>
+ * Append hexa value for <code>ch</code> to <code>buffer</code>
+ *
+ * Hexa value must be two digit. Pad 0 if hexa value has 1 digit.
+ * </p>
+ *
+ * @param buffer {@link StringBuilder} to write
+ * @param ch decimal integer
+ */
+ public static
+ void
+ appendHexa(
+ final StringBuilder buffer,
+ final int ch
+ )
+ {
+ if ( ch < 16 )
+ {
+ // if 1 digit containing hexadecimal
+ buffer.append( '0' );
+ buffer.append( HEXA_CHARS[( 0x0f & ( ch ) )] );
+ }
+ else
+ {
+ // if 2 digit containing hexadecimal
+ buffer.append( HEXA_CHARS[( 0x0f & ( ch >> 4 ) )] );
+ buffer.append( HEXA_CHARS[( 0x0f & ( ch ) )] );
+ }
+ }
+
+ /**
+ * Add end seperation at logging line's end
+ *
+ * @param hexPart hex decimal part
+ * @param textPart text part
+ * @param ret all part
+ */
+ protected static
+ void
+ lineEnd(
+ final StringBuilder hexPart,
+ final StringBuilder textPart,
+ final StringBuilder ret
+ )
+ {
+ // append separator of area
+ hexPart.append( " |" );
+
+ // append separator of termination
+ textPart.append( "|\n" );
+
+ // concatencate two area
+ ret.append( hexPart );
+ ret.append( textPart );
+
+ // clean each area
+ hexPart.delete( 0, hexPart.capacity() );
+ textPart.delete( 0, textPart.capacity() );
+ }
+
+ /**
+ * <p>
+ * Convert <code>data</code> in hexadecimal format for logging or readibility
+ *
+ * Output layout<br>
+ * <table>
+ * <tr><td>Address( or offset )</td><td>byte character</td><td>hexadecimal</td></tr>
+ * </table>
+ *
+ * Replace control character to '.'<br>
+ * </p>
+ *
+ * <code>
+ * Logger logger = ...
+ * byte[] dump = ...
+ * logger.debug( StringUtil.text2hexa( dump ) );
+ * </code>
+ *
+ * @param data byte array to convert
+ *
+ * @return converted textual string
+ *
+ * @see #text2hexa(byte[], int, int)
+ */
+ public static
+ String
+ text2hexa(
+ final byte[] data
+ )
+ {
+ if ( null == data )
+ {
+ return NULL_STRING;
+ }
+ return text2hexa( data, 0, data.length );
+ }
+
+ /**
+ * <p>
+ * Convert data from <code>offset</code> to <code>offset</code> + <code>length</code> in hexadecimal format.
+ *
+ * Output layout<br>
+ * <table>
+ * <tr><td>Address( or offset )</td><td>byte character</td><td>hexadecimal</td></tr>
+ * </table>
+ *
+ * Replace control character to '.'<br>
+ * </p>
+ *
+ * @param data byte array to convert
+ * @param offset start position to convert
+ * @param length length to convert
+ *
+ * @return converted textual string
+ */
+ public static
+ String
+ text2hexa(
+ final byte[] data,
+ final int offset,
+ final int length
+ )
+ {
+
+ if ( null == data )
+ {
+ return NULL_STRING;
+ }
+ if ( data.length <= 0 )
+ {
+ return EMPTY_BYTES_STRING;
+ }
+
+ final ByteArrayInputStream reader = new ByteArrayInputStream( data, offset, length );
+ final StringBuilder ret = new StringBuilder();
+ final StringBuilder hexPart = new StringBuilder();
+ final StringBuilder textPart = new StringBuilder();
+
+ int address = 0;
+ int ch = -1;
+ int printByte = 0;
+ int cnt = 0;
+
+ // fill white space( ' ' ) in address title
+ hexPart.append( " " );
+
+ // make horizontal ruler
+ for ( int i = 0, n = WIDTH_PER_LINE / 4 ; i < n ; i++ )
+ {
+ hexPart.append( "+-------" );
+ textPart.append( "+---" );
+ }
+
+ lineEnd( hexPart, textPart, ret );
+
+ while ( 0 <= ( ch = reader.read() ) )
+ {
+ if ( 0 == cnt )
+ {
+ // calculate and print out start address
+ for ( int i = N_INT_BY_BYTE - 1 ; i >= 0 ; i-- )
+ {
+ printByte = 0xFF & ( address >> ( 8 * i ) );
+ appendHexa( hexPart, printByte );
+ }
+ hexPart.append( " " );
+ address += WIDTH_PER_LINE;
+ }
+
+ appendHexa( hexPart, ch );
+ if ( ( ch & 0x80 ) != 0 || ch < 32 )
+ { // if ch is control character
+ // print out replaced character
+ textPart.append( CONTROL_CHARS_SHOWER );
+ }
+ else
+ {
+ textPart.append( (char) ch );
+ }
+ cnt++;
+
+ if ( WIDTH_PER_LINE == cnt )
+ {
+ lineEnd( hexPart, textPart, ret );
+ cnt = 0;
+ }
+ } // END of while ( 0 <= (ch = reader.read() ) )
+
+ // fill white space( ' ' ) in remaining area
+ if ( 0 != cnt )
+ {
+ for ( ; cnt < WIDTH_PER_LINE ; ++cnt )
+ {
+ hexPart.append( " " );
+ textPart.append( ' ' );
+ }
+ lineEnd( hexPart, textPart, ret );
+ }
+
+ return ret.toString();
+ }
+
+
+ /* Check & Verification */
+ /**
+ * Check that <code>str</code> is <code>null</code> or empty string textually
+ *
+ * @param str string to check
+ *
+ * @return <code>true</code> if <code>str</code> is null or empty string or string containing only white space
+ *
+ * @see StringUtil#hasText( CharSequence )
+ */
+ public static
+ boolean
+ isEmpty(
+ final CharSequence str
+ )
+ {
+ if ( null == str )
+ {
+ return true;
+ }
+
+ for ( int i=0, n=str.length() ; i<n ; ++i )
+ {
+ if ( Character.isWhitespace( str.charAt( i ) ) )
+ {
+ continue;
+ }
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Get length of string
+ *
+ * Return <code>0</code> if <code>str</code> is <code>null</code>
+ *
+ * @param str string whose length is checked
+ *
+ * @return length of <code>str</code>
+ */
+ public static
+ int
+ size(
+ final CharSequence str
+ )
+ {
+ if ( null == str )
+ {
+ return 0;
+ }
+ return str.length();
+ }
+
+ /**
+ * <p>
+ * Check that <code>str</code> contain any character
+ * </p>
+ * @param str string to check
+ *
+ * @return <code>true</code> if <code>str</code> is not <code>null</code> nor empty string
+ *
+ * @see #size(CharSequence)
+ */
+ public static
+ boolean
+ hasLength(
+ final CharSequence str
+ )
+ {
+ return 0 < size( str );
+ }
+
+ /**
+ * Check that <code>str</code> has textual character
+ *
+ * @param str string to check
+ *
+ * @return <code>true</code> if <code>str</code> has textual character
+ *
+ * @see isEmpty( CharSequence )
+ */
+ public static
+ boolean
+ hasText(
+ final CharSequence str
+ )
+ {
+ return !isEmpty( str );
+ }
+
+ /* Conversion */
+ /**
+ * Check <code>strs</code> and return non-null string
+ *
+ * Return empty string if all of element in <code>strs</code>
+ *
+ * @param strs strings to check
+ *
+ * @return non-null in <code>strs</code>
+ *
+ * see #ObjectUtil{@link #nvl(String...)}
+ */
+ public static
+ String
+ nvl(
+ final String... strs
+ )
+ {
+ String val = ObjectUtil.nvl( strs );
+ if ( null == val )
+ {
+ return "";
+ }
+ return val;
+ }
+
+ /**
+ * Trim leading whitespaqce
+ *
+ * @param str string to trim
+ *
+ * @return trimmed string
+ */
+ public static
+ String
+ trimLeading(
+ final String str
+ )
+ {
+ if( !hasLength( str ) )
+ {
+ return str;
+ }
+
+ final char[] chs = str.toCharArray();
+ for ( int i=0, n=chs.length ; i<n ; ++i )
+ {
+ if ( !Character.isWhitespace( chs[i] ) )
+ {
+ return new String( chs, i, str.length() - i );
+ }
+ }
+ return EMPTY_STRING;
+ }
+
+ /**
+ * Trim trailing white space
+ *
+ * @param str string to trim
+ *
+ * @return trimmed string
+ */
+ public static
+ String
+ trimTrailing(
+ final String str
+ )
+ {
+ if( !hasLength( str ) )
+ {
+ return str;
+ }
+
+ final char[] chs = str.toCharArray();
+ for ( int i=chs.length-1, j=chs.length ; 0<j ; --i, --j )
+ {
+ if ( !Character.isWhitespace( chs[i] ) )
+ {
+ return new String( chs, 0, j );
+ }
+ }
+ return EMPTY_STRING;
+ }
+ /**
+ * Remove white spaces at leading and trailing part of <code>str</code>
+ *
+ * Return empty string if <code>str</code> is <code>null</code>
+ *
+ * @param str string to convert
+ *
+ * @return converted string
+ *
+ * @see StringUtil#trimLeading(String)
+ * @see StringUtil#trimTrailing(String)
+ */
+ public static
+ String
+ trim(
+ final String str
+ ) {
+ return trimTrailing( trimLeading( str ) );
+ }
+
+ /**
+ * Convert <code>str</code> to meaningful for search
+ *
+ * @param str string to convert
+ *
+ * @return converted string
+ */
+ public static
+ String
+ getMeaningful(
+ final String str
+ ) {
+ if ( null == str )
+ {
+ return EMPTY_STRING;
+ }
+ return trim( str ).toLowerCase();
+ }
+
+ /**
+ * Mask <code>str</code> with <code>maskingStr</code>
+ *
+ * Replace <code>str</code> to <code>maskingStr</code> with <code>str</code>'s length
+ *
+ * @param str string to mask
+ * @param maskingStr string to mask with
+ *
+ * @return masked string
+ */
+ public static
+ String
+ mask(
+ final String str,
+ final String maskingStr
+ ) {
+ if ( null == str )
+ {
+ return "null";
+ }
+
+ final StringBuilder buffer = new StringBuilder();
+ for ( int i=0, n=str.length() ; i<n ; ++i )
+ {
+ buffer.append( maskingStr );
+ }
+ return buffer.toString();
+ }
+
+ /* Analysis & Extract */
+ /**
+ * Extract <code>targetIndex</code> string from strings
+ *
+ * where <code>str</code> is splitted by <code>delimeter</code>
+ *
+ * @param str string with <code>delimeter</code>
+ * @param delimeter what split <code>str</code> with
+ * @param escaper escape character for <code>delimter</code>
+ * @param targetIndex index from fragments
+ *
+ * @return extracted string
+ */
+ public static
+ String
+ getParamater(
+ final String str,
+ final char delimeter,
+ final int escaper,
+ final int targetIndex
+ )
+ throws IOException
+ {
+ try
+ {
+ if ( null == str )
+ {
+ return null;
+ }
+ final StringReader reader = new StringReader( str );
+ StringWriter writer = null;
+ int ch = 0;
+ final int ST_NORMAL = 0;
+ final int ST_ESCAPE = 1;
+ int status = ST_NORMAL;
+ int index = 0;
+ if ( 0 == targetIndex )
+ {
+ writer = new StringWriter();
+ }
+ while ( 0 <= ( ch = reader.read() ) ) {
+ if ( ST_ESCAPE == status ) {
+ status = ST_NORMAL;
+ } else {
+ if ( escaper == ch ) {
+ status = ST_ESCAPE;
+ continue;
+ } else if ( delimeter == ch ) {
+ if ( index == targetIndex )
+ {
+ return writer.toString();
+ }
+ ++index;
+ if ( index == targetIndex )
+ {
+ writer = new StringWriter();
+ }
+ continue;
+ }
+ }
+ if ( null != writer )
+ {
+ writer.write( (int) ch );
+ }
+ }
+ if ( index == targetIndex )
+ {
+ return writer.toString();
+ }
+ return null;
+ }
+ catch ( final IOException e )
+ {
+ // Never throw
+ throw new IllegalStateException( e );
+ }
+ }
+
+ /**
+ * Return substring starting <code>indexFromLast</code> from last
+ *
+ * @param str original string
+ * @param indexFromLast starting index from last
+ *
+ * @return substring
+ */
+ public static
+ String
+ lastSubstring(
+ final String str,
+ final int indexFromLast
+ )
+ {
+ if ( null == str )
+ {
+ return null;
+ }
+
+ final int length = str.length();
+
+ if ( length < indexFromLast )
+ {
+ return str;
+ }
+
+ return str.substring( length - indexFromLast );
+ }
+
+ /**
+ * Extract last fragment in strings split <code>str</code> with <code>separator</code>
+ *
+ * @param str origin string
+ * @param separator string for separation
+ *
+ * @return last fragment string
+ */
+ public static
+ String
+ getLastSegment(
+ final String str,
+ final String separator
+ )
+ {
+ if ( null == str )
+ {
+ return EMPTY_STRING;
+ }
+
+ final int index = str.lastIndexOf( separator );
+ if ( index < 0 )
+ {
+ return str;
+ }
+
+ return str.substring( index + separator.length() );
+ }
+
+ /**
+ * Extract last fragment in string and return remaining string with <code>separator</code>
+ *
+ * @param str origin string
+ * @param separator string for separation
+ *
+ * @return remaining string
+ */
+ public static
+ String
+ removeLastSegment(
+ final String str,
+ final String separator
+ )
+ {
+ if ( null == str )
+ {
+ return EMPTY_STRING;
+ }
+
+ final int index = str.lastIndexOf( separator );
+
+ if ( index < 0 )
+ {
+ return EMPTY_STRING;
+ }
+
+ return str.substring( 0, index );
+
+ }
+
+ /**
+ * Make <code>n</code> repeated <code>symbol</code> string
+ *
+ * @param symbol composing string
+ * @param n repeat count
+ *
+ * @return made string
+ */
+ public static
+ String
+ multiply(
+ final String symbol,
+ final int n
+ )
+ {
+ if ( null == symbol ) {
+ return EMPTY_STRING;
+ }
+
+ final StringBuilder buffer = new StringBuilder();
+ for ( int i=0 ; i<n ; ++i )
+ {
+ buffer.append( symbol );
+ }
+ return buffer.toString();
+ }
+
+ /**
+ * Check that <code>str</code> contain white spaces
+ *
+ * @param str string to check
+ * @return <code>true</code> if <code>str</code> contain white spaces
+ */
+ public static
+ boolean
+ containsWhitespace(
+ final CharSequence str
+ )
+ {
+ final int nChar = size( str );
+
+ for ( int i= 0; i< nChar; ++i )
+ {
+ if ( Character.isWhitespace( str.charAt( i ) ) )
+ {
+ return true;
+ }
+ }
+ return false;
}
+
+
+ /**
+ * Trim leading <code>leadingCharacter</code> from <code>str</code>
+ *
+ * @param str string to trim
+ * @param leadingCharacter character to trim with
+ *
+ * @return trimmed string
+ */
+ public static
+ String
+ trimLeadingCharacter(
+ final String str,
+ final char leadingCharacter
+ )
+ {
+ if( !hasLength( str ) )
+ {
+ return str;
+ }
+
+ final char[] chs = str.toCharArray();
+ for ( int i=0, n=chs.length ; i<n ; ++i )
+ {
+ if ( leadingCharacter != chs[i] )
+ {
+ return new String( chs, i, str.length() - i );
+ }
+ }
+ return EMPTY_STRING;
+ }
+
+ /**
+ * Trim trailing <code>trailingCharacter</code> from <code>str</code>
+ *
+ * @param str string to trim
+ * @param trailingCharacter character to trim with
+ *
+ * @return trimmed string
+ */
+ public static
+ String
+ trimTrailingCharacter(
+ final String str,
+ final char trailingCharacter
+ )
+ {
+ if( !hasLength( str ) )
+ {
+ return str;
+ }
+
+ final char[] chs = str.toCharArray();
+ for ( int i=chs.length-1, j=chs.length ; 0<j ; --i, --j )
+ {
+ if ( trailingCharacter != chs[i] )
+ {
+ return new String( chs, 0, j );
+ }
+ }
+ return EMPTY_STRING;
+ }
+
+ /**
+ * Trim <code>str</code> with <code>character</code>
+ *
+ * @param str string to trim
+ * @param character character to trim with
+ *
+ * @return trimmed string
+ */
+ public static
+ String
+ trimCharacter(
+ final String str,
+ final char character
+ )
+ {
+ return trimTrailingCharacter( trimLeadingCharacter( str, character ), character );
+ }
+
+ /**
+ * Extract word at <coode>index</code> column in <code>doc</code>
+ *
+ * @param doc full string
+ * @param index column index
+ *
+ * @return word at <code>index</code> column
+ */
+ public static
+ String
+ getWord(
+ final String doc,
+ final int index
+ )
+ {
+ final StringBuilder buffer = new StringBuilder();
+
+ int position = index;
+
+ if ( doc.length() < index )
+ {
+ return "";
+ }
+
+ for ( int i = position - 1 ; 0 <= i ; --i )
+ {
+
+ int ch = doc.charAt( i );
+
+ if ( Character.isWhitespace( ch ) )
+ {
+ break;
+ }
+ buffer.append( (char) ch );
+ }
+ buffer.reverse();
+
+ for ( int i = position , n = doc.length() ; i < n ; ++i )
+ {
+ int ch = doc.charAt( i );
+ if ( Character.isWhitespace( ch ) )
+ {
+ break;
+ }
+ buffer.append( (char) ch );
+ }
+
+ return buffer.toString();
+ }
+
+ /**
+ * Extract word in front of <coode>index</code> column in <code>doc</code>
+ *
+ * @param doc full string
+ * @param index column index
+ *
+ * @return word in front of <code>index</code> column
+ */
+ public static
+ String
+ getPreviousWord(
+ final String doc,
+ final int index
+ )
+ {
+ final StringBuilder buffer = new StringBuilder();
+
+ if ( index < 0 || doc.length() < index )
+ {
+ Logger.debug( "Index[{0}] is out of bound :[0:{1}]", index, doc.length() );
+ return "";
+ }
+
+ int ch = 0;
+ boolean bNeedWord = false;
+ if ( index < doc.length() )
+ {
+ ch = doc.charAt( index );
+ bNeedWord = Character.isWhitespace( ch );
+ }
+ Logger.debug( "Character at index :'{0}'", (char ) ch );
+ for ( int i = index - 1 ; 0 <= i ; --i )
+ {
+ ch = doc.charAt( i );
+
+ if ( Character.isWhitespace( ch ) )
+ {
+ if ( bNeedWord )
+ {
+ continue;
+ }
+ Logger.debug( "Meet space at column {0}", i );
+ break;
+ }
+ bNeedWord = false;
+ buffer.append( (char) ch );
+ }
+
+ return buffer.reverse().toString();
+ }
+
+ /**
+ * Enum to String array
+ *
+ * @param values enum values
+ *
+ * @return string array
+ */
+ public static <T extends Enum<T>> String[] enumNameToStringArray(T[] values) {
+ int i = 0;
+ String[] result = new String[values.length];
+ for (T value: values) {
+ result[i++] = value.name();
+ }
+ return result;
+ }
+
}
diff --git a/org.tizen.common/src/org/tizen/common/util/ThreadUtil.java b/org.tizen.common/src/org/tizen/common/util/ThreadUtil.java
new file mode 100644
index 000000000..d51eed74a
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/util/ThreadUtil.java
@@ -0,0 +1,60 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* BonYong Lee <bonyong.lee@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+package org.tizen.common.util;
+
+/**
+ * ThreadUtil.
+ *
+ * Helper related to <code>Thread</code>
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ */
+public class
+ThreadUtil
+{
+ protected ThreadUtil() {}
+
+ /**
+ * try to invoke {@link Thread#sleep(long)} in safe
+ *
+ * handle <code>milliseconds</code> to zero( 0 ) if it is negative
+ *
+ * @param milliseconds time to sleep in milliseconds
+ *
+ * @see Thread#sleep(long)
+ */
+ public static void trySleep( final long milliseconds )
+ {
+ if ( milliseconds <=0 )
+ {
+ return ;
+ }
+ try {
+ Thread.sleep( milliseconds );
+ } catch ( InterruptedException e ) {
+ }
+ }
+
+}
diff --git a/org.tizen.common/src/org/tizen/common/util/ValidationUtil.java b/org.tizen.common/src/org/tizen/common/util/ValidationUtil.java
new file mode 100644
index 000000000..3f2de9370
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/util/ValidationUtil.java
@@ -0,0 +1,94 @@
+/*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * Changhyun Lee <changhyun1.lee@samsung.com>
+ * Hyeongseok Heo <hyeongseok.heo@samsung.com>
+ * BonYong Lee <bonyong.lee@samsung.com>
+ * Kangho Kim <kh5325.kim@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+
+package org.tizen.common.util;
+
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/**
+ * ValidationUtil.
+ *
+ * Verification Using a regular expression.
+ *
+ * @author Changhyun Lee {@literal <changhyun1.lee@samsung.com>} (S-Core)
+ */
+public class ValidationUtil {
+
+ /**
+ * Check for Email address. RFC 2822 (simplified)Matches a normal email address. Does not check the top-level domain.
+ *
+ * @param value email string
+ *
+ * @return if value is valied email
+ */
+ public static boolean checkForEmail(String value) {
+ String regex = "[A-Za-z0-9!#$%&\'*+/=?^_`{|}~-]+(?:\\.[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?\\.)+[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])??"; //$NON-NLS-1$
+ Pattern pattern = Pattern.compile(regex);
+ Matcher matcher = pattern.matcher(value);
+
+ return matcher.matches();
+ }
+
+ /**
+ * Check for URL string.
+ *
+ * @param value url string
+ *
+ * @return if value is valied url
+ */
+ public static boolean checkForURL(String value) {
+ String regex = "\\b(https?)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]"; //$NON-NLS-1$
+ Pattern pattern = Pattern.compile(regex);
+ Matcher matcher = pattern.matcher(value);
+
+ return matcher.matches();
+ }
+
+ /**
+ * Check for File extension.
+ *
+ * @param value file name
+ * @param extensions valied file extensions
+ *
+ * @return if value is valied file
+ */
+ public static boolean checkForFileExtension(String value, String[] extensions) {
+ if (StringUtil.isEmpty(value) || extensions == null) {
+ return false;
+ }
+
+ for (String ext : extensions) {
+ if (value.endsWith(ext)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+}
diff --git a/org.tizen.common/src/org/tizen/common/util/ViewUtil.java b/org.tizen.common/src/org/tizen/common/util/ViewUtil.java
index 05a3ae525..1bb30fb35 100644
--- a/org.tizen.common/src/org/tizen/common/util/ViewUtil.java
+++ b/org.tizen.common/src/org/tizen/common/util/ViewUtil.java
@@ -25,7 +25,6 @@
package org.tizen.common.util;
import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
@@ -41,9 +40,9 @@ public class ViewUtil {
ViewRunnable runnable = new ViewRunnable(id);
if (sync) {
- Display.getDefault().syncExec(runnable);
+ SWTUtil.syncExec( runnable );
} else {
- Display.getDefault().asyncExec(runnable);
+ SWTUtil.asyncExec( runnable );
}
}
@@ -94,15 +93,17 @@ public class ViewUtil {
}
public static IWorkbenchWindow getWorkbenchWindow() {
- IWorkbench workbench = PlatformUI.getWorkbench();
- IWorkbenchWindow window = workbench.getActiveWorkbenchWindow();
- if (window == null) {
- if (workbench.getWorkbenchWindowCount() == 1) {
- window = workbench.getWorkbenchWindows()[0];
- }
+ final IWorkbench workbench = PlatformUI.getWorkbench();
+ final IWorkbenchWindow window = workbench.getActiveWorkbenchWindow();
+ if ( window != null )
+ {
+ return window;
}
-
- return window;
+ if ( workbench.getWorkbenchWindowCount() == 0 )
+ {
+ return null;
+ }
+ return workbench.getWorkbenchWindows()[0];
}
-} \ No newline at end of file
+}
diff --git a/org.tizen.common/src/org/tizen/common/cache/ColorCache.java b/org.tizen.common/src/org/tizen/common/util/cache/ColorCache.java
index fbd1a3659..3704dc5ec 100644
--- a/org.tizen.common/src/org/tizen/common/cache/ColorCache.java
+++ b/org.tizen.common/src/org/tizen/common/util/cache/ColorCache.java
@@ -23,15 +23,15 @@
* - S-Core Co., Ltd
*
*/
-package org.tizen.common.cache;
+package org.tizen.common.util.cache;
import java.util.HashMap;
-import java.util.Iterator;
import java.util.Map;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.RGB;
-import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.Widget;
+import org.tizen.common.util.SWTUtil;
/**
* Class for caching colors
@@ -41,33 +41,20 @@ import org.eclipse.swt.widgets.Display;
*/
public final class ColorCache {
- public static final RGB BLACK = new RGB(0, 0, 0);
- public static final RGB WHITE = new RGB(255, 255, 255);
+ public static final RGB BLACK = new RGB(0, 0, 0);
+ public static final RGB WHITE = new RGB(255, 255, 255);
- private static Map<RGB, Color> _colorTable;
- private static ColorCache _instance;
-
- static {
- _colorTable = new HashMap<RGB, Color>();
- new ColorCache();
- }
+ private static Map<RGB, Color> _colorTable = new HashMap<RGB, Color>();
private ColorCache() {
- _instance = this;
- }
-
- public static ColorCache getInstance() {
- return _instance;
}
/**
* Disposes of all colors. DO ONLY CALL THIS WHEN YOU ARE SHUTTING DOWN YOUR
* APPLICATION!
*/
- public static void disposeColors() {
- Iterator<Color> e = _colorTable.values().iterator();
- while (e.hasNext())
- e.next().dispose();
+ synchronized public static void disposeColors() {
+ SWTUtil.tryDispose( _colorTable.values().toArray( new Widget[0]) );
_colorTable.clear();
}
@@ -80,27 +67,27 @@ public final class ColorCache {
return getColorFromRGB(new RGB(0, 0, 0));
}
- public static Color getColorFromRGB(RGB rgb) {
+ synchronized public static Color getColorFromRGB(RGB rgb) {
Color color = _colorTable.get(rgb);
if (color == null) {
- color = new Color(Display.getCurrent(), rgb);
+ color = new Color( SWTUtil.getDisplay(), rgb);
_colorTable.put(rgb, color);
}
return color;
}
- public static Color getColor(int r, int g, int b) {
+ synchronized public static Color getColor(int r, int g, int b) {
RGB rgb = new RGB(r, g, b);
Color color = _colorTable.get(rgb);
if (color == null) {
- color = new Color(Display.getCurrent(), rgb);
+ color = new Color( SWTUtil.getDisplay(), rgb);
_colorTable.put(rgb, color);
}
return color;
}
-
-} \ No newline at end of file
+
+}
diff --git a/org.tizen.common/src/org/tizen/common/cache/FontCache.java b/org.tizen.common/src/org/tizen/common/util/cache/FontCache.java
index ec5b81a51..5a83a7700 100644..100755
--- a/org.tizen.common/src/org/tizen/common/cache/FontCache.java
+++ b/org.tizen.common/src/org/tizen/common/util/cache/FontCache.java
@@ -23,14 +23,17 @@
* - S-Core Co., Ltd
*
*/
-package org.tizen.common.cache;
+package org.tizen.common.util.cache;
+
+import static org.tizen.common.util.SWTUtil.tryDispose;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
-import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.Widget;
+import org.tizen.common.util.SWTUtil;
/**
* Caching class for fonts. Also deals with re-creating fonts should they have been disposed when the
@@ -47,12 +50,8 @@ public class FontCache {
* Disposes all fonts and clears out the cache. Never call this unless you are shutting down your
* code/client/etc.
*/
- public static void disposeAll() {
- for (OneFont of : _existing) {
- if (of.getFont() != null && !of.getFont().isDisposed()) {
- of.getFont().dispose();
- }
- }
+ synchronized public static void disposeAll() {
+ SWTUtil.tryDispose( _existing.toArray( new Widget[0] ) );
_existing.clear();
}
@@ -63,7 +62,7 @@ public class FontCache {
* @param fd FontData
* @return Font or null on error
*/
- public static Font getFont(FontData fd) {
+ synchronized public static Font getFont(FontData fd) {
try {
boolean disposed = false;
OneFont toRemove = null;
@@ -92,7 +91,7 @@ public class FontCache {
return null;
}
- public static int getCount() {
+ synchronized public static int getCount() {
return _existing.size();
}
@@ -104,7 +103,10 @@ public class FontCache {
*/
public static Font getFont(Font font) {
try {
- if (font == null || font.isDisposed()) return null;
+ if (font == null || font.isDisposed())
+ {
+ return null;
+ }
FontData fd = font.getFontData()[0];
return getFont(fd);
@@ -124,7 +126,7 @@ public class FontCache {
* @param style Style of font
* @return Font or null on error
*/
- public static Font getFont(String fontName, int height, int style) {
+ synchronized public static Font getFont(String fontName, int height, int style) {
try {
boolean disposed = false;
OneFont toRemove = null;
@@ -165,14 +167,14 @@ class OneFont {
_name = name;
_height = height;
_style = style;
- _font = new Font(Display.getDefault(), name, height, style);
+ _font = new Font( SWTUtil.getDisplay(), name, height, style);
}
public OneFont(FontData fd) {
_name = fd.getName();
_height = fd.getHeight();
_style = fd.getStyle();
- _font = new Font(Display.getDefault(), fd);
+ _font = new Font( SWTUtil.getDisplay(), fd);
}
public String getName() {
diff --git a/org.tizen.common/src/org/tizen/common/util/cache/ImageCache.java b/org.tizen.common/src/org/tizen/common/util/cache/ImageCache.java
new file mode 100644
index 000000000..778991931
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/util/cache/ImageCache.java
@@ -0,0 +1,108 @@
+/*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * Changhyun Lee <changhyun1.lee@samsung.com>
+ * Kangho Kim <kh5325.kim@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common.util.cache;
+
+import java.io.InputStream;
+import java.util.HashMap;
+
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.widgets.Widget;
+import org.tizen.common.util.IOUtil;
+import org.tizen.common.util.SWTUtil;
+
+/**
+ * Class for caching images
+ *
+ * @author Emil
+ */
+public class ImageCache {
+
+ // what path to get to the "icons" directory without actually including it
+ private static final String ICON_ROOT_PATH = "icons/";
+
+ private final static HashMap<String, Image> _ImageMap = new HashMap<String, Image>();
+
+ /**
+ * Returns an image that is also cached if it has to be created and does not already exist in the cache.
+ *
+ * @param fileName Filename of image to fetch
+ * @return Image null if it could not be found
+ */
+ public static Image getImage(String fileName) {
+ fileName = ICON_ROOT_PATH + fileName;
+ Image image = _ImageMap.get(fileName);
+ if (image == null) {
+ image = createImage(fileName);
+ _ImageMap.put(fileName, image);
+ }
+ return image;
+ }
+
+ /**
+ * creates the image, and tries really hard to do so
+ *
+ * FIXME : substring is not exact expression to remove leading '/'
+ *
+ * @param fileName image file name
+ *
+ * @return loaded <code>Image</code>
+ */
+ synchronized private static Image createImage(String fileName) {
+ ClassLoader classLoader = ImageCache.class.getClassLoader();
+ InputStream is = classLoader.getResourceAsStream(fileName);
+ try
+ {
+ if (is == null) {
+ // the old way didn't have leading slash, so if we can't find the image stream,
+ // let's see if the old way works.
+ is = classLoader.getResourceAsStream(fileName.substring(1));
+ }
+ if (is == null) {
+ is = classLoader.getResourceAsStream(fileName);
+ if (is == null) {
+ is = classLoader.getResourceAsStream(fileName.substring(1));
+ if (is == null) { return null; }
+ }
+ }
+
+ return new Image( SWTUtil.getDisplay(), is);
+ }
+ finally
+ {
+ IOUtil.tryClose( is );
+ }
+ }
+
+ /**
+ * Disposes ALL images that have been cached.
+ */
+ synchronized public static void dispose() {
+
+ SWTUtil.tryDispose( _ImageMap.values().toArray( new Widget[0]) );
+ _ImageMap.clear();
+
+ }
+}
diff --git a/org.tizen.common/src/org/tizen/common/manager/ColorCache.java b/org.tizen.common/src/org/tizen/common/util/cache/NamedColorCache.java
index 3920db1d1..08203df15 100644
--- a/org.tizen.common/src/org/tizen/common/manager/ColorCache.java
+++ b/org.tizen.common/src/org/tizen/common/util/cache/NamedColorCache.java
@@ -22,19 +22,19 @@
* - S-Core Co., Ltd
*
*/
-package org.tizen.common.manager;
+package org.tizen.common.util.cache;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.RGB;
-import org.eclipse.swt.widgets.Display;
+import org.tizen.common.util.Assert;
+import org.tizen.common.util.SWTUtil;
-public class ColorCache {
+public class NamedColorCache {
private String[] keys;
private Color[] colors;
- public ColorCache(String[] keys){
- if(keys==null||keys.length==0)
- throw new IllegalArgumentException(Messages.ColorCache_0);
+ public NamedColorCache(String[] keys){
+ Assert.notEmpty( keys, "Argument must not be null" );
this.keys = keys;
this.colors = new Color[keys.length];
@@ -71,7 +71,7 @@ public class ColorCache {
color=null;
}
- colors[index] = new Color(Display.getCurrent(),rgb);
+ colors[index] = new Color( SWTUtil.getDisplay(), rgb );
}
public void dispose(){
diff --git a/org.tizen.common/src/org/tizen/common/util/io/Buffer.java b/org.tizen.common/src/org/tizen/common/util/io/Buffer.java
new file mode 100644
index 000000000..888d346c7
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/util/io/Buffer.java
@@ -0,0 +1,504 @@
+/*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common.util.io;
+
+import java.io.Closeable;
+import java.io.EOFException;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.channels.SocketChannel;
+import java.util.LinkedList;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * <p>
+ * Buffer.
+ *
+ * Buffer for high performance input / output
+ *
+ * No synchronized and no retention
+ *
+ * </p>
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ */
+public class
+Buffer
+implements Closeable
+{
+
+ /**
+ * Logger for this instance
+ */
+ protected Logger logger = LoggerFactory.getLogger( getClass() );
+
+ /**
+ * Pool for {@link ByteBuffer}
+ * @see BufferPool
+ */
+ protected BufferPool pool;
+
+ /**
+ * Used buffers
+ */
+ protected LinkedList<ByteBuffer> useds = new LinkedList<ByteBuffer>();
+
+ /**
+ * in-using read buffer
+ */
+ protected ByteBuffer readBuffer;
+
+ /**
+ * in-using write buffer
+ */
+ protected ByteBuffer writeBuffer;
+
+
+ /**
+ * in-using buffer
+ */
+ protected LinkedList<ByteBuffer> usings = new LinkedList<ByteBuffer>();
+
+ /**
+ * bytes to be read
+ */
+ protected int nReaded = 0;
+
+ /**
+ * total buffer size
+ */
+ protected int size = 0;
+
+ /**
+ * buffer index
+ */
+ protected int index;
+
+ /**
+ * Constructor with {@link BufferPool}
+ *
+ * @param pool {@link BufferPool}
+ */
+ public
+ Buffer(
+ final BufferPool pool
+ )
+ {
+ this.pool = pool;
+ }
+
+ /**
+ * <p>
+ * Return contents' size in buffer
+ * </p>
+ *
+ * @return contents' size
+ */
+ public
+ int
+ size()
+ {
+ return this.size;
+ }
+
+ /**
+ * <p>
+ * Return the number of buffer
+ * </p>
+ * @return the number of {@link ByteBuffer}
+ */
+ public
+ int
+ getBufferSize()
+ {
+ return useds.size() + usings.size() + ( ( null == readBuffer )?0:1 ) + ( ( null == writeBuffer )?0:1 );
+ }
+
+ /**
+ * Return in-using {@link ByteBuffer} for writing
+ *
+ * @return in-using buffer
+ *
+ * @throws IOException When new buffer can't be created
+ */
+ public
+ ByteBuffer
+ getBufferForWrite()
+ throws IOException
+ {
+ if ( null == writeBuffer )
+ {
+ writeBuffer = pool.borrow();
+ }
+ else if ( writeBuffer.remaining() <= 0 )
+ {
+ writeBuffer.flip();
+ usings.addLast( writeBuffer );
+ writeBuffer = pool.borrow();
+ }
+
+ return writeBuffer;
+ }
+
+ /**
+ * Return in-using {@link ByteBuffer} for reading
+ *
+ * @return in-using buffer
+ *
+ * @throws IOException reserved
+ */
+ public
+ ByteBuffer
+ getBufferForRead()
+ throws IOException
+ {
+ if ( null != readBuffer && 0 == readBuffer.remaining() )
+ {
+ readBuffer.position( 0 );
+ useds.add( readBuffer );
+ readBuffer = null;
+ }
+
+ if ( null == readBuffer )
+ {
+ if ( usings.isEmpty() )
+ {
+ if ( null != writeBuffer )
+ {
+ readBuffer = writeBuffer;
+ readBuffer.flip();
+ writeBuffer = null;
+ }
+ else
+ {
+ return null;
+ }
+ }
+ else
+ {
+ readBuffer = usings.removeFirst();
+ }
+ }
+
+ return readBuffer;
+ }
+
+ /**
+ * Read bytes from <code>channel</code>
+ *
+ * @param channel {@link SocketChannel}
+ *
+ * @return the number character to read
+ *
+ * @throws IOException When buffer is NOT available
+ */
+ public
+ int
+ readFrom(
+ final SocketChannel channel
+ )
+ throws IOException
+ {
+ int sum = 0;
+ int nCnt = 0;
+ while ( true )
+ {
+ final ByteBuffer buffer = getBufferForWrite();
+ int nRead = channel.read( buffer );
+ if ( nRead < 0 )
+ {
+ throw new EOFException();
+ }
+ else if ( 0 == nRead )
+ {
+ this.size += sum;
+ if ( 0 < sum )
+ {
+ logger.info( "{} bytes[{}] read from {}", new Object[] { sum, nCnt, channel } );
+ }
+ return sum;
+ }
+ sum += nRead;
+ ++nCnt;
+ }
+ }
+
+
+ /**
+ * Write all contents to <code>channel</code>
+ *
+ * @param channel {@link SocketChannel}
+ *
+ * @return the number of bytes to write
+ *
+ * @throws IOException When buffer is NOT available
+ */
+ public
+ int
+ writeTo(
+ final SocketChannel channel
+ ) throws IOException
+ {
+ int sum = 0;
+
+ while ( 0 < size )
+ {
+ final ByteBuffer buffer = getBufferForRead();
+ final int nWrite = channel.write( buffer );
+ if ( 0 < nWrite )
+ {
+ this.size -= nWrite;
+ sum += nWrite;
+ }
+ }
+
+ nReaded += sum;
+
+ logger.info( "Send {} bytes to {}", sum, channel );
+
+ return sum;
+ }
+
+ /**
+ * Read and return a byte character from buffer
+ *
+ * @return character to read
+ *
+ * @throws IOException When buffer is NOT available
+ */
+ public
+ int
+ read()
+ throws IOException
+ {
+ final ByteBuffer buffer = getBufferForRead();
+ if ( null == buffer )
+ {
+ return -1;
+ }
+
+ int ch = (int) ( 0xFF & buffer.get() );
+ --size;
+ ++nReaded;
+
+ return ch;
+ }
+
+ /**
+ * Read integer from buffer
+ *
+ * @return integer to read
+ *
+ * @throws IOException When buffer is NOT available
+ */
+ public
+ int
+ readInt() throws IOException
+ {
+ int i1 = read();
+ int i2 = read();
+ int i3 = read();
+ int i4 = read();
+
+ return ( (int) 0xFF & i1 ) << 24 | ( (int) 0xFF & i2 ) << 16 | ( (int) 0xFF & i3 ) << 8 | ( (int) 0xFF & i4 );
+ }
+
+ /**
+ * Write a byte character to buffer
+ *
+ * @param value character to write
+ *
+ * @throws IOException When buffer is NOT available
+ */
+ public
+ void
+ write( final int value ) throws IOException
+ {
+ final ByteBuffer buffer = getBufferForWrite();
+ buffer.put( (byte) value );
+ ++size;
+ }
+
+ /**
+ * Write <code>bytes</code> to buffer
+ *
+ * @param bytes contents to write
+ *
+ * @throws IOException When buffer is NOT available
+ */
+ public
+ void
+ write( final byte[] bytes ) throws IOException
+ {
+ for ( int i = 0, n = bytes.length ; i < n ; )
+ {
+ final ByteBuffer buffer = getBufferForWrite();
+ final int remaingSize = buffer.remaining();
+ buffer.put( bytes, i, remaingSize );
+ i += remaingSize;
+ }
+ }
+
+ /**
+ * Write integer to buffer
+ *
+ * @param value integer to write
+ *
+ * @throws IOException When buffer is NOT available
+ */
+ public
+ void
+ writeInt(
+ final int value
+ )
+ throws IOException
+ {
+ write( 0xFF & ( value >> 24 ) );
+ write( 0xFF & ( value >> 16 ) );
+ write( 0xFF & ( value >> 8 ) );
+ write( 0xFF & ( value ) );
+ }
+
+ /**
+ * Reset using resource( buffer, index, ...etc )
+ */
+ public
+ void
+ reset()
+ {
+ if ( null != readBuffer )
+ {
+ readBuffer.position();
+ useds.add( readBuffer );
+ }
+
+ useds.addAll( usings );
+
+ if ( null != writeBuffer )
+ {
+ writeBuffer.flip();
+ useds.add( writeBuffer );
+ writeBuffer = null;
+ }
+
+ usings = useds;
+ useds = new LinkedList<ByteBuffer>();
+ size += nReaded;
+ nReaded = 0;
+ }
+
+ /**
+ * Pack unused resource
+ *
+ * @throws IOException When {@link ByteBuffer} can't be release
+ */
+ synchronized public
+ void
+ pack() throws IOException
+ {
+ for ( final ByteBuffer buffer : useds )
+ {
+ nReaded -= buffer.remaining();
+ pool.release( buffer );
+ }
+
+ useds.clear();
+ }
+
+ /* (non-Javadoc)
+ * @see java.io.Closeable#close()
+ */
+ synchronized public
+ void
+ close()
+ throws IOException
+ {
+ if ( null != readBuffer )
+ {
+ pool.release( readBuffer );
+ readBuffer = null;
+ }
+ for ( final ByteBuffer buffer : usings )
+ {
+ pool.release( buffer );
+ }
+ usings.clear();
+ if ( null != writeBuffer )
+ {
+ pool.release( writeBuffer );
+ writeBuffer = null;
+ }
+
+ for ( final ByteBuffer buffer : useds )
+ {
+ pool.release( buffer );
+ }
+
+ useds.clear();
+ }
+
+ /**
+ * Concatencate buffers
+ *
+ * @param buffers {@link Buffer}s to concatenate
+ *
+ * @return {@link Buffer} to be concatenate
+ */
+ public static
+ Buffer
+ concatenate(
+ final Buffer... buffers
+ )
+ {
+ final Buffer ret = new Buffer( null );
+ boolean bInit = false;
+ for ( final Buffer buffer : buffers )
+ {
+ if ( bInit && ret.pool != buffer.pool )
+ {
+ throw new IllegalArgumentException( "Unmatching buffer pool" );
+ }
+ ret.pool = buffer.pool;
+ bInit = true;
+
+ buffer.reset();
+ ret.usings.addAll( buffer.usings );
+ ret.size += buffer.size;
+ }
+
+ return ret;
+ }
+
+ /* (non-Javadoc)
+ * @see java.lang.Object#toString()
+ */
+ public String toString()
+ {
+ return "Buffer[" + size + "]";
+ }
+}
+
diff --git a/org.tizen.common/src/org/tizen/common/util/io/BufferInputStream.java b/org.tizen.common/src/org/tizen/common/util/io/BufferInputStream.java
new file mode 100644
index 000000000..32608a9a6
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/util/io/BufferInputStream.java
@@ -0,0 +1,81 @@
+/*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common.util.io;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.ByteBuffer;
+
+/**
+ * <p>
+ * BufferInputStream.
+ *
+ * {@link InputStream} to use {@link Buffer}
+ * </p>
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ *
+ * @see Buffer
+ */
+public class
+BufferInputStream
+extends InputStream
+{
+ /**
+ * buffer to store bytes
+ */
+ protected final Buffer buffer;
+
+ /**
+ * Constructor with buffer
+ *
+ * @param buffer {@link ByteBuffer}
+ */
+ public
+ BufferInputStream(
+ final Buffer buffer
+ )
+ {
+ if ( null == buffer )
+ {
+ throw new NullPointerException();
+ }
+
+ this.buffer = buffer;
+ }
+
+ /* (non-Javadoc)
+ * @see java.io.InputStream#read()
+ */
+ @Override
+ public
+ int
+ read()
+ throws IOException
+ {
+ return buffer.read();
+ }
+
+}
diff --git a/org.tizen.common/src/org/tizen/common/util/io/BufferOutputStream.java b/org.tizen.common/src/org/tizen/common/util/io/BufferOutputStream.java
new file mode 100644
index 000000000..3a4a195ae
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/util/io/BufferOutputStream.java
@@ -0,0 +1,94 @@
+/*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common.util.io;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.nio.ByteBuffer;
+
+/**
+ * <p>
+ * BufferOutputStream.
+ *
+ * {@link OutputStream} to use {@link Buffer}
+ * </p>
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ *
+ * @see Buffer
+ */
+public class
+BufferOutputStream
+extends OutputStream
+{
+ /**
+ * buffer to store bytes
+ */
+ protected Buffer buffer;
+
+ /**
+ * Constructor with buffer
+ *
+ * @param buffer {@link ByteBuffer}
+ */
+ public
+ BufferOutputStream(
+ final Buffer buffer
+ )
+ {
+ if ( null == buffer )
+ {
+ throw new NullPointerException();
+ }
+ this.buffer = buffer;
+ }
+
+ /**
+ * Return internal buffer
+ *
+ * @return {@link Buffer}
+ */
+ public
+ Buffer
+ getBuffer()
+ {
+ return this.buffer;
+ }
+
+ /* (non-Javadoc)
+ * @see java.io.OutputStream#write(int)
+ */
+ @Override
+ public
+ void
+ write(
+ final int b
+ )
+ throws IOException
+ {
+ buffer.write( b );
+ }
+
+}
diff --git a/org.tizen.common/src/org/tizen/common/util/io/BufferPool.java b/org.tizen.common/src/org/tizen/common/util/io/BufferPool.java
new file mode 100644
index 000000000..ee6d938b7
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/util/io/BufferPool.java
@@ -0,0 +1,248 @@
+/*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common.util.io;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.util.LinkedList;
+
+import org.apache.commons.lang3.ObjectUtils;
+import org.apache.commons.pool.BasePoolableObjectFactory;
+import org.apache.commons.pool.ObjectPool;
+import org.apache.commons.pool.impl.GenericObjectPoolFactory;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * <p>
+ * BufferPool.
+ *
+ * Pool for {@link Buffer}
+ * </p>
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ *
+ */
+public class
+BufferPool
+implements Closeable
+{
+
+ /**
+ * The default number of buffer fragments
+ */
+ protected static final int N_CREATION = 1024;
+
+ /**
+ * Buffer fragment's default size
+ */
+ protected static final int BUFFER_SIZE = 256;
+
+ /**
+ * Logger for this instance
+ */
+ protected final Logger logger = LoggerFactory.getLogger( getClass() );
+
+ /**
+ * The number of buffer fragements to create
+ */
+ protected int nCreation = N_CREATION;
+
+ /**
+ * Buffer fragement's size
+ */
+ protected int bufferSize = BUFFER_SIZE;
+
+ /**
+ * Set the number of fragment
+ *
+ * @param nCreation the number of fragment
+ */
+ public
+ void
+ setNumberOfFragments(
+ final int nCreation
+ )
+ {
+ this.nCreation = nCreation;
+ }
+
+ /**
+ * Set buffer fragment's size
+ * @param bufferSize buffer fargement's size
+ */
+ public
+ void
+ setSizeOfFragment(
+ final int bufferSize
+ )
+ {
+ this.bufferSize = bufferSize;
+ }
+
+ /**
+ * Pool for {@link ByteBuffer}
+ */
+ protected final ObjectPool<ByteBuffer> bufferPool =
+ new GenericObjectPoolFactory<ByteBuffer>( new BasePoolableObjectFactory<ByteBuffer>() {
+
+ protected final LinkedList<ByteBuffer> buffers = new LinkedList<ByteBuffer>();
+
+ /* (non-Javadoc)
+ * @see org.apache.commons.pool.BasePoolableObjectFactory#makeObject()
+ */
+ @Override
+ public
+ ByteBuffer
+ makeObject()
+ throws Exception
+ {
+ logger.trace( "{} buffer(s) exist", buffers.size() );
+ if ( !buffers.isEmpty() )
+ {
+ return buffers.removeFirst();
+ }
+
+ final long startTime = System.currentTimeMillis();
+ final int totalSize = nCreation * bufferSize;
+
+ final ByteBuffer totalBuffer = ByteBuffer.allocateDirect( totalSize );
+
+ for ( int limit = bufferSize ; limit <= totalSize ; limit += bufferSize )
+ {
+ totalBuffer.limit( limit );
+ buffers.add( totalBuffer.slice() );
+ totalBuffer.position( limit );
+ }
+
+ final long endTime = System.currentTimeMillis();
+ logger.info( "Buffer creation time :{} ms", ( endTime - startTime ) );
+
+ return buffers.removeFirst();
+ }
+
+
+ /* (non-Javadoc)
+ * @see org.apache.commons.pool.BasePoolableObjectFactory#activateObject(java.lang.Object)
+ */
+ public
+ void
+ activateObject(
+ final ByteBuffer buffer
+ )
+ throws Exception
+ {
+ super.activateObject( buffer );
+
+ buffer.clear();
+ }
+
+ }, -1 ).createPool();
+
+ /**
+ * Pick-up and return {@link ByteBuffer} from pool
+ *
+ * @return {@link ByteBuffer}
+ *
+ * @throws IOException When {@link ByteBuffer} can't be created or available
+ */
+ public
+ ByteBuffer
+ borrow()
+ throws IOException
+ {
+ try
+ {
+ return bufferPool.borrowObject();
+ }
+ catch (
+ final Exception e
+ )
+ {
+ throw new IOException( e );
+ }
+ }
+
+ /**
+ * Release buffer to pool
+ *
+ * @param buffer {@link ByteBuffer} to release
+ *
+ * @throws IOException When {@link ByteBuffer} can't be release
+ */
+ public
+ void
+ release(
+ final ByteBuffer buffer
+ ) throws IOException
+ {
+ try
+ {
+ bufferPool.returnObject( buffer );
+ }
+ catch
+ (
+ final Exception e
+ )
+ {
+ throw new IOException( e );
+ }
+ }
+
+ /* (non-Javadoc)
+ * @see java.io.Closeable#close()
+ */
+ @Override
+ public
+ void
+ close()
+ throws IOException
+ {
+
+ try {
+ bufferPool.close();
+ } catch (
+ final Exception e
+ )
+ {
+ throw new IOException( e );
+ }
+
+ }
+
+ /* (non-Javadoc)
+ * @see java.lang.Object#toString()
+ */
+ @Override
+ public
+ String
+ toString()
+ {
+ return ObjectUtils.toString( this );
+ }
+
+
+}
diff --git a/org.tizen.common/src/org/tizen/common/log/Logger.java b/org.tizen.common/src/org/tizen/common/util/log/Logger.java
index 6f09f7824..59d172173 100644
--- a/org.tizen.common/src/org/tizen/common/log/Logger.java
+++ b/org.tizen.common/src/org/tizen/common/util/log/Logger.java
@@ -23,7 +23,7 @@
*
*/
-package org.tizen.common.log;
+package org.tizen.common.util.log;
import java.text.MessageFormat;
@@ -31,7 +31,7 @@ import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.tizen.common.CommonPlugin;
-import org.tizen.common.console.ConsoleManager;
+import org.tizen.common.ui.view.console.ConsoleManager;
/**
@@ -74,6 +74,11 @@ public class Logger {
log(new Status(IStatus.ERROR, getCallerName(), e.toString(), e));
}
}
+
+ public static void debug( String message, Object... arguments )
+ {
+
+ }
public static void info(String message, Object... arguments) {
log(new Status(Status.INFO, getCallerName(), getPossiblyFormattedString(message, arguments)));
diff --git a/org.tizen.common/src/org/tizen/common/util/url/classpath/Connection.java b/org.tizen.common/src/org/tizen/common/util/url/classpath/Connection.java
new file mode 100644
index 000000000..55b015f8b
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/util/url/classpath/Connection.java
@@ -0,0 +1,181 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* BonYong Lee <bonyong.lee@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+package org.tizen.common.util.url.classpath;
+
+import static org.tizen.common.util.StringUtil.removeLastSegment;
+import static org.tizen.common.util.StringUtil.trimLeadingCharacter;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
+import java.net.URLConnection;
+import java.util.Collection;
+import java.util.LinkedHashSet;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.tizen.common.util.Assert;
+
+/**
+ * Connection.
+ *
+ * {@link URLConnection} for classpath url
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ */
+public class
+Connection
+extends URLConnection
+{
+
+ protected final Logger logger = LoggerFactory.getLogger( getClass() );
+
+ protected String fqcn;
+
+ protected URL internalUrl = null;
+
+ /**
+ * <p>
+ * Constructor with classpath url
+ * </p>
+ *
+ * @param url url for resouce in classpath
+ */
+ protected Connection( final URL url, final String fqcn )
+ {
+ super( url );
+
+ this.fqcn = fqcn;
+ logger.debug( "Fully qualified class name :{}", fqcn );
+ }
+
+ /* (non-Javadoc)
+ * @see java.net.URLConnection#connect()
+ */
+ @Override
+ public
+ void
+ connect()
+ throws IOException
+ {
+ Assert.isNull( this.internalUrl );
+
+ final String path = trimLeadingCharacter( getURL().getPath(), '/' );
+
+ final Collection<ClassLoader> classLoaders = getClassLoaders();
+ logger.trace( "Classloaders :{}", classLoaders );
+
+ for ( final ClassLoader cl : classLoaders )
+ {
+ URL url = cl.getResource( path );
+ logger.trace( "Check url for {} :{}", path, url );
+ if ( null == url )
+ {
+ continue;
+ }
+
+ this.internalUrl = url;
+ connected = true;
+ return ;
+ }
+
+ if ( null == fqcn )
+ {
+ connected = true;
+ return ;
+ }
+
+ final String packageName = removeLastSegment( fqcn, "." );
+ final String fullPath = trimLeadingCharacter( packageName.replace( '.', '/' ), '/' ) + "/" + path;
+ logger.trace( "Package name :{}, Full path :{}", packageName, fullPath );
+
+ for ( final ClassLoader cl : classLoaders )
+ {
+ URL url = cl.getResource( fullPath );
+ logger.trace( "Check url for {} :{}", fullPath, url );
+ if ( null == url )
+ {
+ continue;
+ }
+
+ this.internalUrl = url;
+ connected = true;
+ return ;
+ }
+
+ }
+
+ /**
+ * <p>
+ * Return classloaders to provide resource<br>
+ *
+ * ClassLoader is following
+ * <ul>
+ * <li>Context ClassLoader</li>
+ * <li>ClassLoader for this class</li>
+ * <li>SystemClassLoader</li>
+ * </ul>
+ * </p>
+ *
+ * @return {@link ClassLoader} candidate
+ */
+ protected static Collection<ClassLoader> getClassLoaders()
+ {
+ final LinkedHashSet<ClassLoader> classLoaders = new LinkedHashSet<ClassLoader>();
+
+ if ( null != Thread.currentThread().getContextClassLoader() )
+ {
+ classLoaders.add( Thread.currentThread().getContextClassLoader() );
+ }
+
+ classLoaders.add( Connection.class.getClassLoader() );
+ classLoaders.add( ClassLoader.getSystemClassLoader() );
+
+ return classLoaders;
+ }
+
+ /* (non-Javadoc)
+ * @see java.net.URLConnection#getInputStream()
+ */
+ @Override
+ public
+ InputStream
+ getInputStream()
+ throws IOException
+ {
+ if ( !connected )
+ {
+ connect();
+ }
+ if ( null == this.internalUrl )
+ {
+ throw new IOException( "resource not found" );
+ }
+ logger.trace( "Open stream :{}", internalUrl );
+
+ return internalUrl.openStream();
+ }
+
+}
diff --git a/org.tizen.common/src/org/tizen/common/util/url/classpath/Handler.java b/org.tizen.common/src/org/tizen/common/util/url/classpath/Handler.java
new file mode 100644
index 000000000..b87d5aee7
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/util/url/classpath/Handler.java
@@ -0,0 +1,104 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* BonYong Lee <bonyong.lee@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+package org.tizen.common.util.url.classpath;
+
+import java.io.IOException;
+import java.net.URL;
+import java.net.URLConnection;
+import java.net.URLStreamHandler;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.tizen.common.util.ObjectUtil;
+
+/**
+ * Handler.
+ *
+ * {@link URLStreamHandler} for classpath url
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ */
+public class
+Handler
+extends URLStreamHandler
+{
+
+
+ /**
+ * Logger of object
+ */
+ protected final Logger logger = LoggerFactory.getLogger( getClass() );
+
+ /**
+ * Full qualified class name of caller( exactly caller that call new URL() )
+ */
+ protected final String fqcnOfCaller;
+
+ public Handler()
+ {
+ fqcnOfCaller = pickupCaller();
+ }
+
+ protected String pickupCaller()
+ {
+ final StackTraceElement[] callStacks = new Exception().getStackTrace();
+
+ boolean bUrl = false;
+
+ for ( final StackTraceElement element : callStacks )
+ {
+ logger.trace( "Check stack :{}", element );
+ final String className = element.getClassName();
+ logger.trace( "Class :{}", className );
+
+ if ( ObjectUtil.equals( className, URL.class.getName() ) )
+ {
+ bUrl = true;
+ }
+ else if ( bUrl )
+ {
+ return className;
+ }
+ }
+
+ return null;
+ }
+
+
+ /* (non-Javadoc)
+ * @see java.net.URLStreamHandler#openConnection(java.net.URL)
+ */
+ @Override
+ protected
+ URLConnection
+ openConnection(
+ final URL u
+ )
+ throws IOException
+ {
+ return new Connection( u, fqcnOfCaller );
+ }
+
+}
diff --git a/org.tizen.common/src/org/tizen/common/util/url/cp/Connection.java b/org.tizen.common/src/org/tizen/common/util/url/cp/Connection.java
new file mode 100644
index 000000000..7c13ac232
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/util/url/cp/Connection.java
@@ -0,0 +1,54 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* BonYong Lee <bonyong.lee@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+package org.tizen.common.util.url.cp;
+
+import java.net.URL;
+import java.net.URLConnection;
+
+/**
+ * Connection.
+ *
+ * {@link URLConnection} for classpath url
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ *
+ * @see org.tizen.common.util.url.classpath.Connection
+ */
+public class
+Connection
+extends org.tizen.common.util.url.classpath.Connection
+{
+
+ /**
+ * Constructor with url
+ *
+ * @param url {@link URL}
+ */
+ protected Connection( final URL url, final String fqcn )
+ {
+ super( url, fqcn );
+ }
+
+}
diff --git a/org.tizen.common/src/org/tizen/common/util/url/cp/Handler.java b/org.tizen.common/src/org/tizen/common/util/url/cp/Handler.java
new file mode 100644
index 000000000..d2f9686b9
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/util/url/cp/Handler.java
@@ -0,0 +1,60 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* BonYong Lee <bonyong.lee@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+package org.tizen.common.util.url.cp;
+
+import java.io.IOException;
+import java.net.URL;
+import java.net.URLConnection;
+import java.net.URLStreamHandler;
+
+/**
+ * Handler.
+ *
+ * {@link URLStreamHandler} for classpath url
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ *
+ * @see org.tizen.common.util.url.classpath.Handler
+ */
+public class
+Handler
+extends org.tizen.common.util.url.classpath.Handler
+{
+
+ /* (non-Javadoc)
+ * @see java.net.URLStreamHandler#openConnection(java.net.URL)
+ */
+ @Override
+ protected
+ URLConnection
+ openConnection(
+ final URL u
+ )
+ throws IOException
+ {
+ return new Connection( u, fqcnOfCaller );
+ }
+
+}
diff --git a/org.tizen.common/src/org/tizen/common/util/url/vf/Connection.java b/org.tizen.common/src/org/tizen/common/util/url/vf/Connection.java
new file mode 100644
index 000000000..e32f42da2
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/util/url/vf/Connection.java
@@ -0,0 +1,125 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* BonYong Lee <bonyong.lee@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+package org.tizen.common.util.url.vf;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
+import java.net.URLConnection;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.tizen.common.file.VirtualFileHandler;
+
+/**
+ * Connection.
+ *
+ * {@link URLConnection} for {@link VirtualFileHandler}
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ */
+public class
+Connection
+extends URLConnection
+{
+
+ /**
+ * Virutal file handler to search
+ */
+ protected static VirtualFileHandler vfHandler = new VirtualFileHandler();
+
+ /**
+ * Logger for this instance
+ */
+ protected final Logger logger = LoggerFactory.getLogger( getClass() );
+
+ /**
+ * Return {@link VirtualFileHandler} to search
+ *
+ * @return {@link #vfHandler}
+ */
+ public static
+ VirtualFileHandler
+ getVirtualFileHandler()
+ {
+ return vfHandler;
+ }
+
+ /**
+ * Set {@link VirtualFileHandler} to search
+ *
+ * @param vfHandler new {@link VirtualFileHandler}
+ */
+ public static
+ void
+ setVirtualFileHandler(
+ final VirtualFileHandler vfHandler
+ )
+ {
+ Connection.vfHandler = vfHandler;
+ }
+
+
+
+
+ /**
+ * Constructor with url
+ *
+ * @param url {@link URL}
+ */
+ protected
+ Connection(
+ final URL url
+ )
+ {
+ super( url );
+ logger.trace( "URL :{}", url );
+ }
+
+ /* (non-Javadoc)
+ * @see java.net.URLConnection#connect()
+ */
+ @Override
+ public
+ void
+ connect()
+ throws IOException
+ {
+ logger.trace( "connect" );
+ }
+
+ /* (non-Javadoc)
+ * @see java.net.URLConnection#getInputStream()
+ */
+ public
+ InputStream
+ getInputStream()
+ throws IOException
+ {
+ final String path = url.getPath();
+ logger.trace( "Path :{}", path );
+ return vfHandler.read( path );
+ }
+}
diff --git a/org.tizen.common/src/org/tizen/common/util/url/vf/Handler.java b/org.tizen.common/src/org/tizen/common/util/url/vf/Handler.java
new file mode 100644
index 000000000..95089ff68
--- /dev/null
+++ b/org.tizen.common/src/org/tizen/common/util/url/vf/Handler.java
@@ -0,0 +1,59 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* BonYong Lee <bonyong.lee@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+package org.tizen.common.util.url.vf;
+
+import java.io.IOException;
+import java.net.URL;
+import java.net.URLConnection;
+import java.net.URLStreamHandler;
+
+/**
+ * Handler.
+ *
+ * {@link URLStreamHandler} for classpath url
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ *
+ * @see org.tizen.common.util.url.classpath.Handler
+ */
+public class
+Handler
+extends URLStreamHandler
+{
+ /* (non-Javadoc)
+ * @see java.net.URLStreamHandler#openConnection(java.net.URL)
+ */
+ @Override
+ protected
+ URLConnection
+ openConnection(
+ final URL u
+ )
+ throws IOException
+ {
+ return new Connection( u );
+ }
+
+}
diff --git a/org.tizen.common/test/lib/asm-4.0.jar b/org.tizen.common/test/lib/asm-4.0.jar
new file mode 100644
index 000000000..6d63075eb
--- /dev/null
+++ b/org.tizen.common/test/lib/asm-4.0.jar
Binary files differ
diff --git a/org.tizen.common/test/lib/asm-tree-4.0.jar b/org.tizen.common/test/lib/asm-tree-4.0.jar
new file mode 100644
index 000000000..aa99d3a3c
--- /dev/null
+++ b/org.tizen.common/test/lib/asm-tree-4.0.jar
Binary files differ
diff --git a/org.tizen.common/test/lib/junit-4.10-src.jar b/org.tizen.common/test/lib/junit-4.10-src.jar
new file mode 100644
index 000000000..1449d28b5
--- /dev/null
+++ b/org.tizen.common/test/lib/junit-4.10-src.jar
Binary files differ
diff --git a/org.tizen.common/test/lib/junit-4.10.jar b/org.tizen.common/test/lib/junit-4.10.jar
new file mode 100644
index 000000000..bf5c0b9c6
--- /dev/null
+++ b/org.tizen.common/test/lib/junit-4.10.jar
Binary files differ
diff --git a/org.tizen.common/test/lib/mockito-all-1.9.0.jar b/org.tizen.common/test/lib/mockito-all-1.9.0.jar
new file mode 100644
index 000000000..273fd50fe
--- /dev/null
+++ b/org.tizen.common/test/lib/mockito-all-1.9.0.jar
Binary files differ
diff --git a/org.tizen.common/test/src/log4j.xml b/org.tizen.common/test/src/log4j.xml
new file mode 100755
index 000000000..e5d1893f3
--- /dev/null
+++ b/org.tizen.common/test/src/log4j.xml
@@ -0,0 +1,15 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE log4j:configuration PUBLIC "-//APACHE//DTD LOG4J 1.2//EN" "log4j.dtd">
+<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
+ <appender name="console" class="org.apache.log4j.ConsoleAppender">
+ <param name="Target" value="System.out" />
+ <layout class="org.apache.log4j.PatternLayout">
+ <param name="ConversionPattern" value="[%p] %F(%L) - %m%n" />
+ </layout>
+ </appender>
+
+ <root>
+ <priority value="info" />
+ <appender-ref ref="console" />
+ </root>
+</log4j:configuration> \ No newline at end of file
diff --git a/org.tizen.common/test/src/org/tizen/common/AppIdGeneratorTest.java b/org.tizen.common/test/src/org/tizen/common/AppIdGeneratorTest.java
new file mode 100644
index 000000000..3481b7ed4
--- /dev/null
+++ b/org.tizen.common/test/src/org/tizen/common/AppIdGeneratorTest.java
@@ -0,0 +1,76 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* ChangHyun Lee <changhyun1.lee@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+package org.tizen.common;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import org.junit.Test;
+
+/**
+ * AppIdGeneratorTest.
+ *
+ * Test case for {@link AppIdGenerator}
+ *
+ * @author Changhyun Lee{@literal <changhyun1.lee@samsung.com>} (S-Core)
+ *
+ * @see AppIdGenerator
+ *
+ */
+public class AppIdGeneratorTest {
+
+ /**
+ * Test {@link AppIdGenerator#generate()}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see {@link AppIdGenerator#generate()}
+ */
+ @Test
+ public void test_generate() throws Exception {
+ AppIdGenerator generator = new AppIdGenerator();
+ String id = generator.generate();
+ String id2 = generator.generate();
+ assertTrue(id.length() == 10);
+ assertTrue(id2.length() == 10);
+ }
+
+ /**
+ * Test {@link AppIdGenerator#generate(int size)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see {@link AppIdGenerator#generate(int size)}
+ */
+ @Test
+ public void test_generate2() throws Exception {
+ AppIdGenerator generator = new AppIdGenerator();
+ String id = generator.generate(10);
+ String id2 = generator.generate(11);
+ assertTrue(id.length() == 10);
+ assertTrue(id2.length() == 11);
+ }
+
+}
diff --git a/org.tizen.common/test/src/org/tizen/common/ClassSource.java b/org.tizen.common/test/src/org/tizen/common/ClassSource.java
new file mode 100644
index 000000000..6e4a9ccc8
--- /dev/null
+++ b/org.tizen.common/test/src/org/tizen/common/ClassSource.java
@@ -0,0 +1,53 @@
+/*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common;
+
+import java.io.IOException;
+import java.io.InputStream;
+
+/**
+ * <p>
+ * ClassSource.
+ *
+ * Provide resource in class path
+ * </p>
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ */
+public interface
+ClassSource
+{
+ /**
+ * Provide {@link InputStream} of resource having <code>path</code> besed on classpath
+ *
+ * @param path relative path based on classpath
+ *
+ * @return {@link InputStream}
+ *
+ * @throws IOException If resource can't be accessible
+ */
+ InputStream getResource( String path ) throws IOException;
+
+}
diff --git a/org.tizen.common/test/src/org/tizen/common/CommonPluginTest.java b/org.tizen.common/test/src/org/tizen/common/CommonPluginTest.java
new file mode 100644
index 000000000..4082bfa42
--- /dev/null
+++ b/org.tizen.common/test/src/org/tizen/common/CommonPluginTest.java
@@ -0,0 +1,80 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* BonYong Lee <bonyong.lee@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+package org.tizen.common;
+
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.tizen.common.FrequentlyUsedMatcher.doNotCare;
+
+import org.eclipse.jface.preference.IPreferenceStore;
+import org.junit.Test;
+import org.tizen.common.core.application.InstallPathConfig;
+import org.tizen.common.ui.page.preference.TizenBasePreferencePage;
+
+
+
+/**
+ * CommonPluginTest
+ *
+ * Test case for {@link CommonPlugin}
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ *
+ * @see CommonPlugin
+ */
+public class
+CommonPluginTest
+{
+ /**
+ * Test {@link CommonPlugin#initializeDefaultPreferences(IPreferenceStore)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see CommonPlugin#initializeDefaultPreferences(IPreferenceStore)
+ */
+ @Test
+ public void test_initializeDefaultPreferences() throws Exception
+ {
+ final CommonPlugin plugin = new CommonPlugin();
+ final IPreferenceStore preferenceStore = mock( IPreferenceStore.class );
+
+ plugin.initializeDefaultPreferences( preferenceStore );
+
+ /*
+ * LookAtMe : Test with No argument specification
+ */
+ if ( null != InstallPathConfig.getSDKPath() )
+ {
+ // in case of non-installed env.
+ verify( preferenceStore ).setDefault(
+ eq( TizenBasePreferencePage.KEY_SDKLOCATION ),
+ (String) doNotCare()
+ );
+ }
+ verify( preferenceStore ).setDefault( TizenBasePreferencePage.KEY_SDKUPDATE, true );
+ }
+
+}
diff --git a/org.tizen.common/test/src/org/tizen/common/DirectorySource.java b/org.tizen.common/test/src/org/tizen/common/DirectorySource.java
new file mode 100644
index 000000000..172d9cc7c
--- /dev/null
+++ b/org.tizen.common/test/src/org/tizen/common/DirectorySource.java
@@ -0,0 +1,85 @@
+/*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+
+/**
+ * <p>
+ * DirectorySource.
+ *
+ * Directory base {@link ClassSource}
+ *
+ * Provide *.class file as {@link InputStream}
+ * </p>
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ */
+public class
+DirectorySource
+implements ClassSource
+{
+ /**
+ * Root directory
+ */
+ protected final File root;
+
+ /**
+ * Constructor with base directory path
+ *
+ * @param root directory path
+ */
+ public
+ DirectorySource(
+ final String root
+ )
+ {
+ this.root = new File( root );
+ }
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.ClassSource#getResource(java.lang.String)
+ */
+ @Override
+ public
+ InputStream
+ getResource(
+ final String path
+ )
+ throws IOException
+ {
+ final File file = new File( root, path );
+
+ if ( file.exists() && file.canRead() )
+ {
+ return new FileInputStream( file );
+ }
+ return null;
+ }
+
+}
diff --git a/org.tizen.common/test/src/org/tizen/common/FrequentlyUsedMatcher.java b/org.tizen.common/test/src/org/tizen/common/FrequentlyUsedMatcher.java
new file mode 100644
index 000000000..01423c6d3
--- /dev/null
+++ b/org.tizen.common/test/src/org/tizen/common/FrequentlyUsedMatcher.java
@@ -0,0 +1,70 @@
+package org.tizen.common;
+
+import org.hamcrest.BaseMatcher;
+import org.hamcrest.Description;
+import org.mockito.Matchers;
+
+public class FrequentlyUsedMatcher
+{
+ public static <T> T doNotCare()
+ {
+ return Matchers.argThat( new BaseMatcher<T>()
+ {
+ public boolean matches( final Object arg )
+ {
+ return true;
+ }
+
+ public void describeTo( final Description desc )
+ {
+ }
+ } );
+ }
+
+ public static <T> T eq( T type )
+ {
+ return Matchers.eq( type );
+ }
+
+
+ public static boolean eq( boolean type )
+ {
+ return Matchers.eq( type );
+ }
+
+ public static byte eq( byte type )
+ {
+ return Matchers.eq( type );
+ }
+
+ public static char eq( char type )
+ {
+ return Matchers.eq( type );
+ }
+
+ public static double eq( double type )
+ {
+ return Matchers.eq( type );
+ }
+
+ public static float eq( float type )
+ {
+ return Matchers.eq( type );
+ }
+
+ public static int eq( int type )
+ {
+ return Matchers.eq( type );
+ }
+
+ public static long eq( long type )
+ {
+ return Matchers.eq( type );
+ }
+
+ public static short eq( short type )
+ {
+ return Matchers.eq( type );
+ }
+
+}
diff --git a/org.tizen.common/test/src/org/tizen/common/JarSource.java b/org.tizen.common/test/src/org/tizen/common/JarSource.java
new file mode 100644
index 000000000..60033bdd2
--- /dev/null
+++ b/org.tizen.common/test/src/org/tizen/common/JarSource.java
@@ -0,0 +1,103 @@
+/*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common;
+
+import static org.tizen.common.util.IOUtil.getBytes;
+import static org.tizen.common.util.IOUtil.tryClose;
+
+import java.io.ByteArrayInputStream;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.jar.JarEntry;
+import java.util.jar.JarFile;
+
+/**
+ * <p>
+ * JarSource.
+ *
+ * Read jar file and provide class {@link InputStream}
+ * </p>
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ */
+public class
+JarSource
+implements ClassSource
+{
+
+ /**
+ * Jar file path
+ */
+ protected final String path;
+
+ /**
+ * Constructor with jar file path
+ *
+ * @param location jar path
+ */
+ public
+ JarSource(
+ String location
+ )
+ {
+ if ( null == location )
+ {
+ throw new NullPointerException();
+ }
+ this.path = location;
+ }
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.ClassSource#getResource(java.lang.String)
+ */
+ @Override
+ public
+ InputStream
+ getResource(
+ final String path
+ )
+ throws IOException
+ {
+ final JarFile file = new JarFile( new File( this.path ) );
+ final JarEntry entry = file.getJarEntry( path );
+ if ( null == entry )
+ {
+ return null;
+ }
+ InputStream in = null;
+ try
+ {
+ in = file.getInputStream( entry );
+ ByteArrayInputStream byteIn = new ByteArrayInputStream( getBytes( in ) );
+ return byteIn;
+ }
+ finally
+ {
+ tryClose( in );
+ file.close();
+ }
+ }
+}
diff --git a/org.tizen.common/test/src/org/tizen/common/Location.java b/org.tizen.common/test/src/org/tizen/common/Location.java
new file mode 100644
index 000000000..3a08e95f6
--- /dev/null
+++ b/org.tizen.common/test/src/org/tizen/common/Location.java
@@ -0,0 +1,53 @@
+/*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common;
+
+import java.lang.annotation.Inherited;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * <p>
+ * Location.
+ *
+ * Annotation for class path
+ * </p>
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ */
+@Retention( RetentionPolicy.RUNTIME )
+@Target({java.lang.annotation.ElementType.TYPE})
+@Inherited
+public @interface Location
+{
+ /**
+ * reeturn classpath
+ *
+ * @return classpath
+ */
+ String[] value();
+
+}
diff --git a/org.tizen.common/test/src/org/tizen/common/TestAgent.java b/org.tizen.common/test/src/org/tizen/common/TestAgent.java
new file mode 100644
index 000000000..f06d4ae6e
--- /dev/null
+++ b/org.tizen.common/test/src/org/tizen/common/TestAgent.java
@@ -0,0 +1,17 @@
+package org.tizen.common;
+
+import java.lang.instrument.Instrumentation;
+
+public class
+TestAgent
+{
+ public static void premain(
+ final String name,
+ final Instrumentation inst
+ )
+ {
+ inst.addTransformer( new Transformer() );
+ }
+
+
+}
diff --git a/org.tizen.common/test/src/org/tizen/common/Transformer.java b/org.tizen.common/test/src/org/tizen/common/Transformer.java
new file mode 100644
index 000000000..bbdefa3c7
--- /dev/null
+++ b/org.tizen.common/test/src/org/tizen/common/Transformer.java
@@ -0,0 +1,38 @@
+package org.tizen.common;
+
+import java.lang.instrument.ClassFileTransformer;
+import java.lang.instrument.IllegalClassFormatException;
+import java.security.ProtectionDomain;
+
+import org.objectweb.asm.ClassReader;
+import org.objectweb.asm.ClassWriter;
+import org.objectweb.asm.Opcodes;
+import org.objectweb.asm.tree.ClassNode;
+
+public class
+Transformer
+implements ClassFileTransformer
+{
+ @Override
+ public
+ byte[] transform(
+ final ClassLoader loader,
+ final String className,
+ final Class<?> classBeingRedefined,
+ final ProtectionDomain protectionDomain,
+ final byte[] bytes
+ )
+ throws IllegalClassFormatException
+ {
+ ClassReader reader = new ClassReader( bytes );
+ ClassNode classNode = new ClassNode();
+ reader.accept( classNode, 0 );
+ classNode.access &= (~Opcodes.ACC_FINAL);
+
+ final ClassWriter cw =
+ new ClassWriter( ClassWriter.COMPUTE_MAXS|ClassWriter.COMPUTE_FRAMES );
+ classNode.accept( cw );
+ return cw.toByteArray();
+ }
+
+}
diff --git a/org.tizen.common/test/src/org/tizen/common/UnsafeClassLoader.java b/org.tizen.common/test/src/org/tizen/common/UnsafeClassLoader.java
new file mode 100644
index 000000000..dcf8d337f
--- /dev/null
+++ b/org.tizen.common/test/src/org/tizen/common/UnsafeClassLoader.java
@@ -0,0 +1,255 @@
+/*
+ *
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common;
+
+import static org.tizen.common.util.IOUtil.getBytes;
+import static org.tizen.common.util.IOUtil.tryClose;
+
+import java.io.ByteArrayInputStream;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.lang.instrument.ClassFileTransformer;
+import java.lang.instrument.IllegalClassFormatException;
+import java.util.ArrayList;
+import java.util.Arrays;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.tizen.common.util.IOUtil;
+
+
+/**
+ * <p>
+ * UnsafeClassLoader.
+ *
+ * Classloader for untestable class
+ *
+ * FIXME add {@link Package} info and {@link #getResource(String)}, {@link #getResourceAsStream(String)}, {@link #getResources(String)}
+ * </p>
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ */
+public class
+UnsafeClassLoader
+extends ClassLoader
+{
+ /**
+ * Logger for this instance
+ */
+ protected final Logger logger = LoggerFactory.getLogger( getClass() );
+
+ /**
+ * Parent classloader
+ */
+ protected final ClassLoader parent;
+
+ protected ClassFileTransformer transformer = new Transformer();
+
+ /**
+ * {@link ClassSource}s providing class contents
+ */
+ protected final ArrayList<ClassSource> sources = new ArrayList<ClassSource>();
+
+ /**
+ * Constructor with {@link ClassSource}s
+ * @param source
+ */
+ public
+ UnsafeClassLoader(
+ final ClassSource... source
+ )
+ {
+ this( null, source );
+ }
+
+ /**
+ * Constructor with parent class loader and class source
+ *
+ * @param parent {@link ClassLoader}
+ * @param sources {@link ClassSource}s
+ */
+ public
+ UnsafeClassLoader(
+ final ClassLoader parent,
+ final ClassSource... sources
+ )
+ {
+ this.parent = parent;
+ this.sources.addAll( Arrays.asList( sources ) );
+ }
+
+ /* (non-Javadoc)
+ * @see java.lang.ClassLoader#loadClass(java.lang.String, boolean)
+ */
+ @Override
+ synchronized protected
+ Class<?>
+ loadClass(
+ final String name,
+ final boolean resolve
+ )
+ throws ClassNotFoundException
+ {
+ // First, check if the class has already been loaded
+ Class<?> c = findLoadedClass( name );
+ if ( c == null )
+ {
+ if ( name.startsWith( "java." ) )
+ {
+ return ClassLoader.getSystemClassLoader().loadClass( name );
+ }
+ try
+ {
+ c = findClass( name );
+ } catch (ClassNotFoundException e) {
+ if ( null != parent )
+ {
+ c = parent.loadClass( name );
+ }
+ else
+ {
+ throw new ClassNotFoundException();
+ }
+ }
+ }
+ if ( resolve )
+ {
+ resolveClass( c );
+ }
+ return c;
+ }
+
+ /* (non-Javadoc)
+ * @see java.lang.ClassLoader#findClass(java.lang.String)
+ */
+ @Override
+ protected
+ Class<?>
+ findClass(
+ final String name
+ )
+ throws ClassNotFoundException
+ {
+ logger.trace( "Class name :{}", name );
+ final String path = name.replace( '.', '/' ) + ".class";
+ for ( final ClassSource source : sources )
+ {
+ logger.trace( "Source :{}", source );
+ InputStream in = null;;
+ try
+ {
+ in = source.getResource( path );
+ final Class<?> clazz = define( name, in );
+ if ( null != clazz )
+ {
+ return clazz;
+ }
+ }
+ catch ( final IOException e )
+ {
+ }
+ finally
+ {
+ tryClose( in );
+ }
+ }
+
+// final ClassLoader loader = getClass().getClassLoader();
+//
+// final InputStream in = loader.getResourceAsStream( path );
+// try
+// {
+// final Class<?> clazz = define( name, in );
+// if ( null != clazz )
+// {
+// return clazz;
+// }
+// }
+// finally
+// {
+// tryClose( in );
+// }
+//
+ throw new ClassNotFoundException();
+
+ }
+
+ protected Class<?> define(
+ final String name,
+ final InputStream in
+ )
+ {
+ try {
+ if ( null == in )
+ {
+ return null;
+ }
+ byte[] bytes = getBytes( in );
+ final String qn = name.replace( '.', '/' );
+ bytes = transformer.transform( this, qn, null, null, bytes );
+ logger.trace( "{} bytes read", bytes.length );
+ return defineClass( name, bytes, 0, bytes.length );
+ } catch ( final IOException e )
+ {
+ } catch ( final IllegalClassFormatException e )
+ {
+ }
+
+ return null;
+ }
+
+ /**
+ * Write log file about converted class
+ *
+ * @param path file path to write
+ * @param bytes class contents
+ *
+ * @throws IOException If file can't be write
+ */
+ protected
+ void
+ writeLog(
+ final String path,
+ byte[] bytes
+ )
+ throws IOException
+ {
+ FileOutputStream fileOut = null;
+ try
+ {
+ File logFile = new File( "test/log/" + path );
+ logFile.getParentFile().mkdirs();
+ fileOut = new FileOutputStream( logFile );
+ IOUtil.redirect( new ByteArrayInputStream( bytes ), fileOut );
+ }
+ finally
+ {
+ tryClose( fileOut);
+ }
+ }
+
+}
diff --git a/org.tizen.common/test/src/org/tizen/common/UnsafeRunner.java b/org.tizen.common/test/src/org/tizen/common/UnsafeRunner.java
new file mode 100644
index 000000000..dd17f9ae9
--- /dev/null
+++ b/org.tizen.common/test/src/org/tizen/common/UnsafeRunner.java
@@ -0,0 +1,180 @@
+/*
+ *
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.junit.internal.builders.JUnit4Builder;
+import org.junit.runner.Description;
+import org.junit.runner.Runner;
+import org.junit.runner.notification.RunNotifier;
+import org.junit.runners.ParentRunner;
+import org.junit.runners.model.InitializationError;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * <p>
+ * UnsafeRunner.
+ *
+ * JUnit extensible {@link Runner}
+ * </p>
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ */
+public class
+UnsafeRunner
+extends ParentRunner<Runner>
+{
+ /**
+ * Logger for this instance
+ */
+ protected final Logger logger = LoggerFactory.getLogger( getClass() );
+
+ /**
+ * Classloader to convert test case
+ */
+ protected ClassLoader loader;
+
+ /**
+ * Test case name
+ */
+ protected final String className;
+
+ /**
+ * Constructor with test case {@link Class}
+ *
+ * @param testClass test case {@link Class}
+ *
+ * @throws InitializationError If <code>testClass</code> is invalid test case
+ */
+ public
+ UnsafeRunner(
+ final Class<?> testClass
+ )
+ throws InitializationError
+ {
+ super( testClass );
+ logger.trace( "Class :{}", testClass );
+
+ this.className = testClass.getName();
+
+ ClassSource[] sources = getSources( testClass );
+
+ loader = new UnsafeClassLoader( getClass().getClassLoader(), sources );
+ }
+
+ /**
+ * Extrace {@link ClassSource} from test case's annotation
+ *
+ * @param testClass test case
+ *
+ * @return {@link ClassSource}s
+ */
+ protected
+ ClassSource[] getSources(
+ final Class<?> testClass
+ )
+ {
+ final Location annotation =
+ testClass.getAnnotation( Location.class );
+ if ( null == annotation )
+ {
+ return new ClassSource[0];
+ }
+
+ final String[] locations = annotation.value();
+
+ final ArrayList<ClassSource> sources = new ArrayList<ClassSource>();
+
+ for ( final String location : locations )
+ {
+ if ( location.endsWith( ".jar" ) )
+ {
+ sources.add( new JarSource( location ) );
+ }
+ else if ( location.endsWith( "/" ) )
+ {
+ sources.add( new DirectorySource( location ) );
+ }
+ }
+
+ return sources.toArray( new ClassSource[0] );
+ }
+
+ /* (non-Javadoc)
+ * @see org.junit.runners.ParentRunner#getChildren()
+ */
+ @Override
+ protected
+ List<Runner>
+ getChildren()
+ {
+ final ArrayList<Runner> runners = new ArrayList<Runner>();
+ try {
+ final Class<?> clazz = loader.loadClass( className );
+ logger.trace( "Class :{}, Loader :{}", clazz, clazz.getClassLoader() );
+ final JUnit4Builder builder = new JUnit4Builder();
+ runners.add( builder.runnerForClass( clazz ) );
+ } catch (ClassNotFoundException e) {
+ e.printStackTrace();
+ } catch (Throwable e) {
+ e.printStackTrace();
+ }
+
+ logger.debug( "Runners :{}", runners );
+
+ return runners;
+ }
+
+ /* (non-Javadoc)
+ * @see org.junit.runners.ParentRunner#describeChild(java.lang.Object)
+ */
+ @Override
+ protected
+ Description
+ describeChild(
+ final Runner runner
+ )
+ {
+ return runner.getDescription();
+ }
+
+ /* (non-Javadoc)
+ * @see org.junit.runners.ParentRunner#runChild(java.lang.Object, org.junit.runner.notification.RunNotifier)
+ */
+ @Override
+ protected
+ void
+ runChild(
+ final Runner runner,
+ final RunNotifier notifier
+ )
+ {
+ logger.trace( "Runner :{}", runner );
+ runner.run( notifier );
+ }
+}
diff --git a/org.tizen.common/test/src/org/tizen/common/core/application/MessagesTest.java b/org.tizen.common/test/src/org/tizen/common/core/application/MessagesTest.java
new file mode 100644
index 000000000..85ea2c5e3
--- /dev/null
+++ b/org.tizen.common/test/src/org/tizen/common/core/application/MessagesTest.java
@@ -0,0 +1,58 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* BonYong Lee <bonyong.lee@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+package org.tizen.common.core.application;
+
+import static org.junit.Assert.assertFalse;
+
+import org.junit.Test;
+import org.tizen.common.util.StringUtil;
+
+
+/**
+ * MessagesTest
+ *
+ * Test case for {@link MessagesTest}
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ *
+ * @see MessagesTest
+ */
+public class MessagesTest
+{
+
+ /**
+ * Test {@link Messages}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see {@link Messages}
+ * @see Messages#DIALOG_TITLE
+ */
+ @Test
+ public void test_Messages() throws Exception
+ {
+ assertFalse( StringUtil.isEmpty( Messages.DIALOG_TITLE ) );
+ }
+}
diff --git a/org.tizen.common/test/src/org/tizen/common/core/application/StatusLineMessageManagerTest.java b/org.tizen.common/test/src/org/tizen/common/core/application/StatusLineMessageManagerTest.java
new file mode 100644
index 000000000..24e33743d
--- /dev/null
+++ b/org.tizen.common/test/src/org/tizen/common/core/application/StatusLineMessageManagerTest.java
@@ -0,0 +1,95 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* BonYong Lee <bonyong.lee@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+package org.tizen.common.core.application;
+
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+
+import org.eclipse.jface.action.IStatusLineManager;
+import org.junit.Test;
+
+
+/**
+ * StatusLineMessageManagerTest
+ *
+ * Test case for {@link StatusLineMessageManager}
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ *
+ * @see StatusLineMessageManager
+ */
+public class StatusLineMessageManagerTest
+{
+ /**
+ * Test {@link StatusLineMessageManager#setMessage(String)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see {@link StatusLineMessageManager#setMessage(String)}
+ */
+ @Test
+ public void test_setMessage() throws Exception
+ {
+ final String[] TEST_CASES = new String[] {
+ null, "Hello", "Test"
+ };
+
+ for ( final String TEST_CASE : TEST_CASES )
+ {
+ final IStatusLineManager statusLineManager = mock( IStatusLineManager.class );
+ final StatusLineMessageManager manager =
+ new StatusLineMessageManager( statusLineManager );
+
+ manager.setMessage( TEST_CASE );
+ verify( statusLineManager ).setMessage( TEST_CASE );
+ }
+ }
+
+ /**
+ * Test {@link StatusLineMessageManager#setErrorMessage(String)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see {@link StatusLineMessageManager#setErrorMessage(String)}
+ */
+ @Test
+ public void test_setErrorMessage() throws Exception
+ {
+ final String[] TEST_CASES = new String[] {
+ null, "Hello", "Test"
+ };
+
+ for ( final String TEST_CASE : TEST_CASES )
+ {
+ final IStatusLineManager statusLineManager = mock( IStatusLineManager.class );
+ final StatusLineMessageManager manager =
+ new StatusLineMessageManager( statusLineManager );
+
+ manager.setErrorMessage( TEST_CASE );
+ verify( statusLineManager ).setErrorMessage( TEST_CASE );
+ }
+ }
+
+}
diff --git a/org.tizen.common/test/src/org/tizen/common/core/command/CommandTest.java b/org.tizen.common/test/src/org/tizen/common/core/command/CommandTest.java
new file mode 100755
index 000000000..14d18642e
--- /dev/null
+++ b/org.tizen.common/test/src/org/tizen/common/core/command/CommandTest.java
@@ -0,0 +1,151 @@
+/*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common.core.command;
+
+import org.junit.After;
+import org.junit.Before;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.tizen.common.core.command.policy.PolicyRegistry;
+import org.tizen.common.core.command.prompter.NopPrompter;
+import org.tizen.common.file.VirtualFileHandler;
+
+/**
+ * CommandTest
+ *
+ * Test case for {@link Command}'s sub class
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ */
+public class
+CommandTest
+{
+
+ /**
+ * Logger for testcase
+ */
+ protected final Logger logger = LoggerFactory.getLogger( getClass() );
+ /**
+ * {@link ExecutionContext} for test
+ */
+ protected ExecutionContext context;
+
+ /**
+ * {@link Executor} for test
+ */
+ protected Executor executor;
+
+ /**
+ * Return {@link Prompter} for test
+ *
+ * @return {@link Prompter}
+ */
+ protected
+ Prompter
+ getPrompter()
+ {
+ return context.getPrompter();
+ }
+
+ /**
+ * Return {@link PolicyRegistry} for test
+ *
+ * @return {@link PolicyRegistry}
+ */
+ protected
+ PolicyRegistry
+ getPolicies() {
+ return context.getPolicyRegistry();
+ }
+
+ /**
+ * Return {@link VirtualFileHandler} for test
+ *
+ * @return {@link VirtualFileHandler}
+ */
+ protected
+ VirtualFileHandler
+ getFileHandler()
+ {
+ return (VirtualFileHandler) context.getFileHandler();
+ }
+
+ /**
+ * Return {@link Executor} for test
+ *
+ * @return {@link Executor}
+ */
+ protected
+ Executor
+ getExecutor()
+ {
+ return this.executor;
+ }
+
+ /**
+ * Return {@link ExecutionContext} for test
+ *
+ * @return {@link ExecutionContext}
+ */
+ protected
+ ExecutionContext
+ getExecutionContext()
+ {
+ return this.context;
+ }
+
+ /**
+ * Create prompter for test
+ *
+ * @return {@link Prompter}
+ *
+ * @see NopPrompter
+ */
+ protected
+ Prompter
+ createPrompter()
+ {
+ return new NopPrompter();
+ }
+
+ /**
+ * Set up test
+ */
+ @Before
+ public void setUp()
+ {
+ context = new ExecutionContext( new PolicyRegistry(), createPrompter(), new VirtualFileHandler() );
+ }
+
+ /**
+ * Tear down test
+ */
+ @After
+ public void tearDown()
+ {
+ context = null;
+ }
+
+}
diff --git a/org.tizen.common/test/src/org/tizen/common/core/command/CompositeCommandTest.java b/org.tizen.common/test/src/org/tizen/common/core/command/CompositeCommandTest.java
new file mode 100644
index 000000000..735763a6e
--- /dev/null
+++ b/org.tizen.common/test/src/org/tizen/common/core/command/CompositeCommandTest.java
@@ -0,0 +1,104 @@
+/*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common.core.command;
+
+import static org.junit.Assert.assertEquals;
+
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.junit.Test;
+
+
+/**
+ * CompositeCommandTest
+ *
+ * Test case for {@link CompositeCommand}
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ *
+ * @see CompositeCommandTest
+ */
+public class
+CompositeCommandTest
+extends CommandTest
+{
+ /**
+ * Test {@link CompositeCommand#execute(Executor, ExecutionContext)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see CompositeCommand#execute(Executor, ExecutionContext)
+ */
+ @Test
+ public
+ void
+ test_execute()
+ throws Exception
+ {
+ final AtomicInteger value = new AtomicInteger( 1 );
+ final AbstractCommand<Object> command1 = new AbstractCommand<Object>()
+ {
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.core.command.AbstractCommand#run(org.tizen.common.core.command.Executor, org.tizen.common.core.command.ExecutionContext)
+ */
+ @Override
+ public
+ void
+ run(
+ final Executor executor,
+ final ExecutionContext context
+ )
+ throws Exception
+ {
+ value.set( value.get() + 1 );
+ }
+ };
+ final AbstractCommand<Object> command2 = new AbstractCommand<Object>()
+ {
+
+ /* (non-Javadoc)
+ * @see org.tizen.common.core.command.AbstractCommand#run(org.tizen.common.core.command.Executor, org.tizen.common.core.command.ExecutionContext)
+ */
+ @Override
+ public
+ void
+ run(
+ final Executor executor,
+ final ExecutionContext context
+ )
+ throws Exception
+ {
+ value.set( value.get() * 3 );
+ }
+ };
+
+ final CompositeCommand commands = new CompositeCommand( command1, command2 );
+ commands.run( getExecutor(), getExecutionContext() );
+
+ assertEquals( 6, value.get() );
+ }
+
+}
diff --git a/org.tizen.common/test/src/org/tizen/common/core/command/ExecutionContextTest.java b/org.tizen.common/test/src/org/tizen/common/core/command/ExecutionContextTest.java
new file mode 100644
index 000000000..5be95d52f
--- /dev/null
+++ b/org.tizen.common/test/src/org/tizen/common/core/command/ExecutionContextTest.java
@@ -0,0 +1,100 @@
+/*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common.core.command;
+
+import static org.junit.Assert.assertEquals;
+
+import org.junit.Test;
+import org.tizen.common.core.command.policy.PolicyRegistry;
+import org.tizen.common.core.command.prompter.NopPrompter;
+import org.tizen.common.file.VirtualFileHandler;
+
+
+/**
+ * ExecutionContextTest
+ *
+ * Test case for {@link ExecutionContext}
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ *
+ * @see ExecutionContext
+ */
+public class
+ExecutionContextTest
+{
+ /**
+ * Test {@link ExecutionContext#getPolicyRegistry()}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see ExecutionContext#getPolicyRegistry()
+ */
+ @Test
+ public void test_getPolicyRegistry() throws Exception {
+ // Given
+ final PolicyRegistry registry = new PolicyRegistry();
+ final ExecutionContext context = new ExecutionContext( registry, null, null );
+
+ // When & Then
+ assertEquals( registry, context.getPolicyRegistry() );
+ }
+
+ /**
+ * Test {@link ExecutionContext#getPrompter()}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see ExecutionContext#getPrompter()
+ */
+ @Test
+ public void test_getPrompter() throws Exception {
+ // Given
+ final NopPrompter prompter = new NopPrompter();
+ final ExecutionContext context = new ExecutionContext( null, prompter, null );
+
+ // When & Then
+ assertEquals( prompter, context.getPrompter() );
+
+ }
+
+ /**
+ * Test {@link ExecutionContext#getFileHandler()}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see ExecutionContext#getFileHandler()
+ */
+ @Test
+ public void test_getFileHandler() throws Exception {
+ // Given
+ final VirtualFileHandler handler = new VirtualFileHandler();
+ final ExecutionContext context = new ExecutionContext( null, null, handler );
+
+ // When & Then
+ assertEquals( handler, context.getFileHandler() );
+ }
+
+
+}
diff --git a/org.tizen.common/test/src/org/tizen/common/core/command/file/FileHandlingCommandTest.java b/org.tizen.common/test/src/org/tizen/common/core/command/file/FileHandlingCommandTest.java
new file mode 100644
index 000000000..b1bcb6e21
--- /dev/null
+++ b/org.tizen.common/test/src/org/tizen/common/core/command/file/FileHandlingCommandTest.java
@@ -0,0 +1,103 @@
+/*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common.core.command.file;
+
+import static org.junit.Assert.fail;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+
+import org.junit.Test;
+import org.mockito.Matchers;
+import org.tizen.common.file.Filter;
+import org.tizen.common.file.SimpleFileFilter;
+
+
+/**
+ * FileHandlingCommandTest.
+ *
+ * Test case for {@link FileHandlingCommand}
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ *
+ * @see FileHandlingCommand
+ */
+public class
+FileHandlingCommandTest
+{
+
+ /**
+ * Test {@link FileHandlingCommand#setFilter(SimpleFileFilter)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see FileHandlingCommand#setFilter(SimpleFileFilter)
+ */
+ @Test
+ public
+ void
+ test_setFilter() throws Exception
+ {
+ // Given
+ final FileHandlingCommand<Object> command = new FileHandlingCommand<Object>();
+
+ // When & Then
+ command.setFilter( new SimpleFileFilter() );
+
+ try
+ {
+ // When
+ command.setFilter( null );
+ fail();
+ }
+ catch ( NullPointerException e )
+ {
+ // Then
+ }
+ }
+
+ /**
+ * Test {@link FileHandlingCommand#setIncludes(String[])}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see FileHandlingCommand#setIncludes(String[])
+ */
+ @Test
+ public void test_setIncludes() throws Exception {
+ // Given
+ final FileHandlingCommand<Object> command = new FileHandlingCommand<Object>();
+ SimpleFileFilter mockFilter = mock( SimpleFileFilter.class );
+ command.setFilter( mockFilter );
+
+ // When
+ command.setIncludes( new String[] { "*" } );
+
+ // Then
+ verify( mockFilter ).clearIncludes();
+ verify( mockFilter ).addIncludes( Matchers.<Filter>any() );
+
+ }
+
+}
diff --git a/org.tizen.common/test/src/org/tizen/common/core/command/policy/PolicyRegistryTest.java b/org.tizen.common/test/src/org/tizen/common/core/command/policy/PolicyRegistryTest.java
new file mode 100644
index 000000000..b6f88ea02
--- /dev/null
+++ b/org.tizen.common/test/src/org/tizen/common/core/command/policy/PolicyRegistryTest.java
@@ -0,0 +1,72 @@
+/*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common.core.command.policy;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
+import org.junit.Test;
+
+
+/**
+ * PolicyRegistryTest
+ *
+ * Test case for {@link PolicyRegistry}
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ *
+ * @see PolicyRegistry
+ */
+public class PolicyRegistryTest
+{
+
+ /**
+ * Test {@link PolicyRegistry#getPolicy(String)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see PolicyRegistry#getPolicy(String)
+ */
+ @Test
+ public void test_getPolicy() throws Exception {
+ final PolicyRegistry register = new PolicyRegistry();
+
+ final AbstractPolicy expected = new AbstractPolicy( "exist.output.file" ) {
+ public <T> T adapt(Class<T> clazz) {
+ return null;
+ }
+ };
+
+ register.register( expected );
+
+ assertNotNull( register.getPolicy( null ) );
+ assertNotNull( register.getPolicy( "" ) );
+ assertEquals( null, register.getPolicy( "exist" ) );
+ assertEquals( null, register.getPolicy( "exist.output" ) );
+ assertEquals( expected, register.getPolicy( "exist.output.file.xml" ) );
+ assertEquals( expected, register.getPolicy( "exist.output.file" ) );
+ }
+
+}
diff --git a/org.tizen.common/test/src/org/tizen/common/core/command/prompter/GenericOptionTest.java b/org.tizen.common/test/src/org/tizen/common/core/command/prompter/GenericOptionTest.java
new file mode 100644
index 000000000..4094c3ef2
--- /dev/null
+++ b/org.tizen.common/test/src/org/tizen/common/core/command/prompter/GenericOptionTest.java
@@ -0,0 +1,98 @@
+/*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common.core.command.prompter;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import org.junit.Test;
+
+
+/**
+ * <p>
+ * GenericOptionTest.
+ *
+ * Test case for {@link GenericOption}
+ * </p>
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ *
+ * @see GenericOption
+ */
+public class
+GenericOptionTest
+{
+ /**
+ * Test {@link GenericOption#isMatch(String)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see GenericOption#isMatch(String)
+ */
+ @Test
+ public
+ void
+ test_isMatch()
+ throws Exception
+ {
+
+ final GenericOption option = new GenericOption();
+
+ assertTrue( option.isMatch( "Hello" ) );
+ assertTrue( option.isMatch( "World" ) );
+
+
+ }
+
+ /**
+ * Test {@link GenericOption#getAnswer()}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see GenericOption#getAnswer()
+ */
+ @Test
+ public
+ void
+ test_getAnswer()
+ throws Exception
+ {
+ final String userAnser = "Dummy answer";
+ NopPrompter prompter = new NopPrompter() {
+ @Override
+ public Option interact(String question, Option... options) {
+ options[0].isMatch( userAnser );
+ return options[0];
+ }
+ };
+ GenericOption option = new GenericOption();
+ final Option answer = prompter.interact( "Answer ?", option );
+
+ assertEquals( userAnser, ((GenericOption) answer).getAnswer() );
+ assertEquals( userAnser, answer.toString() );
+
+ }
+
+}
diff --git a/org.tizen.common/test/src/org/tizen/common/core/command/prompter/OptionTest.java b/org.tizen.common/test/src/org/tizen/common/core/command/prompter/OptionTest.java
new file mode 100644
index 000000000..beb2027a1
--- /dev/null
+++ b/org.tizen.common/test/src/org/tizen/common/core/command/prompter/OptionTest.java
@@ -0,0 +1,91 @@
+/*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common.core.command.prompter;
+
+import static org.junit.Assert.assertEquals;
+
+import org.junit.Test;
+
+
+/**
+ * OptionTest
+ *
+ * Test case for {@link ChoiceOption}
+ *
+ * @author bylee
+ *
+ * @see ChoiceOption
+ */
+public class
+OptionTest
+{
+ /**
+ * Test {@link ChoiceOption#isMatch(String)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see ChoiceOption#isMatch(String)
+ */
+ @Test
+ public
+ void
+ test_isMatch()
+ throws Exception
+ {
+ // Test cases
+ final Object[][] TEST_CASES = new Object[][] {
+ new Object[] {
+ new ChoiceOption( "test" ),
+ new Object[][] {
+ new Object[] { "t", true },
+ new Object[] { "TEST", true },
+ new Object[] { "TEst", true },
+ new Object[] { "No", false },
+ new Object[] { null, false }
+ }
+ }
+ };
+ // Given
+
+ for ( final Object[] TEST_CASE : TEST_CASES )
+ {
+
+ final ChoiceOption option = (ChoiceOption) TEST_CASE[0];
+ final Object[][] TEST_CASE2 = (Object[][]) TEST_CASE[1];
+ for ( final Object[] TEST_CASE3 : TEST_CASE2 )
+ {
+ // When
+ String input = (String) TEST_CASE3[0];
+ boolean expected = (Boolean) TEST_CASE3[1];
+
+ boolean result = option.isMatch( input );
+
+ // Then
+ assertEquals( expected, result );
+ }
+ }
+ }
+
+}
diff --git a/org.tizen.common/test/src/org/tizen/common/core/command/prompter/SWTPrompterTest.java b/org.tizen.common/test/src/org/tizen/common/core/command/prompter/SWTPrompterTest.java
new file mode 100644
index 000000000..f222f83f2
--- /dev/null
+++ b/org.tizen.common/test/src/org/tizen/common/core/command/prompter/SWTPrompterTest.java
@@ -0,0 +1,109 @@
+/*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common.core.command.prompter;
+
+import static org.junit.Assert.assertEquals;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import org.eclipse.jface.dialogs.Dialog;
+import org.eclipse.jface.dialogs.MessageDialog;
+import org.junit.Test;
+
+
+/**
+ * SWTPrompterTest
+ *
+ * Test case for {@link SWTPrompter}
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ *
+ * @see SWTPrompter
+ */
+public class
+SWTPrompterTest
+{
+ /**
+ * Test {@link SWTPrompter#interact(String, ChoiceOption...)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see SWTPrompter#interact(String, ChoiceOption...)
+ */
+ @Test
+ public void test_interact() throws Exception {
+ {
+ // Given
+ final MessageDialog mockDialog = mock( MessageDialog.class );
+ when( mockDialog.getReturnCode() ).thenReturn( 0 );
+ final SWTPrompter prompter = new SWTPrompter() {
+ @Override
+ protected Dialog createDialog(
+ final String question,
+ final String[] optionNames,
+ final int defaultOptionIndex
+ )
+ {
+ return mockDialog;
+ }
+ };
+
+ // When
+ ChoiceOption opt1 = new ChoiceOption( "Yes" );
+ ChoiceOption opt2 = new ChoiceOption( "No", true );
+
+ // Then
+ Option result = prompter.interact( "Yes or No", opt1, opt2 );
+ assertEquals( opt1, result );
+ }
+
+ {
+ // Given
+ final MessageDialog mockDialog = mock( MessageDialog.class );
+ when( mockDialog.getReturnCode() ).thenReturn( 1 );
+ final SWTPrompter prompter = new SWTPrompter() {
+ @Override
+ protected Dialog createDialog(
+ final String question,
+ final String[] optionNames,
+ final int defaultOptionIndex
+ )
+ {
+ return mockDialog;
+ }
+ };
+
+ // When
+ ChoiceOption opt1 = new ChoiceOption( "Yes" );
+ ChoiceOption opt2 = new ChoiceOption( "No", true );
+
+ // Then
+ Option result = prompter.interact( "Yes or No", opt1, opt2 );
+ assertEquals( opt2, result );
+
+ }
+ }
+
+}
diff --git a/org.tizen.common/test/src/org/tizen/common/core/command/sdb/DevicesSdbCommandTest.java b/org.tizen.common/test/src/org/tizen/common/core/command/sdb/DevicesSdbCommandTest.java
new file mode 100644
index 000000000..205e8b0dd
--- /dev/null
+++ b/org.tizen.common/test/src/org/tizen/common/core/command/sdb/DevicesSdbCommandTest.java
@@ -0,0 +1,68 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* GyeongSeok Seo <gyeongseok.seo@samsung.com>
+* BonYong Lee <bonyong.lee@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+package org.tizen.common.core.command.sdb;
+
+import static org.junit.Assert.assertEquals;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import org.junit.Test;
+import org.tizen.common.core.command.CommandTest;
+import org.tizen.sdblib.IDevice;
+
+/**
+ * DevicesSdbCommandTest
+ *
+ * Test case for {@link DevicesSdbCommand}
+ *
+ * @author GyeongSeok Seo{@literal <gyeongseok.seo@samsung.com>} (S-Core)
+ *
+ * @see DevicesSdbCommand
+ */
+public class
+DevicesSdbCommandTest
+extends CommandTest
+{
+ @Test
+ public void test_execute() throws Exception {
+ DevicesSdbCommand testCommand = new DevicesSdbCommand() {
+ @Override
+ protected SmartDevelopmentBridgeManager createBridge() {
+ SmartDevelopmentBridgeManager mockBridge = mock( SmartDevelopmentBridgeManager.class );
+ IDevice mockDevice1 = mock( IDevice.class );
+ IDevice mockDevice2 = mock( IDevice.class );
+ when( mockDevice1.toString() ).thenReturn( "TizenDevice1" );
+ when( mockDevice2.toString() ).thenReturn( "TizenDevice2" );
+ when( mockBridge.getDevices() ).thenReturn( new IDevice[] { mockDevice1, mockDevice2 } );
+ return mockBridge;
+ }
+
+ };
+ testCommand.run( null, context );
+ String result = "TizenDevice1" + System.getProperty("line.separator") + "TizenDevice2" + System.getProperty("line.separator");
+ assertEquals( result, testCommand.getResult() );
+ }
+}
diff --git a/org.tizen.common/test/src/org/tizen/common/core/command/sdb/DlogSdbCommandTest.java b/org.tizen.common/test/src/org/tizen/common/core/command/sdb/DlogSdbCommandTest.java
new file mode 100644
index 000000000..b8dcbe177
--- /dev/null
+++ b/org.tizen.common/test/src/org/tizen/common/core/command/sdb/DlogSdbCommandTest.java
@@ -0,0 +1,82 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* GyeongSeok Seo <gyeongseok.seo@samsung.com>
+* BonYong Lee <bonyong.lee@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+package org.tizen.common.core.command.sdb;
+
+import static org.junit.Assert.*;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+
+import org.junit.Test;
+import org.tizen.common.core.command.CommandTest;
+import org.tizen.sdblib.IDevice;
+import org.tizen.sdblib.MultiLineReceiver;
+
+/**
+ * DlogSdbCommandTest
+ *
+ * Test case for {@link DlogSdbCommand}
+ *
+ * @author GyeongSeok Seo{@literal <gyeongseok.seo@samsung.com>} (S-Core)
+ *
+ * @see DlogSdbCommand
+ */
+public class
+DlogSdbCommandTest
+extends CommandTest
+{
+ @Test
+ public void test_execute() throws Exception {
+ final MultiLineReceiver mockMultiLineReceiver = mock( MultiLineReceiver.class );
+ String cmd = "dlogutil";
+ DlogSdbCommand testCommand = new DlogSdbCommand() {
+ @Override
+ public MultiLineReceiver createMultiLineReceiver() {
+ return mockMultiLineReceiver;
+ }
+ };
+
+ try {
+ testCommand.run( null, context );
+ fail( "when device is null then must throw exception" );
+ } catch ( Exception e) {
+ }
+
+ IDevice mockDevice = mock( IDevice.class );
+ testCommand.setDevice( mockDevice );
+ try {
+ testCommand.run( null, context );
+ assertEquals( testCommand.getCommand(), cmd );
+ verify( mockDevice ).executeShellCommand( cmd, mockMultiLineReceiver );
+
+ testCommand.setFilter( "filter" );
+ testCommand.run( null, context );
+ assertEquals( testCommand.getCommand(), cmd + " filter" );
+ verify( mockDevice ).executeShellCommand( cmd + " filter", mockMultiLineReceiver );
+ } catch (Exception e) {
+ fail( "should't throw exception" );
+ }
+ }
+}
diff --git a/org.tizen.common/test/src/org/tizen/common/core/command/sdb/ForwardSdbCommandTest.java b/org.tizen.common/test/src/org/tizen/common/core/command/sdb/ForwardSdbCommandTest.java
new file mode 100644
index 000000000..30ba8d2eb
--- /dev/null
+++ b/org.tizen.common/test/src/org/tizen/common/core/command/sdb/ForwardSdbCommandTest.java
@@ -0,0 +1,94 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* GyeongSeok Seo <gyeongseok.seo@samsung.com>
+* BonYong Lee <bonyong.lee@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+package org.tizen.common.core.command.sdb;
+
+import static org.junit.Assert.*;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+
+import org.junit.Test;
+import org.tizen.common.core.command.CommandTest;
+import org.tizen.sdblib.IDevice;
+
+/**
+ * ForwardSdbCommandTest
+ *
+ * Test case for {@link ForwardSdbCommand}
+ *
+ * @author GyeongSeok Seo{@literal <gyeongseok.seo@samsung.com>} (S-Core)
+ *
+ * @see ForwardSdbCommand
+ */
+public class
+ForwardSdbCommandTest
+extends CommandTest
+{
+ @Test
+ public void test_execute() throws Exception {
+ int localPort = 5000;
+ int remotePort = 4000;
+ ForwardSdbCommand testCommand = new ForwardSdbCommand(localPort, remotePort);
+
+ // device null test
+ try {
+ testCommand.run( null, context );
+ fail( "when device is null then must throw exception" );
+ } catch (Exception e) {
+ }
+
+ try {
+ IDevice mockDevice = mock( IDevice.class );
+ testCommand.setDevice( mockDevice );
+ testCommand.run( null, context );
+ verify( mockDevice ).createForward( localPort, remotePort );
+ } catch (Exception e) {
+ fail( "should't throw exception" );
+ }
+ }
+
+ @Test
+ public void test_undo() throws Exception {
+ int localPort = 5000;
+ int remotePort = 4000;
+ ForwardSdbCommand testCommand = new ForwardSdbCommand(localPort, remotePort);
+
+ // device null test
+ try {
+ testCommand.undo( null, context );
+ fail( "when device is null then must throw exception" );
+ } catch (Exception e) {
+ }
+
+ try {
+ IDevice mockDevice = mock( IDevice.class );
+ testCommand.setDevice( mockDevice );
+ testCommand.undo( null, context );
+ verify( mockDevice ).removeForward( localPort, remotePort );
+ } catch (Exception e) {
+ fail( "should't throw exception" );
+ }
+ }
+}
diff --git a/org.tizen.common/test/src/org/tizen/common/core/command/sdb/PullSdbCommandTest.java b/org.tizen.common/test/src/org/tizen/common/core/command/sdb/PullSdbCommandTest.java
new file mode 100644
index 000000000..7da5260d6
--- /dev/null
+++ b/org.tizen.common/test/src/org/tizen/common/core/command/sdb/PullSdbCommandTest.java
@@ -0,0 +1,83 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* GyeongSeok Seo <gyeongseok.seo@samsung.com>
+* BonYong Lee <bonyong.lee@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+package org.tizen.common.core.command.sdb;
+
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import java.io.IOException;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.tizen.common.Location;
+import org.tizen.common.UnsafeRunner;
+import org.tizen.common.core.command.CommandTest;
+import org.tizen.sdblib.IDevice;
+import org.tizen.sdblib.SdbCommandRejectedException;
+import org.tizen.sdblib.SyncService;
+import org.tizen.sdblib.SyncService.SyncResult;
+import org.tizen.sdblib.TimeoutException;
+
+/**
+ * PullSdbCommandTest
+ *
+ * Test case for {@link PullSdbCommand}
+ *
+ * @author GyeongSeok Seo{@literal <gyeongseok.seo@samsung.com>} (S-Core)
+ *
+ * @see PullSdbCommand
+ */
+@RunWith( UnsafeRunner.class )
+@Location( { "lib/sdblib.jar", "bin/" } )
+public class
+PullSdbCommandTest
+extends CommandTest
+{
+ @Test
+ public void test_execute() throws Exception {
+ final IDevice mockDevice = mock( IDevice.class );
+ final SyncService mockService = mock( SyncService.class );
+ SyncResult r = mock( SyncResult.class );
+ when( mockService.pullFile( "remotePath", "localPath", SyncService.getNullProgressMonitor() ) )
+ .thenReturn( r );
+
+ PullSdbCommand testCommand = new PullSdbCommand( "remotePath", "localPath" )
+ {
+ @Override
+ protected SyncService getSyncService() throws TimeoutException,
+ SdbCommandRejectedException, IOException {
+ return mockService;
+ }
+ };
+ testCommand.setDevice( mockDevice );
+ testCommand.run( null, context );
+ }
+
+ @Override
+ public String toString() {
+ return getClass().getSimpleName() + ":" + getClass().getClassLoader();
+ }
+}
diff --git a/org.tizen.common/test/src/org/tizen/common/core/command/sdb/PushSdbCommandTest.java b/org.tizen.common/test/src/org/tizen/common/core/command/sdb/PushSdbCommandTest.java
new file mode 100644
index 000000000..f37820f69
--- /dev/null
+++ b/org.tizen.common/test/src/org/tizen/common/core/command/sdb/PushSdbCommandTest.java
@@ -0,0 +1,71 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* GyeongSeok Seo <gyeongseok.seo@samsung.com>
+* BonYong Lee <bonyong.lee@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+package org.tizen.common.core.command.sdb;
+
+import static org.mockito.Mockito.mock;
+
+import java.io.IOException;
+import java.lang.reflect.Constructor;
+
+import org.junit.Test;
+import org.tizen.common.core.command.CommandTest;
+import org.tizen.sdblib.IDevice;
+import org.tizen.sdblib.SdbCommandRejectedException;
+import org.tizen.sdblib.SyncService;
+import org.tizen.sdblib.TimeoutException;
+
+/**
+ * PushSdbCommandTest
+ *
+ * Test case for {@link PushSdbCommand}
+ *
+ * @author GyeongSeok Seo{@literal <gyeongseok.seo@samsung.com>} (S-Core)
+ *
+ * @see PushSdbCommand
+ */
+public class
+PushSdbCommandTest
+extends CommandTest
+{
+ @Test
+ public void test_execute() throws Exception {
+ IDevice mockDevice = mock( IDevice.class );
+ Class<?> serviceClass = SyncService.class;
+ Constructor<?>[] con = serviceClass.getDeclaredConstructors();
+ con[0].setAccessible( true );
+ final SyncService mockService = (SyncService) con[0].newInstance( null, null );
+
+ PushSdbCommand testCommand = new PushSdbCommand( "sourcePath", "targetPath" ) {
+ @Override
+ protected SyncService getSyncService() throws TimeoutException,
+ SdbCommandRejectedException, IOException {
+ return mockService;
+ }
+ };
+ testCommand.setDevice( mockDevice );
+ testCommand.run( null, context );
+ }
+}
diff --git a/org.tizen.common/test/src/org/tizen/common/core/command/sdb/ShellSdbCommandTest.java b/org.tizen.common/test/src/org/tizen/common/core/command/sdb/ShellSdbCommandTest.java
new file mode 100644
index 000000000..db7265358
--- /dev/null
+++ b/org.tizen.common/test/src/org/tizen/common/core/command/sdb/ShellSdbCommandTest.java
@@ -0,0 +1,111 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* GyeongSeok Seo <gyeongseok.seo@samsung.com>
+* BonYong Lee <bonyong.lee@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+package org.tizen.common.core.command.sdb;
+
+import static org.junit.Assert.*;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+
+import org.junit.Test;
+import org.tizen.common.core.command.CommandTest;
+import org.tizen.sdblib.IDevice;
+import org.tizen.sdblib.MultiLineReceiver;
+
+/**
+ * ShellSdbCommandTest
+ *
+ * Test case for {@link ShellSdbCommand}
+ *
+ * @author GyeongSeok Seo{@literal <gyeongseok.seo@samsung.com>} (S-Core)
+ *
+ * @see ShellSdbCommand
+ */
+
+public class
+ShellSdbCommandTest
+extends CommandTest
+{
+ @Test
+ public void test_execute() throws Exception {
+ String cmd = "ls";
+ final MultiLineReceiver mockMultiLineReceiver = mock( MultiLineReceiver.class );
+ ShellSdbCommand testCommand1 = new ShellSdbCommand();
+ ShellSdbCommand testCommand2 = new ShellSdbCommand( cmd ) {
+ @Override
+ public MultiLineReceiver createMultiLineReceiver() {
+ return mockMultiLineReceiver;
+ }
+
+ };
+
+ // construction test
+ assertEquals( testCommand1.getCommand(), null );
+ assertEquals( testCommand2.getCommand(), cmd);
+
+ // time value test
+ assertEquals( testCommand1.getTime(), 90 );
+ testCommand1.setTime( 30 );
+ assertEquals( testCommand1.getTime(), 30 );
+ testCommand1.setTime( 1 );
+ assertEquals( testCommand1.getTime(), 1 );
+ testCommand1.setTime( 0 );
+ assertEquals( testCommand1.getTime(), 90 );
+ testCommand1.setTime( -1 );
+ assertEquals( testCommand1.getTime(), 90 );
+
+ try {
+ // device null test
+ testCommand1.run( null, context );
+ fail( "when device is null then must throw exception" );
+ } catch (Exception e) {
+ }
+
+ IDevice mockDevice = mock( IDevice.class );
+ testCommand1.setDevice( mockDevice );
+ testCommand2.setDevice( mockDevice );
+ try {
+ // command null test
+ testCommand1.run( null, context );
+ fail( "when command is null then must throw exception" );
+ } catch (Exception e) {
+ }
+
+ try {
+ // normal operation test
+ String clearResult = "Test clearResult call";
+ testCommand2.setResult( clearResult );
+ testCommand2.run( null, context );
+
+ // clearResult call test
+ assertNotSame( clearResult, testCommand2.getResult() );
+ // executeShellCommand call test
+ verify( mockDevice ).executeShellCommand( cmd, mockMultiLineReceiver, 90000 );
+ } catch (Exception e) {
+ fail( "should't throw exception" );
+ }
+ }
+
+}
diff --git a/org.tizen.common/test/src/org/tizen/common/core/command/zip/ZipCommandTest.java b/org.tizen.common/test/src/org/tizen/common/core/command/zip/ZipCommandTest.java
new file mode 100644
index 000000000..a325eda29
--- /dev/null
+++ b/org.tizen.common/test/src/org/tizen/common/core/command/zip/ZipCommandTest.java
@@ -0,0 +1,79 @@
+/*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common.core.command.zip;
+
+import static org.junit.Assert.assertTrue;
+import static org.tizen.common.util.ArrayUtil.size;
+import static org.tizen.common.util.IOUtil.getBytes;
+
+import java.io.InputStream;
+
+import org.junit.Test;
+import org.tizen.common.core.command.CommandTest;
+import org.tizen.common.core.command.ExecutionContext;
+import org.tizen.common.core.command.Executor;
+import org.tizen.common.file.FileHandler.Attribute;
+import org.tizen.common.file.VirtualFileHandler;
+
+
+/**
+ * ZipCommandTest
+ *
+ * Test case for {@link ZipCommand}
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ *
+ * @see ZipCommand
+ */
+public class
+ZipCommandTest
+extends CommandTest
+{
+ /**
+ * Test {@link ZipCommand#execute(Executor, ExecutionContext)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see ZipCommand#execute(Executor, ExecutionContext)
+ */
+ @Test
+ public void test_execute() throws Exception {
+ // Given
+ final VirtualFileHandler vfs = (VirtualFileHandler) context.getFileHandler();
+ vfs.makeDirectory( "/test" );
+ vfs.write( "/test/a.txt", "Hello, World" );
+
+ // When
+ final ZipCommand command = new ZipCommand( "/test", "/test.zip" );
+ command.run( getExecutor(), getExecutionContext() );
+
+ // Then
+ assertTrue( (Boolean) vfs.get( "/test.zip", Attribute.EXISTS ) );
+ final InputStream in = vfs.read( "/test.zip" );
+ assertTrue( 0 < size( getBytes( in, true ) ) );
+
+ }
+
+}
diff --git a/org.tizen.common/test/src/org/tizen/common/file/SimpleFileFilterTest.java b/org.tizen.common/test/src/org/tizen/common/file/SimpleFileFilterTest.java
new file mode 100755
index 000000000..cb61e5ce2
--- /dev/null
+++ b/org.tizen.common/test/src/org/tizen/common/file/SimpleFileFilterTest.java
@@ -0,0 +1,90 @@
+/*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common.file;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import org.junit.Test;
+import org.tizen.common.file.filter.WildCardFilter;
+
+
+/**
+ * <p>
+ * SimpleFileFilterTest.
+ *
+ * Test case for {@link SimpleFileFilter}
+ * </p>
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ *
+ * @see SimpleFileFilter
+ */
+public class
+SimpleFileFilterTest
+{
+ /**
+ * Test {@link SimpleFileFilter#accept(String, String)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see SimpleFileFilter#accept(String, String)
+ */
+ @Test
+ public
+ void
+ test_accept()
+ throws Exception
+ {
+ SimpleFileFilter filter = new SimpleFileFilter();
+ filter.addIncludes( new WildCardFilter( "Test*" ) );
+ assertTrue( filter.accept( null, "/test/Test.txt" ) );
+ assertFalse( filter.accept( null, "/test/Te.txt" ) );
+
+ filter.addExcludes( new WildCardFilter( "T*" ) );
+ assertFalse( filter.accept( null, "/test/Test.txt" ) );
+
+ try
+ {
+ filter.accept( null, "xxx.txt" );
+ fail();
+ } catch ( final Exception e )
+ {
+ }
+
+ filter.clearIncludes();
+ filter.setExcludes( new WildCardFilter( ".*" ), new WildCardFilter( "*~" ) );
+ assertTrue( filter.accept( null, "a.a.a." ) );
+ assertFalse( filter.accept( null, ".aaa." ) );
+ assertTrue( filter.accept( null, "~a~a~a~." ) );
+ assertFalse( filter.accept( null, "~a~a~a~" ) );
+ assertFalse( filter.accept( null, ".project" ) );
+ assertFalse( filter.accept( null, ".classpath" ) );
+ assertFalse( filter.accept( null, "viclone.txt~" ) );
+
+ }
+
+}
diff --git a/org.tizen.common/test/src/org/tizen/common/file/VirtualFileHandlerTest.java b/org.tizen.common/test/src/org/tizen/common/file/VirtualFileHandlerTest.java
new file mode 100644
index 000000000..d61fd69f6
--- /dev/null
+++ b/org.tizen.common/test/src/org/tizen/common/file/VirtualFileHandlerTest.java
@@ -0,0 +1,71 @@
+/*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common.file;
+
+import static org.junit.Assert.assertTrue;
+import static org.tizen.common.util.ArrayUtil.size;
+import static org.tizen.common.util.IOUtil.getBytes;
+
+import org.junit.Test;
+
+
+/**
+ * <p>
+ * VirtualFileHandlerTest.
+ *
+ * Test case for {@link VirtualFileHandler}
+ *
+ * </p>
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ *
+ * @see VirtualFileHandler
+ */
+public class
+VirtualFileHandlerTest
+{
+ /**
+ * Test {@link VirtualFileHandler#write(String, String)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see VirtualFileHandler#write(String, String)
+ */
+ @Test
+ public
+ void
+ test_write()
+ throws Exception
+ {
+ final VirtualFileHandler vfs = new VirtualFileHandler();
+
+ vfs.makeDirectory( "/test" );
+
+ vfs.write( "/test/a.txt", "Hello, World" );
+
+ assertTrue( 0 < size( getBytes( vfs.read( "/test/a.txt" ) ) ) );
+ }
+
+}
diff --git a/org.tizen.common/test/src/org/tizen/common/file/filter/WildCardFilterFactoryTest.java b/org.tizen.common/test/src/org/tizen/common/file/filter/WildCardFilterFactoryTest.java
new file mode 100644
index 000000000..0bb5f3b67
--- /dev/null
+++ b/org.tizen.common/test/src/org/tizen/common/file/filter/WildCardFilterFactoryTest.java
@@ -0,0 +1,81 @@
+/*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common.file.filter;
+
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.fail;
+
+import org.junit.Test;
+
+
+/**
+ * <p>
+ * WildCardFilterFactoryTest.
+ *
+ * Test case for {@link WildCardFilterFactory}
+ *
+ * </p>
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ *
+ * @see WildCardFilterFactory
+ */
+public class
+WildCardFilterFactoryTest
+{
+
+ /**
+ * Test {@link WildCardFilterFactory#create(String)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see WildCardFilterFactory#create(String)
+ */
+ @Test
+ public
+ void
+ test_create()
+ throws Exception
+ {
+ final WildCardFilterFactory factory = new WildCardFilterFactory();
+
+ assertNotNull( factory.create( "*" ) );
+ assertNotNull( factory.create( "**" ) );
+ assertNotNull( factory.create( "?" ) );
+ assertNotNull( factory.create( "Test" ) );
+ assertNotNull( factory.create( "" ) );
+ try
+ {
+ factory.create( null );
+ fail();
+ }
+ catch ( NullPointerException e )
+ {
+ }
+
+
+ }
+
+}
diff --git a/org.tizen.common/test/src/org/tizen/common/file/filter/WildCardFilterTest.java b/org.tizen.common/test/src/org/tizen/common/file/filter/WildCardFilterTest.java
new file mode 100644
index 000000000..b5477a22d
--- /dev/null
+++ b/org.tizen.common/test/src/org/tizen/common/file/filter/WildCardFilterTest.java
@@ -0,0 +1,89 @@
+/*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common.file.filter;
+
+import static org.junit.Assert.assertEquals;
+
+import org.junit.Test;
+
+
+/**
+ * <p>
+ * WildCardFilterTest.
+ *
+ * Test case for {@link WildCardFilter}
+ *
+ * </p>
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ *
+ * @see WildCardFilter
+ */
+public class
+WildCardFilterTest
+{
+ /**
+ * Test {@link WildCardFilter#accept(String, String)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see WildCardFilter#accept(String, String)
+ */
+ @Test
+ public void
+ test_accept()
+ throws Exception
+ {
+ final Object[][] TEST_CASES = new Object[][] {
+ new Object[] { "aaa*", "aaaa/abc.text", false },
+ new Object[] { "aaa*", "aaaa/aaa.text", true },
+ new Object[] { "aaa*", "aaaa/aaa33.text", true },
+ new Object[] { "aaa*", "aaaa/aa", false },
+ new Object[] { ".*", ".text", true },
+ new Object[] { "*Test*", "A_Test", true },
+ };
+
+
+ int iCase = 0;
+ for ( final Object[] TEST_CASE : TEST_CASES )
+ {
+ ++iCase;
+
+ final String pattern = (String) TEST_CASE[0];
+ final String path = (String) TEST_CASE[1];
+ final boolean expected = (Boolean) TEST_CASE[2];
+
+ // Given
+
+ // When
+ final WildCardFilter filter = new WildCardFilter();
+ filter.setPattern( pattern );
+
+ // Then
+ assertEquals( expected, filter.accept( "/", path ) );
+
+ }
+ }
+}
diff --git a/org.tizen.common/test/src/org/tizen/common/ui/page/preference/MessagesTest.java b/org.tizen.common/test/src/org/tizen/common/ui/page/preference/MessagesTest.java
new file mode 100644
index 000000000..7b56ab266
--- /dev/null
+++ b/org.tizen.common/test/src/org/tizen/common/ui/page/preference/MessagesTest.java
@@ -0,0 +1,66 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* BonYong Lee <bonyong.lee@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+package org.tizen.common.ui.page.preference;
+
+import static org.junit.Assert.assertFalse;
+
+import org.junit.Test;
+import org.tizen.common.util.StringUtil;
+
+
+/**
+ * MessagesTest
+ *
+ * Test case for {@link MessagesTest}
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ *
+ * @see MessagesTest
+ */
+public class MessagesTest
+{
+ /**
+ * Test {@link Messages}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see {@link Messages}
+ * @see Messages#DESCRIPTION
+ * @see Messages#GROUP1
+ * @see Messages#GROUP2
+ * @see Messages#LABEL_LOCATION
+ * @see Messages#LABEL_UPDATE
+ */
+ @Test
+ public void test_Messages() throws Exception
+ {
+ assertFalse( StringUtil.isEmpty( Messages.DESCRIPTION ) );
+ assertFalse( StringUtil.isEmpty( Messages.GROUP1 ) );
+ assertFalse( StringUtil.isEmpty( Messages.GROUP2 ) );
+ assertFalse( StringUtil.isEmpty( Messages.LABEL_LOCATION ) );
+ assertFalse( StringUtil.isEmpty( Messages.LABEL_UPDATE ) );
+ }
+
+}
diff --git a/org.tizen.common/test/src/org/tizen/common/ui/page/wizard/TrayWizardPageTest.java b/org.tizen.common/test/src/org/tizen/common/ui/page/wizard/TrayWizardPageTest.java
new file mode 100644
index 000000000..15a560945
--- /dev/null
+++ b/org.tizen.common/test/src/org/tizen/common/ui/page/wizard/TrayWizardPageTest.java
@@ -0,0 +1,91 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* BonYong Lee <bonyong.lee@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+package org.tizen.common.ui.page.wizard;
+
+import static org.junit.Assert.assertEquals;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import org.eclipse.jface.wizard.IWizard;
+import org.eclipse.jface.wizard.WizardDialog;
+import org.eclipse.swt.widgets.Composite;
+import org.junit.Test;
+import org.tizen.common.ui.dialog.ClosableTray;
+
+
+/**
+ * TrayWizardPageTest
+ *
+ * Test case for {@link TrayWizardPage}
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ *
+ * @see TrayWizardPage
+ */
+public class
+TrayWizardPageTest
+{
+ public void test_TrayWizardPage() throws Exception
+ {
+ assertEquals( "Test Page", (new TrayWizardPage( "Test Page" ) {
+ public void createControl(Composite parent)
+ {
+ }
+ }).getName() );
+
+ assertEquals( "Title", (new TrayWizardPage( "Test Page", "Title", null ) {
+ public void createControl(Composite parent)
+ {
+ }
+ }).getTitle() );
+ }
+ @Test
+ public
+ void
+ test_openClosableTray()
+ throws Exception
+ {
+ final TrayWizardPage page = new TrayWizardPage( "Test Page" )
+ {
+ public void createControl(Composite parent)
+ {
+ }
+ };
+
+ /*
+ * This means that functional is successful If run on WizardDialog
+ */
+ final IWizard wizard = mock( IWizard.class );
+ final WizardDialog dialog = mock( WizardDialog.class );
+ when( wizard.getContainer() ).thenReturn( dialog );
+ final ClosableTray tray = mock( ClosableTray.class );
+
+ page.setWizard( wizard );
+ page.openClosableTray( tray );
+
+ verify( dialog ).openTray( tray );
+ }
+}
diff --git a/org.tizen.common/test/src/org/tizen/common/util/ArrayUtilTest.java b/org.tizen.common/test/src/org/tizen/common/util/ArrayUtilTest.java
new file mode 100755
index 000000000..863a1b7f7
--- /dev/null
+++ b/org.tizen.common/test/src/org/tizen/common/util/ArrayUtilTest.java
@@ -0,0 +1,765 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* BonYong Lee <bonyong.lee@samsung.com>
+* Gun Kim <gune.kim@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+package org.tizen.common.util;
+
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+import static org.tizen.common.util.ArrayUtil.safe;
+
+import java.lang.reflect.InvocationTargetException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.ConcurrentModificationException;
+import java.util.Iterator;
+
+import org.junit.Test;
+
+
+/**
+ * ArrayUtilsTest
+ *
+ * Test case for {@link ArrayUtil}
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ *
+ * @see ArrayUtil
+ */
+public class ArrayUtilTest
+{
+ public static int arrayIndex = 0;
+ public static boolean successTest = true;
+
+ /**
+ * Test {@link ArrayUtil#pickupFirst(Collection)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see ArrayUtil#pickupFirst(Collection)
+ */
+ @Test
+ public void
+ test_pickupFirst()
+ throws Exception
+ {
+ final Object[][] TEST_CASES = new Object[][] {
+ new Object[] { null, null },
+ new Object[] { new Object[] { null }, null },
+ new Object[] { new Object[] { "hello", null }, "hello" },
+ new Object[] { new Object[] { null, "hello" }, null },
+ new Object[] { new Object[] { "A", "B" }, "A" },
+ };
+
+ int iTestCase = 0;
+ for ( final Object[] TEST_CASE : TEST_CASES )
+ {
+ ++iTestCase;
+ final Object[] input = (Object[]) TEST_CASE[0];
+ final Object expected = (Object) TEST_CASE[1];
+
+ assertEquals( iTestCase + " th test case", expected, ArrayUtil.pickupFirst( input ) );
+ }
+ }
+
+ /**
+ * Test {@link ArrayUtil#pickupLast(Collection)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see ArrayUtil#pickupLast(Collection)
+ */
+ @Test
+ public void
+ test_pickupLast()
+ throws Exception
+ {
+ final Object[][] TEST_CASES = new Object[][] {
+ new Object[] { null, null },
+ new Object[] { new Object[] { null }, null },
+ new Object[] { new Object[] { "hello", null }, null },
+ new Object[] { new Object[] { null, "hello" }, "hello" },
+ new Object[] { new Object[] { "A", "B" }, "B" },
+ };
+
+ int iTestCase = 0;
+ for ( final Object[] TEST_CASE : TEST_CASES )
+ {
+ ++iTestCase;
+ final Object[] input = (Object[]) TEST_CASE[0];
+ final Object expected = (Object) TEST_CASE[1];
+
+ assertEquals( iTestCase + " th test case", expected, ArrayUtil.pickupLast( input ) );
+ }
+ }
+
+
+ /**
+ * Test {@link ArrayUtil#iterator(Object[])}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see ArrayUtil#iterator(Object[])
+ */
+ @Test
+ public void test_iterator() throws Exception
+ {
+ final Object[][] TEST_CASES = new Object[][] {
+ new Object[] { null },
+ new Object[] { "hello" },
+ new Object[] { null, "hello" },
+ new Object[] { "A", "B" },
+ };
+
+ int iTestCase = 0;
+ for ( final Object[] TEST_CASE : TEST_CASES )
+ {
+ ++iTestCase;
+ final Object[] array = TEST_CASE;
+ final ArrayList<Object> list = new ArrayList<Object>( Arrays.asList( array ) );
+ final Iterator<Object> iter = list.iterator();
+ final Iterator<Object> testTarget = ArrayUtil.iterator( array );
+
+ int iElement = 0;
+ while ( iter.hasNext() && testTarget.hasNext() )
+ {
+ assertEquals( iTestCase + " th test case :" + (++iElement) + " th element", iter.next(), testTarget.next() );
+ }
+ assertEquals( iTestCase + "th test case's last assert :", iter.hasNext(), testTarget.hasNext() );
+ }
+
+ try
+ {
+ final Object[] array = new Object[] { "a", "b", "c" };
+ final Iterator<Object> iter = ArrayUtil.iterator( array );
+ assertTrue( iter.hasNext() );
+ assertEquals( array[0], iter.next() );
+
+ array[1] = "d";
+
+ assertTrue( iter.hasNext() );
+ iter.next();
+ fail( "ConcurrentModificatoinException Test fail" );
+
+ } catch ( ConcurrentModificationException e )
+ {
+ // Test Success
+ }
+ }
+
+ /**
+ * Test {@link ArrayUtil#iterate(Object[], IteratingRunner, boolean)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see {@link ArrayUtil#iterate(Object[], IteratingRunner, boolean)}
+ */
+ @Test
+ public void test_iterator_with_iteratingRunner() {
+ final Object[][] TEST_CASES = new Object[][] {
+ null,
+ new Object[] { null },
+ new Object[] { "hello" },
+ new Object[] { null, "hello" },
+ new Object[] { "A", "B" },
+ };
+ for ( final Object[] TEST_CASE : TEST_CASES )
+ {
+ final Object[] array = TEST_CASE;
+
+ try {
+ ArrayUtil.iterate(array, null, false);
+ } catch (InvocationTargetException e1) {
+ fail("Failed iterate(Collection, null, false) test");
+ }
+
+ arrayIndex = 0;
+ successTest = true;
+ try {
+ ArrayUtil.iterate(array,
+ new IteratingRunner<Object>() {
+ @Override
+ public void run(Object arg) {
+ if ( successTest && arg != array[arrayIndex++] ) {
+ successTest = false;
+ }
+ }
+ },
+ true);
+ if ( !successTest ) {
+ fail("Failed iterate(Collection, IteratingRunner, true) test");
+ }
+ } catch (InvocationTargetException e) {
+ fail("Failed iterate(Collection, IteratingRunner, true) test");
+ }
+
+ arrayIndex = 0;
+ successTest = true;
+ try {
+ ArrayUtil.iterate(array,
+ new IteratingRunner<Object>() {
+ @Override
+ public void run(Object arg) {
+ if ( arg == null ) {
+ successTest = false;
+ return;
+ }
+ if ( successTest ) {
+ for ( int i = arrayIndex ; i < array.length ; i++ ) {
+ if( array[i] == null ) {
+ continue;
+ }
+ if ( arg != array[i] ) {
+ successTest = false;
+ return;
+ }
+ else {
+ arrayIndex = ++i;
+ }
+ }
+ }
+ }
+ },
+ false);
+ if ( !successTest ) {
+ fail("Failed iterate(Collection, IteratingRunner, false) test");
+ }
+ } catch (InvocationTargetException e) {
+ fail("Failed iterate(Collection, IteratingRunner, false) test");
+ }
+ }
+ }
+
+
+ /**
+ * Test {@link ArrayUtil#convertToWrapper(char[])}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see ArrayUtil#convertToWrapper(char[])
+ */
+ @Test
+ public void test_convertToWrapper() throws Exception
+ {
+ final char[] input = "hello".toCharArray();
+ final Character[] ret = ArrayUtil.convertToWrapper( input );
+
+ assertEquals( input.length, ret.length );
+ }
+
+ /**
+ * Test {@link ArrayUtil#filter(Object[], IteratingAcceptor, boolean)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see ArrayUtil#filter(Object[], IteratingAcceptor, boolean)
+ */
+ @Test
+ public void test_filter() throws Exception
+ {
+ final Character[] input = ArrayUtil.convertToWrapper( "hello".toCharArray() );
+
+ assertTrue( Arrays.equals(
+ new Character[] { 'l', 'l' },
+ ArrayUtil.filter( input, new IteratingAcceptor<Character>() {
+ public boolean accept( Character arg)
+ {
+ return ( 'l' == arg );
+ }
+ }, true )
+ ) );
+ }
+
+ @Test
+ public void test_toObjectArray() {
+ final Object[][] inputArray = new Object[][]{
+ null,
+ new String[]{"hello", "test", "java"},
+ new Integer[]{10, 20, 30},
+ {10,20,30},
+ {true, false, true},
+ {true, 10, false},
+ new Object[]{"hello", 10, 5},
+ new Object[]{5, "java", 5},
+ new Object[]{null, "hello", 10},
+ new Object[]{null, null, null},
+ new Object[]{ }
+ };
+
+ final int inputInt[] = {10,20,30};
+ final boolean inputBool[] = {true, false, false};
+
+ Object[] actualData = null;
+
+ for ( Object[] input : inputArray ) {
+ actualData = ArrayUtil.toObjectArray(input);
+ if ( (input == null || input.length == 0) ) {
+ if ( actualData.length != 0 ) {
+ fail("Failed toObjectArray(object) test");
+ }
+ }
+ else {
+ if ( input != actualData) {
+ fail("Failed toObjectArray(object) test");
+ }
+ }
+ }
+
+ actualData = ArrayUtil.toObjectArray(inputInt);
+ if ( !(actualData instanceof Integer[]) ) {
+ fail("Failed toObjectArray(int[]) test");
+ }
+ actualData = ArrayUtil.toObjectArray(inputBool);
+ if ( !(actualData instanceof Boolean[]) ) {
+ fail("Failed toObjectArray(boolean[]) test");
+ }
+ }
+
+ @Test
+ public void test_size_primitive(){
+ final boolean[][] inputBool = {
+ null,
+ {false},
+ {true, true},
+ };
+ final byte[][] inputByte = {
+ null,
+ {0x00},
+ {0x1a, 0x10},
+ };
+ final char[][] inputChar = {
+ null,
+ {'a'},
+ {'a', 'b'}
+ };
+ final short[][] inputShort = {
+ null,
+ {1},
+ {10, 20}
+ };
+ final int[][] inputInt = {
+ null,
+ {100},
+ {200, 300}
+ };
+ final long[][] inputLong = {
+ null,
+ {100l},
+ {200l, 300l}
+ };
+ final float[][] inputFloat = {
+ null,
+ {100f},
+ {200f, 300f}
+ };
+ final double[][] inputDouble = {
+ null,
+ {100d},
+ {200d, 300d}
+ };
+ int size = 0;
+
+ for ( boolean[] input : inputBool ) {
+ size = ArrayUtil.size(input);
+ if ( input == null ) {
+ if ( size != 0 ) {
+ fail("Failed size(boolean[]) test");
+ }
+ }
+ else {
+ assertEquals(input.length, ArrayUtil.size(input));
+ }
+ }
+
+ for ( byte[] input : inputByte ) {
+ size = ArrayUtil.size(input);
+ if ( input == null ) {
+ if ( size != 0 ) {
+ fail("Failed size(byte[]) test");
+ }
+ }
+ else {
+ assertEquals(input.length, ArrayUtil.size(input));
+ }
+ }
+
+ for ( char[] input : inputChar ) {
+ size = ArrayUtil.size(input);
+ if ( input == null ) {
+ if ( size != 0 ) {
+ fail("Failed size(char[]) test");
+ }
+ }
+ else {
+ assertEquals(input.length, ArrayUtil.size(input));
+ }
+ }
+
+ for ( short[] input : inputShort ) {
+ size = ArrayUtil.size(input);
+ if ( input == null ) {
+ if ( size != 0 ) {
+ fail("Failed size(short[]) test");
+ }
+ }
+ else {
+ assertEquals(input.length, ArrayUtil.size(input));
+ }
+ }
+
+ for ( int[] input : inputInt ) {
+ size = ArrayUtil.size(input);
+ if ( input == null ) {
+ if ( size != 0 ) {
+ fail("Failed size(int[]) test");
+ }
+ }
+ else {
+ assertEquals(input.length, ArrayUtil.size(input));
+ }
+ }
+
+ for ( long[] input : inputLong ) {
+ size = ArrayUtil.size(input);
+ if ( input == null ) {
+ if ( size != 0 ) {
+ fail("Failed size(long[]) test");
+ }
+ }
+ else {
+ assertEquals(input.length, ArrayUtil.size(input));
+ }
+ }
+
+ for ( float[] input : inputFloat ) {
+ size = ArrayUtil.size(input);
+ if ( input == null ) {
+ if ( size != 0 ) {
+ fail("Failed size(float[]) test");
+ }
+ }
+ else {
+ assertEquals(input.length, ArrayUtil.size(input));
+ }
+ }
+
+ for ( double[] input : inputDouble ) {
+ size = ArrayUtil.size(input);
+ if ( input == null ) {
+ if ( size != 0 ) {
+ fail("Failed size(double[]) test");
+ }
+ }
+ else {
+ assertEquals(input.length, ArrayUtil.size(input));
+ }
+ }
+ }
+
+ @Test
+ public void test_size() {
+ final Object[][] inputArray = new Object[][]{
+ null,
+ new String[]{"hello", "test", "java"},
+ new Integer[]{10, 20, 30},
+ {10,20,30},
+ {true, false, true},
+ {true, 10, false},
+ new Object[]{"hello", 10, 5},
+ new Object[]{5, "java", 5},
+ new Object[]{null, "hello", 10},
+ new Object[]{null, null, null},
+ new Object[]{ }
+ };
+ final int inputInt[] = {10,20,30};
+ final boolean inputBool[] = {true, false, false};
+
+ int size = 0;
+ int size2 = 0;
+ for ( Object[] input : inputArray ) {
+ size = ArrayUtil.size(input);
+ if ( input == null || input.length == 0 ) {
+ if (size != 0) {
+ fail("Failed size(T[]) test");
+ }
+ }
+ else {
+ assertEquals(input.length, size);
+ }
+
+ size2 = ArrayUtil.size((Object)input);
+ if ( input == null || input.length == 0 ) {
+ if (size2 != 0) {
+ fail("Failed size(T[]) test");
+ }
+ }
+ else {
+ assertEquals(input.length, size2);
+ }
+ }
+
+ assertEquals("Failed size(Object) test", inputInt.length, ArrayUtil.size((Object)inputInt));
+ assertEquals("Failed size(Object) test", inputInt.length, ArrayUtil.size((Object)inputBool));
+ }
+
+ @Test
+ public void test_add() {
+ final Object[][] inputArray = new Object[][]{
+ null,
+ new String[]{"hello", "test", "java"},
+ new Integer[]{10, 20, 30},
+ {10,20,30},
+ {true, false, true},
+ {true, 10, false},
+ new Object[]{"hello", 10, 5},
+ new Object[]{5, "java", 5},
+ new Object[]{null, "hello", 10},
+ new Object[]{null, null, null},
+ new Object[]{ }
+ };
+ final Object[] inputAddArg = new Object[]{
+ null,
+ "hello",
+ 10,
+ true
+ };
+
+ Object[] actualData = null;
+
+ for ( Object[] input : inputArray ) {
+ for ( Object arg : inputAddArg ) {
+ try {
+ actualData = ArrayUtil.add(input, arg);
+ } catch (ArrayStoreException e) {
+ if ( input == null ) {
+ fail("Failed add(T[], Object) test");
+ }
+ if ( arg.getClass().getName().equals(input[0].getClass().getName()) ) {
+ fail("Failed add(T[], Object) test");
+ }
+ continue;
+ }
+ if ( input == null || input.length == 0 ) {
+ assertEquals(1, actualData.length);
+ assertEquals(arg, actualData[0]);
+ }
+ else {
+ assertEquals(input.length + 1 , actualData.length);
+ assertEquals(arg, actualData[input.length]);
+ }
+ }
+ }
+ }
+
+ @Test
+ public void test_remove() {
+
+ assertArrayEquals( new String[] { "a", "b", "c" }, ArrayUtil.remove( new String[] { "a", "b", "c" }, -1 ) );
+ assertArrayEquals( new String[] { "b", "c" }, ArrayUtil.remove( new String[] { "a", "b", "c" }, 0 ) );
+ assertArrayEquals( new String[] { "a", "c" }, ArrayUtil.remove( new String[] { "a", "b", "c" }, 1 ) );
+ assertArrayEquals( new String[] { "a", "b" }, ArrayUtil.remove( new String[] { "a", "b", "c" }, 2 ) );
+ assertArrayEquals( new String[] { "a", "b", "c" }, ArrayUtil.remove( new String[] { "a", "b", "c" }, 3 ) );
+
+ assertArrayEquals( new String[] { "a", "b", "c" }, ArrayUtil.remove( new String[] { "a", "b", "c" }, -1, 0 ) );
+ assertArrayEquals( new String[] { "b", "c" }, ArrayUtil.remove( new String[] { "a", "b", "c" }, 0, 1 ) );
+ assertArrayEquals( new String[] { "a", "c" }, ArrayUtil.remove( new String[] { "a", "b", "c" }, 1, 2 ) );
+ assertArrayEquals( new String[] { "a", "b" }, ArrayUtil.remove( new String[] { "a", "b", "c" }, 2, 3 ) );
+ assertArrayEquals( new String[] { "a", "b", "c" }, ArrayUtil.remove( new String[] { "a", "b", "c" }, 3, 4 ) );
+
+ assertArrayEquals( new String[] { "c" }, ArrayUtil.remove( new String[] { "a", "b", "c" }, -1, 2 ) );
+
+ final Object[][] inputArray = new Object[][]{
+ null,
+ new String[]{"hello", "test", "java", "c", "c++", "junit", "time"},
+ new Integer[]{10, 20, 30, 40, 50, 60, 70, 80, 90},
+ {10, 20, 30, 40, 50, 60, 70, 80, 90, 100},
+ {true, false, true, true, false, true, false},
+ {true, 10, false, 20, "test", "java", 30},
+ new Object[]{"hello", 10, 5, 20, 30, true},
+ new Object[]{5, "java", 5},
+ new Object[]{null, "hello", 10},
+ new Object[]{null, null, null},
+ new Object[]{ }
+ };
+ Object[] actualData = null;
+
+ for ( Object[] input : inputArray ) {
+ for ( int i = -1 ; i < 10 ; i++ ) {
+ for( int j = -1 ; j < 10 ; j++ ) {
+ int deleteCount = 0;
+ try {
+ actualData = ArrayUtil.remove( input, i, j);
+ i = Math.max( 0, i );
+ if( j <= i) {
+ assertArrayEquals(input , actualData);
+ }
+ else {
+ deleteCount = j - i;
+ for ( int k = 0 ; k < actualData.length ; k++ ) {
+ if ( k >= i ) {
+ assertEquals(
+ "K:" + k + ", J:" + j + ", I:" +i + ", Input :" + input[k + deleteCount] + ", Actual :" + actualData[k],
+ input[k+deleteCount], actualData[k]);
+ }
+ else {
+ assertEquals(
+ "K:" + k + ", J:" + j + ", I:" +i + ", Input :" + input[k] + ", Actual :" + actualData[k],
+ input[k], actualData[k]);
+ }
+
+ }
+ }
+ }
+ catch ( ArrayIndexOutOfBoundsException e ) {
+ if ( j >= input.length || i >= input.length ) {
+ continue;
+ }
+ else {
+ fail("Failed remove(Object[], i : " + i + " , j : " + j + ") test");
+ }
+ }
+ catch ( IllegalArgumentException e ) {
+ if ( i >= j ) {
+ continue;
+ }
+ else {
+ fail("Failed remove(Object[], int, int) test");
+ }
+ }
+ catch ( NullPointerException e ){
+ if ( input == null) {
+ continue;
+ }
+ else {
+ fail("Failed remove(Object[], int, int) test");
+ }
+ }
+ catch (NegativeArraySizeException e) {
+ if ( input.length < j - i ) {
+ continue;
+ }
+ else {
+ fail("Failed remove(Object[], int, int) test");
+ }
+ }
+ }
+ }
+ }
+ }
+
+ @Test
+ public void test_contains() {
+ final Object[][] inputArray = new Object[][]{
+ null,
+ new String[]{"hello", "test", "java"},
+ new Integer[]{10, 20, 30},
+ {10,20,30},
+ {true, false, true},
+ {true, 10, false},
+ new Object[]{"hello", 10, 5},
+ new Object[]{5, "java", 5},
+ new Object[]{null, "hello", 10},
+ new Object[]{null, null, null},
+ new Object[]{ }
+ };
+ final Object[] inputElement = new Object[]{
+ 10583,
+ "zxcvb",
+ };
+
+ boolean actualData = true;
+
+ for ( Object[] input : inputArray ) {
+ if ( input == null ) {
+ actualData = ArrayUtil.contains(input, "blah");
+ assertEquals( false, actualData );
+ }
+ else {
+ for ( Object element : input) {
+ actualData = ArrayUtil.contains(input, element);
+ assertEquals( true, actualData );
+ }
+ }
+ for ( Object element : inputElement ) {
+ actualData = ArrayUtil.contains(input, element);
+ assertEquals( false, actualData );
+ }
+ }
+ }
+
+ @Test
+ public void test_get() {
+ final Object[][] inputArray = new Object[][]{
+ null,
+ new String[]{"hello", "test", "java"},
+ new Integer[]{10, 20, 30},
+ {10,20,30},
+ {true, false, true},
+ {true, 10, false},
+ new Object[]{"hello", 10, 5},
+ new Object[]{5, "java", 5},
+ new Object[]{null, "hello", 10},
+ new Object[]{null, null, null},
+ new Object[]{ }
+ };
+
+ for( Object[] input : inputArray) {
+ if ( input == null || input.length == 0 ) {
+ assertEquals( null, ArrayUtil.get(input, -1) );
+ assertEquals( null, ArrayUtil.get(input, 0) );
+ }
+ else {
+ assertEquals(null, ArrayUtil.get(input, -1) );
+ assertEquals( input[0], ArrayUtil.get(input, 0) );
+ assertEquals(null, ArrayUtil.get(input, input.length + 1) );
+ }
+ }
+ }
+
+ public
+ void
+ test_safe()
+ throws Exception
+ {
+ final String[][] TEST_CASES = new String[][] {
+ null,
+ new String[] { null, "aaa" },
+ new String[] { "hello", "world" },
+ };
+
+ for ( final String[] TEST_CASE : TEST_CASES )
+ {
+ assertNotNull( safe( TEST_CASE ) );
+ for ( final String value : safe( TEST_CASE ) )
+ {
+ assertTrue( "value :" + value, true );
+ }
+ }
+
+ }
+}
diff --git a/org.tizen.common/test/src/org/tizen/common/util/AssertTest.java b/org.tizen.common/test/src/org/tizen/common/util/AssertTest.java
new file mode 100644
index 000000000..22ed64d07
--- /dev/null
+++ b/org.tizen.common/test/src/org/tizen/common/util/AssertTest.java
@@ -0,0 +1,158 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* BonYong Lee <bonyong.lee@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+package org.tizen.common.util;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
+
+import org.junit.Test;
+
+/**
+ * AssertTest
+ *
+ * Test case for {@link Assert}
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ *
+ * @see Assert
+ */
+public class
+AssertTest
+{
+ /**
+ * Test {@link Assert#fail(String)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see {@link Assert#fail(String)}
+ */
+ @Test
+ public
+ void
+ test_fail()
+ throws Exception
+ {
+ try
+ {
+ Assert.fail( "Hello" );
+ fail();
+ }
+ catch ( final IllegalArgumentException e )
+ {
+ assertEquals( "Hello", e.getMessage() );
+ }
+ }
+
+ /**
+ * Test {@link Assert#isTrue(boolean)} and
+ * {@link Assert#isTrue(boolean, String)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see {@link Assert#isTrue(boolean)}
+ * @see {@link Assert#isTrue(boolean, String)}
+ */
+ @Test
+ public
+ void
+ test_assertTrue()
+ throws Exception
+ {
+ int a = 5;
+ int b = 2;
+ Assert.isTrue( 3 == a-b, "Good case" );
+
+ Assert.isTrue( 3 == a-b );
+ Assert.isTrue( "abc".equals( "abc" ) );
+ try
+ {
+ Assert.isTrue( 3==4 );
+ fail();
+ }
+ catch ( final IllegalArgumentException e )
+ {
+ }
+
+ }
+
+ /**
+ * Test {@link Assert#assertFalse(boolean)} and
+ * {@link Assert#assertFalse(boolean, String)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see {@link Assert#assertFalse(boolean)}
+ * @see {@link Assert#assertFalse(boolean, String)}
+ */
+ @Test
+ public void
+ test_assertFalse()
+ throws Exception
+ {
+ Assert.isFalse( 3 == 4, "Assertion passed" );
+ Assert.isFalse( 3 == 4 );
+ }
+
+ /**
+ * Test {@link Assert#isNull(Object)} and
+ * {@link Assert#isNull(Object, String)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see {@link Assert#isNull(Object)}
+ * @see {@link Assert#isNull(Object, String)}
+ */
+ @Test
+ public
+ void
+ test_assertNull()
+ throws Exception
+ {
+ Assert.isNull( null );
+ Assert.isNull( null, "Assertion passed" );
+ }
+
+ /**
+ * Test {@link Assert#notNull(boolean)} and
+ * {@link Assert#notNull(boolean, String)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see {@link Assert#notNull(boolean)}
+ * @see {@link Assert#notNull(boolean, String)}
+ */
+ @Test
+ public
+ void
+ test_notNull()
+ throws Exception
+ {
+
+ Assert.notNull( new Object() );
+ Assert.notNull( "Hello", "Assertion passed" );
+
+ }
+
+}
diff --git a/org.tizen.common/test/src/org/tizen/common/util/CollectionMapTest.java b/org.tizen.common/test/src/org/tizen/common/util/CollectionMapTest.java
new file mode 100644
index 000000000..95c6140bc
--- /dev/null
+++ b/org.tizen.common/test/src/org/tizen/common/util/CollectionMapTest.java
@@ -0,0 +1,139 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* BonYong Lee <bonyong.lee@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+package org.tizen.common.util;
+
+import static org.junit.Assert.assertEquals;
+
+import java.util.Arrays;
+
+import org.junit.Test;
+
+
+/**
+ * CollectionMapTest
+ *
+ * Test case for {@link CollectionMap}
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ *
+ * @see CollectionMap
+ */
+public class
+CollectionMapTest
+{
+ /**
+ * Test {@link CollectionMap#put(Object, Object)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see CollectionMap#put(Object, Object)
+ */
+ public
+ void
+ test_put()
+ throws Exception {
+ final CollectionMap<String, String> map = new CollectionMap<String, String>();
+
+ map.put( "hello", "world1" );
+
+ assertEquals( Arrays.asList( "world1" ), map.get( "hello" ) );
+ map.put( "hello", "world2" );
+ assertEquals( Arrays.asList( "world1", "world2" ), map.get( "hello" ) );
+ }
+
+
+ /**
+ * Test {@link CollectionMap#get(Object)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see CollectionMap#get(Object)
+ */
+ @Test
+ public
+ void
+ test_get()
+ throws Exception
+ {
+ final CollectionMap<String, String> map = new CollectionMap<String, String>();
+
+ map.put( "hello", "world1" );
+
+ assertEquals( Arrays.asList( "world1" ), map.get( "hello" ) );
+ map.put( "hello", "world2" );
+ assertEquals( Arrays.asList( "world1", "world2" ), map.get( "hello" ) );
+ }
+
+ /**
+ * Test {@link CollectionMap#remove(Object)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see CollectionMap#remove(Object)
+ */
+ @Test
+ public
+ void
+ test_remove()
+ throws Exception
+ {
+ final CollectionMap<String, String> map = new CollectionMap<String, String>();
+
+ map.put( "hello", "world1" );
+ map.put( "hello", "world2" );
+ assertEquals( Arrays.asList( "world1", "world2" ), map.get( "hello" ) );
+
+ map.remove( "hello", "world1" );
+ assertEquals( Arrays.asList( "world2" ), map.get( "hello" ) );
+ map.remove( "hello", "world1" );
+ assertEquals( Arrays.asList( "world2" ), map.get( "hello" ) );
+ map.remove( "hello", "world2" );
+ assertEquals( null, map.get( "hello" ) );
+ }
+
+
+ /**
+ * Test {@link CollectionMap#toString()}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see CollectionMap#toString()
+ */
+ @Test
+ public
+ void
+ test_toString()
+ throws Exception
+ {
+ final CollectionMap<String, String> map = new CollectionMap<String, String>();
+ map.put( "a", "b" );
+ map.put( "a", "c" );
+
+ assertEquals( "CollectionMap[a=[b, c]]", map.toString() );
+
+ map.put( "c", "d" );
+ assertEquals( "CollectionMap[a=[b, c], c=[d]]", map.toString() );
+ }
+}
diff --git a/org.tizen.common/test/src/org/tizen/common/util/CollectionUtilTest.java b/org.tizen.common/test/src/org/tizen/common/util/CollectionUtilTest.java
new file mode 100644
index 000000000..cbce5521b
--- /dev/null
+++ b/org.tizen.common/test/src/org/tizen/common/util/CollectionUtilTest.java
@@ -0,0 +1,950 @@
+/*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common.util;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.SortedMap;
+import java.util.SortedSet;
+import java.util.TreeMap;
+import java.util.TreeSet;
+import java.util.Vector;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.junit.Test;
+
+
+/**
+ * CollectionUtilsTest
+ *
+ * Test case for {@link CollectionUtil}
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ * @author GyeongSeok Seo{@literal <gyeongseok.seo@samsung.com>} (S-Core)
+ *
+ * @see CollectionUtil
+ */
+public class
+CollectionUtilTest
+{
+ /**
+ * Test {@link CollectionUtil#isEmpty(java.util.Collection)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see CollectionUtil#isEmpty(java.util.Collection)
+ */
+ @Test
+ @SuppressWarnings("serial")
+ public void test_isEmpty() throws Exception
+ {
+ assertTrue( CollectionUtil.isEmpty( null ) );
+ assertTrue( CollectionUtil.isEmpty( new HashSet<Object>() ) );
+ assertTrue( CollectionUtil.isEmpty( new HashMap<String, Object>().keySet() ) );
+ assertFalse( CollectionUtil.isEmpty( new ArrayList<Object>() {{ add("Hello"); }} ) );
+ assertFalse( CollectionUtil.isEmpty( new ArrayList<Object>( Arrays.asList( "Hello" ) ) ) );
+ }
+
+ /**
+ * Test {@link CollectionUtil#size(java.util.Collection)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see CollectionUtil#size(java.util.Collection)
+ */
+ @SuppressWarnings("unchecked")
+ @Test
+ public void test_size() throws Exception
+ {
+ assertEquals( 0, CollectionUtil.size( null ) );
+
+ /* Mock Object using Mockito */
+ final ArrayList<Object> list = mock( ArrayList.class );
+
+ when( list.size() ).thenReturn( 3 );
+ assertEquals( 3, CollectionUtil.size(list) );
+ verify( list ).size();
+
+ final HashMap<String, Object> map = new HashMap<String, Object>();
+ assertEquals( 0, CollectionUtil.size( map.keySet() ) );
+
+ map.put("Hello", 1);
+ map.put("Tizen", 2);
+ assertEquals( 2, CollectionUtil.size( map.keySet() ) );
+ }
+
+ /**
+ * Test {@link CollectionUtil#iterate(java.util.Collection, IteratingRunner)}
+ * and {@link CollectionUtil#iterate(java.util.Collection, IteratingRunner, boolean)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see {@link CollectionUtil#iterate(java.util.Collection, IteratingRunner)}
+ * @see {@link CollectionUtil#iterate(java.util.Collection, IteratingRunner, boolean)}
+ */
+ @Test
+ public void test_iterate() throws Exception
+ {
+ final AtomicInteger count = new AtomicInteger();
+
+ CollectionUtil.iterate(
+ new ArrayList<String>( Arrays.asList(
+ "hello", "Hello", "World", null, "Test"
+ ) ),
+ new IteratingRunner<String>()
+ {
+ public void run(String arg)
+ {
+ if ( Character.isUpperCase( arg.charAt( 0 ) ) )
+ {
+ count.incrementAndGet();
+ }
+ }
+ }
+ );
+
+ assertEquals( 3, count.get() );
+
+ count.set( 0 );
+ CollectionUtil.iterate(
+ new ArrayList<String>( Arrays.asList(
+ "hello", "Hello", "World", null, "Test"
+ ) ),
+ new IteratingRunner<String>()
+ {
+ public void run( final String arg)
+ {
+ throw new IllegalStateException();
+ }
+ },
+ true
+ );
+ assertEquals( 0, count.get() );
+ }
+
+ /**
+ * Test {@link CollectionUtil#filter(java.util.Collection, java.util.Collection, IteratingAcceptor, boolean)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see {@link CollectionUtil#filter(java.util.Collection, java.util.Collection, IteratingAcceptor, boolean)}
+ */
+ @Test
+ public void test_filter() throws Exception
+ {
+ final ArrayList<String> results = new ArrayList<String>();
+
+ CollectionUtil.filter(
+ null,
+ results,
+ new IteratingAcceptor<String>()
+ {
+ @Override
+ public boolean accept(String arg) {
+ return true;
+ }
+ },
+ true
+ );
+ assertEquals( 0, CollectionUtil.size(results) );
+
+ results.clear();
+ CollectionUtil.filter(
+ new ArrayList<String>( Arrays.asList(
+ "hello", "Hello", "World", null, "Test"
+ ) ),
+ results,
+ new IteratingAcceptor<String>()
+ {
+ @Override
+ public boolean accept(String arg) {
+ if ( arg != null && Character.isUpperCase( arg.charAt( 0 ) ) )
+ {
+ return true;
+ }
+ return false;
+ }
+ },
+ true
+ );
+ assertEquals( 3, CollectionUtil.size(results) );
+
+ results.clear();
+ CollectionUtil.filter(
+ new ArrayList<String>( Arrays.asList(
+ "hello", "Hello", "World", null, "Test"
+ ) ),
+ results,
+ new IteratingAcceptor<String>()
+ {
+ @Override
+ public boolean accept(String arg) {
+ if ( arg != null && Character.isUpperCase( arg.charAt( 0 ) ) )
+ {
+ return true;
+ }
+ throw new IllegalStateException();
+ }
+ },
+ true
+ );
+ assertEquals( 3, CollectionUtil.size(results) );
+ }
+
+ /**
+ * Test {@link CollectionUtil#pickupFirst(Collection)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see {@link CollectionUtil#pickupFirst(Collection)}
+ */
+ @Test
+ public void
+ test_pickupFirst()
+ throws Exception
+ {
+ final Object[][] TEST_CASES = new Object[][] {
+ new Object[] { null, null },
+ new Object[] { new Object[] { null }, null },
+ new Object[] { new Object[] { "hello", null }, "hello" },
+ new Object[] { new Object[] { null, "hello" }, null },
+ new Object[] { new Object[] { "A", "B" }, "A" },
+ };
+
+ int iTestCase = 0;
+ for ( final Object[] TEST_CASE : TEST_CASES )
+ {
+ ++iTestCase;
+ final Object[] closeables = (Object[]) TEST_CASE[0];
+ final Object expected = (Object) TEST_CASE[1];
+
+ Collection<Object> collection = null;
+ if ( null != closeables )
+ {
+ collection = Arrays.asList( closeables );
+ }
+
+ assertEquals( iTestCase + " th test case", expected, CollectionUtil.pickupFirst( collection ) );
+ }
+ }
+
+ /**
+ * Test {@link CollectionUtil#pickupLast(Collection)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see {@link CollectionUtil#pickupLast(Collection)}
+ */
+ @Test
+ public void
+ test_pickupLast()
+ throws Exception
+ {
+ final Object[][] TEST_CASES = new Object[][] {
+ new Object[] { null, null },
+ new Object[] { new Object[] { null }, null },
+ new Object[] { new Object[] { "hello", null }, null },
+ new Object[] { new Object[] { null, "hello" }, "hello" },
+ new Object[] { new Object[] { "A", "B" }, "B" },
+ };
+
+ int iTestCase = 0;
+ for ( final Object[] TEST_CASE : TEST_CASES )
+ {
+ ++iTestCase;
+ final Object[] closeables = (Object[]) TEST_CASE[0];
+ final Object expected = (Object) TEST_CASE[1];
+
+ Collection<Object> collection = null;
+ if ( null != closeables )
+ {
+ collection = Arrays.asList( closeables );
+ }
+
+ assertEquals( iTestCase + " th test case", expected, CollectionUtil.pickupLast( collection ) );
+ }
+ }
+
+ /**
+ * Test {@link CollectionUtil#iterator(Enumeration)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see {@link CollectionUtil#iterator(Enumeration)}
+ */
+ @Test
+ public
+ void
+ test_iterator()
+ throws Exception
+ {
+ final Object[][] TEST_CASES = new Object[][] {
+ new Object[] { null },
+ new Object[] { "hello" },
+ new Object[] { null, "hello" },
+ new Object[] { "A", "B" },
+ };
+
+ int iTestCase = 0;
+ for ( final Object[] TEST_CASE : TEST_CASES )
+ {
+ ++iTestCase;
+ final Object[] array = TEST_CASE;
+ final Vector<Object> list = new Vector<Object>( Arrays.asList( array ) );
+ final Iterator<Object> iter = list.iterator();
+ final Enumeration<Object> enumeration = list.elements();
+
+ final Iterator<Object> testTarget = CollectionUtil.iterator( enumeration );
+ int iElement = 0;
+ while ( iter.hasNext() && testTarget.hasNext() )
+ {
+ assertEquals( iTestCase + " th test case :" + (++iElement) + " th element", iter.next(), testTarget.next() );
+ }
+ assertEquals( iter.hasNext(), testTarget.hasNext() );
+ }
+ }
+
+ /**
+ * Test {@link CollectionUtil#asList(Object)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see {@link CollectionUtil#asList(Object)}
+ */
+ @Test
+ public
+ void
+ test_asList()
+ throws Exception
+ {
+ final Object[][] TEST_CASES = new Object[][] {
+ new Object[] { null, null },
+ new Object[] { new Object[] { null }, null },
+ new Object[] { new Object[] { "hello", null }, null },
+ new Object[] { new Object[] { null, "hello" }, "hello" },
+ new Object[] { new Object[] { "A", "B" }, "B" },
+ };
+
+ for ( final Object[] TEST_CASE : TEST_CASES )
+ {
+ assertTrue( CollectionUtil.asList(TEST_CASE) instanceof List );
+ }
+ }
+
+ /**
+ * Test {@link CollectionUtil#mergeArrayIntoCollection(Object, Collection)}
+ *
+ * @throws Exception is case of failure in test
+ *
+ * @see {@link CollectionUtil#mergeArrayIntoCollection(Object, Collection)}
+ */
+ @Test
+ public
+ void
+ test_mergeArrayIntoCollection()
+ throws Exception
+ {
+ final ArrayList<Object> list = new ArrayList<Object>();
+ list.add( "Tizen" );
+ list.add( "Test" );
+
+ final Object[][] TEST_CASES = new Object[][] {
+ new Object[] { null, null },
+ new Object[] { new Object[] { null }, null },
+ new Object[] { new Object[] { "hello", null }, null },
+ new Object[] { new Object[] { null, "hello" }, "hello" },
+ new Object[] { new Object[] { "A", "B" }, "B" },
+ };
+
+ try {
+ CollectionUtil.mergeArrayIntoCollection( TEST_CASES[0], null );
+ fail( "mergeArrayIntoCollection must throw exception" );
+ } catch (NullPointerException e) {
+ }
+
+ for ( final Object[] TEST_CASE : TEST_CASES )
+ {
+ final int count = TEST_CASE.length + CollectionUtil.size( list );
+ CollectionUtil.mergeArrayIntoCollection( TEST_CASE, list );
+ assertEquals( count, CollectionUtil.size( list ) );
+ }
+ }
+
+ /**
+ * Test {@link CollectionUtil#contains(Collection, Object)}
+ * and {@link CollectionUtil#contains(Enumeration, Object)}
+ * and {@link CollectionUtil#contains(Iterator, Object)}
+ *
+ * @throws Exception is case of failure in test
+ *
+ * @see {@link CollectionUtil#contains(Collection, Object)}
+ * @see {@link CollectionUtil#contains(Enumeration, Object)}
+ * @see {@link CollectionUtil#contains(Iterator, Object)}
+ */
+ @Test
+ public
+ void
+ test_contains()
+ throws Exception
+ {
+ final Object[][] TEST_CASES = new Object[][] {
+ new Object[] { null },
+ new Object[] { "hello" },
+ new Object[] { null, "hello" },
+ new Object[] { "Tizen", "Test" },
+ };
+
+ assertFalse( CollectionUtil.contains( (Collection<Object>)null , null) );
+ assertFalse( CollectionUtil.contains( (Enumeration<Object>)null , null) );
+ assertFalse( CollectionUtil.contains( (Iterator<Object>)null , null) );
+
+ for ( final Object[] TEST_CASE : TEST_CASES )
+ {
+ final Object[] array = TEST_CASE;
+ final Vector<Object> list = new Vector<Object>( CollectionUtil.asList( array ) );
+ final Enumeration<Object> enumeration = list.elements();
+ final Iterator<Object> iter = CollectionUtil.iterator( list.elements() );
+ final Object element = list.get(0);
+ final Object element2 = "False";
+
+ assertTrue( CollectionUtil.contains( list, element ) );
+ assertTrue( CollectionUtil.contains( enumeration, element ) );
+ assertTrue( CollectionUtil.contains( iter, element ) );
+
+ assertFalse( CollectionUtil.contains( list, element2 ) );
+ assertFalse( CollectionUtil.contains( enumeration, element2 ) );
+ assertFalse( CollectionUtil.contains( iter, element2 ) );
+ }
+ }
+
+ /**
+ * Test {@link CollectionUtil#containsAny(Collection, Collection)}
+ *
+ * @throws Exception is case of failure in test
+ *
+ * @see {@link CollectionUtil#containsAny(Collection, Collection)}
+ */
+ @Test
+ public
+ void
+ test_containsAny()
+ throws Exception
+ {
+ final Object[][] TEST_CASES = new Object[][] {
+ new Object[] { null },
+ new Object[] { "hello" },
+ new Object[] { null, "hello" },
+ new Object[] { "Tizen", "Test" },
+ };
+
+ final ArrayList<String> candidates = new ArrayList<String>();
+ candidates.add(null);
+ candidates.add("hello");
+ candidates.add("Test");
+
+ final ArrayList<String> candidates2 = new ArrayList<String>();
+ candidates2.add("False");
+
+ final ArrayList<String> source = new ArrayList<String>();
+ source.add("Tizen");
+ source.add("Test");
+ source.add(null);
+
+ assertFalse( CollectionUtil.containsAny( (Collection<Object>)null , candidates) );
+ assertFalse( CollectionUtil.containsAny( source, (Collection<Object>)null ) );
+
+ for ( final Object[] TEST_CASE : TEST_CASES )
+ {
+ final Object[] array = TEST_CASE;
+ final Vector<Object> source2 = new Vector<Object>( CollectionUtil.asList( array ) );
+
+ assertTrue( CollectionUtil.containsAny( source2, candidates ) );
+ assertFalse( CollectionUtil.containsAny( source2, candidates2 ) );
+ }
+ }
+
+ /**
+ * Test {@link CollectionUtil#isApproximableCollectionType(Class)}
+ *
+ * @throws Exception is case of failure in test
+ *
+ * @see {@link CollectionUtil#isApproximableCollectionType(Class)}
+ */
+ @Test
+ public
+ void
+ test_isApproximableCollectionType()
+ throws Exception
+ {
+ final List<Class<?>> collectionTypeList = Arrays.asList( new Class<?>[] {
+ Collection.class,
+ Set.class, HashSet.class, SortedSet.class, LinkedHashSet.class, TreeSet.class,
+ List.class, LinkedList.class, ArrayList.class
+ } );
+
+ final List<Class<?>> mapTypeList = Arrays.asList( new Class<?>[] {
+ Map.class, SortedMap.class, HashMap.class, LinkedHashMap.class, TreeMap.class
+ } );
+
+ final List<Class<?>> generalTypeList = Arrays.asList( new Class<?>[] {
+ String.class, Integer.class, Exception.class, File.class
+ } );
+
+ assertFalse( CollectionUtil.isApproximableCollectionType( (Class<?>)null ) );
+
+ final Iterator<Class<?>> iter = collectionTypeList.iterator();
+ while( iter.hasNext() ) {
+ assertTrue( CollectionUtil.isApproximableCollectionType( iter.next() ) );
+ }
+
+ final Iterator<Class<?>> iter2 = mapTypeList.iterator();
+ while( iter2.hasNext() ) {
+ assertFalse( CollectionUtil.isApproximableCollectionType( iter2.next() ) );
+ }
+
+ final Iterator<Class<?>> iter3 = generalTypeList.iterator();
+ while( iter3.hasNext() ) {
+ assertFalse( CollectionUtil.isApproximableCollectionType( iter3.next() ) );
+ }
+ }
+
+ /**
+ * Test {@link CollectionUtil#isApproximableMapType(Class)}
+ *
+ * @throws Exception is case of failure in test
+ *
+ * @see {@link CollectionUtil#isApproximableMapType(Class)}
+ */
+ @Test
+ public
+ void
+ test_isApproximableMapType()
+ throws Exception
+ {
+ final List<Class<?>> collectionTypeList = Arrays.asList( new Class<?>[] {
+ Collection.class,
+ Set.class, HashSet.class, SortedSet.class, LinkedHashSet.class, TreeSet.class,
+ List.class, LinkedList.class, ArrayList.class
+ } );
+
+ final List<Class<?>> mapTypeList = Arrays.asList( new Class<?>[] {
+ Map.class, SortedMap.class, HashMap.class, LinkedHashMap.class, TreeMap.class
+ } );
+
+ final List<Class<?>> generalTypeList = Arrays.asList( new Class<?>[] {
+ String.class, Integer.class, Exception.class, File.class
+ } );
+
+ assertFalse( CollectionUtil.isApproximableMapType( (Class<?>)null ) );
+
+ final Iterator<Class<?>> iter = collectionTypeList.iterator();
+ while( iter.hasNext() ) {
+ assertFalse( CollectionUtil.isApproximableMapType( iter.next() ) );
+ }
+
+ final Iterator<Class<?>> iter2 = mapTypeList.iterator();
+ while( iter2.hasNext() ) {
+ assertTrue( CollectionUtil.isApproximableMapType( iter2.next() ) );
+ }
+
+ final Iterator<Class<?>> iter3 = generalTypeList.iterator();
+ while( iter3.hasNext() ) {
+ assertFalse( CollectionUtil.isApproximableMapType( iter3.next() ) );
+ }
+ }
+
+ /**
+ * Test {@link CollectionUtil#createApproximableCollection(Collection, int)}
+ *
+ * @throws Exception is case of failure in test
+ *
+ * @see {@link CollectionUtil#createApproximableCollection(Collection, int)}
+ */
+ @Test
+ public
+ void
+ test_createApproximableCollection()
+ throws Exception
+ {
+ final ArrayList<String> list = new ArrayList<String>( Arrays.asList(
+ "hello", "Hello", "World", null, "Test"
+ ) );
+
+ final HashMap<String, Object> map = new HashMap<String, Object>();
+ map.put("Hello", 1);
+ map.put("Tizen", 2);
+
+ Collection<?> result = CollectionUtil.createApproximableCollection( null, 5 );
+ assertTrue( CollectionUtil.isApproximableCollectionType( result.getClass() ) );
+ result.clear();
+
+ result = CollectionUtil.createApproximableCollection( list, 3 );
+ assertTrue( CollectionUtil.isApproximableCollectionType( result.getClass() ) );
+ result.clear();
+
+ result = CollectionUtil.createApproximableCollection( map.keySet(), 2 );
+ assertTrue( CollectionUtil.isApproximableCollectionType( result.getClass() ) );
+ }
+
+ /**
+ * Test {@link CollectionUtil#createApproximableMap(Map, int)}
+ *
+ * @throws Exception is case of failure in test
+ *
+ * @see {@link CollectionUtil#createApproximableMap(Map, int)}
+ */
+ @Test
+ public
+ void
+ test_createApproximableMap()
+ throws Exception
+ {
+ final HashMap<String, Object> map = new HashMap<String, Object>();
+ map.put("Hello", 1);
+ map.put("Tizen", 2);
+
+ Map<?,?> result = CollectionUtil.createApproximableMap( null, 5 );
+ assertTrue( CollectionUtil.isApproximableMapType( result.getClass() ) );
+ result.clear();
+
+ result = CollectionUtil.createApproximableMap( map, 1 );
+ assertTrue( CollectionUtil.isApproximableMapType( result.getClass() ) );
+ }
+
+ /**
+ * Test {@link CollectionUtil#toString(Object)}
+ * and {@link CollectionUtil#toString(boolean[])}
+ * and {@link CollectionUtil#toString(char[])}
+ *
+ * @throws Exception is case of failure in test
+ *
+ * @see {@link CollectionUtil#toString(Object)}
+ * @see {@link CollectionUtil#toString(boolean[])}
+ * @see {@link CollectionUtil#toString(char[])}
+ */
+ @Test
+ public
+ void
+ test_toString()
+ throws Exception
+ {
+ Object obj = (Object)new ArrayList<String>( Arrays.asList(
+ "hello", "Hello", "World", null, "Test"
+ ) );
+ boolean [] booleanArray = { true, false };
+ boolean [] booleanArray2 = {};
+ char [] charArray = { 'T', 'i', 'Z', 'e', 'N' };
+ char [] charArray2 = {};
+
+ // toString(Object)
+ String result = CollectionUtil.toString( (Object)null );
+ assertEquals( StringUtil.NULL_STRING, result);
+ result = CollectionUtil.toString( (Object)booleanArray );
+ assertEquals( "{true, false}", result );
+ result = CollectionUtil.toString( (Object)charArray );
+ assertEquals( "{T, i, Z, e, N}", result );
+ result = CollectionUtil.toString(obj);
+ assertEquals( "[hello, Hello, World, null, Test]", result);
+
+ // toString(boolean[])
+ result = CollectionUtil.toString( (boolean[])null );
+ assertEquals( StringUtil.NULL_STRING, result);
+ result = CollectionUtil.toString( booleanArray );
+ assertEquals( "{true, false}", result );
+ result = CollectionUtil.toString( booleanArray2 );
+ assertEquals( "{}", result );
+
+ // toString(char[])
+ result = CollectionUtil.toString( (char[])null );
+ assertEquals( StringUtil.NULL_STRING, result);
+ result = CollectionUtil.toString( charArray );
+ assertEquals( "{T, i, Z, e, N}", result );
+ result = CollectionUtil.toString( charArray2 );
+ assertEquals( "{}", result );
+ }
+
+ /**
+ * Test {@link CollectionUtil#concatenate(Collection, String)}
+ * and {@link CollectionUtil#concatenate(Object[], String)}
+ * and {@link CollectionUtil#concatenate(Iterator, String)}
+ *
+ * @throws Exception is case of failure in test
+ *
+ * @see {@link CollectionUtil#concatenate(Collection, String)}
+ * @see {@link CollectionUtil#concatenate(Object[], String)}
+ * @see {@link CollectionUtil#concatenate(Iterator, String)}
+ */
+ @Test
+ public
+ void
+ test_concatenate()
+ throws Exception
+ {
+ final String separator = "$";
+
+ final Object[][] TEST_CASES = new Object[][] {
+ new Object[] {},
+ new Object[] { null },
+ new Object[] { "hello" },
+ new Object[] { null, "hello" },
+ new Object[] { "Tizen", "Test" },
+ };
+
+ assertEquals( StringUtil.NULL_STRING,
+ CollectionUtil.concatenate( (Object[])null, separator ) );
+ assertEquals( StringUtil.NULL_STRING,
+ CollectionUtil.concatenate( (Collection<Object>)null, separator) );
+ assertEquals( StringUtil.NULL_STRING,
+ CollectionUtil.concatenate( (Iterator<Object>)null, separator) );
+
+ int count = 0;
+ for ( final Object[] TEST_CASE : TEST_CASES )
+ {
+ count++;
+ final Object[] array = TEST_CASE;
+ final Vector<Object> list = new Vector<Object>( CollectionUtil.asList( array ) );
+ Iterator<Object> iter = CollectionUtil.iterator( list.elements() );
+
+ switch (count) {
+ case 1:
+ assertEquals( "{}",
+ CollectionUtil.concatenate( array, separator ) );
+ assertEquals( "{}",
+ CollectionUtil.concatenate( list, separator ) );
+ assertEquals( "{}",
+ CollectionUtil.concatenate( iter, separator ) );
+ break;
+ case 2:
+ assertEquals( StringUtil.NULL_STRING,
+ CollectionUtil.concatenate( array, separator ) );
+ assertEquals( StringUtil.NULL_STRING,
+ CollectionUtil.concatenate( list, separator ) );
+ assertEquals( StringUtil.NULL_STRING,
+ CollectionUtil.concatenate( iter, separator ) );
+ break;
+ case 3:
+ assertEquals( "hello",
+ CollectionUtil.concatenate( array, separator ) );
+ assertEquals( "hello",
+ CollectionUtil.concatenate( list, separator ) );
+ assertEquals( "hello",
+ CollectionUtil.concatenate( iter, separator ) );
+ break;
+ case 4:
+ assertEquals( StringUtil.NULL_STRING+separator+"hello",
+ CollectionUtil.concatenate( array, separator ) );
+ assertEquals( StringUtil.NULL_STRING+separator+"hello",
+ CollectionUtil.concatenate( list, separator ) );
+ assertEquals( StringUtil.NULL_STRING+separator+"hello",
+ CollectionUtil.concatenate( iter, separator ) );
+ break;
+ case 5:
+ assertEquals( "Tizen"+separator+"Test",
+ CollectionUtil.concatenate( array, separator ) );
+ assertEquals( "Tizen"+separator+"Test",
+ CollectionUtil.concatenate( list, separator ) );
+ assertEquals( "Tizen"+separator+"Test",
+ CollectionUtil.concatenate( iter, separator ) );
+
+ iter = CollectionUtil.iterator( list.elements() );
+ assertEquals( "Tizen"+null+"Test",
+ CollectionUtil.concatenate( array, null ) );
+ assertEquals( "Tizen"+null+"Test",
+ CollectionUtil.concatenate( list, null ) );
+ assertEquals( "Tizen"+null+"Test",
+ CollectionUtil.concatenate( iter, null ) );
+
+ iter = CollectionUtil.iterator( list.elements() );
+ assertEquals( "Tizen"+StringUtil.EMPTY_STRING+"Test",
+ CollectionUtil.concatenate( array, StringUtil.EMPTY_STRING ) );
+ assertEquals( "Tizen"+StringUtil.EMPTY_STRING+"Test",
+ CollectionUtil.concatenate( list, StringUtil.EMPTY_STRING ) );
+ assertEquals( "Tizen"+StringUtil.EMPTY_STRING+"Test",
+ CollectionUtil.concatenate( iter, StringUtil.EMPTY_STRING ) );
+ break;
+ }
+
+ }
+ }
+
+ /**
+ * Test {@link CollectionUtil#hashCode(Object)}
+ * and {@link CollectionUtil#hashCode(boolean[])}
+ * and {@link CollectionUtil#hashCode(int[])}
+ *
+ * @throws Exception is case of failure in test
+ *
+ * @see {@link CollectionUtil#hashCode(Object)}
+ * @see {@link CollectionUtil#hashCode(boolean[])}
+ * @see {@link CollectionUtil#hashCode(int[])}
+ */
+ @Test
+ public
+ void
+ test_hashCode()
+ throws Exception
+ {
+ Object obj = (Object)new ArrayList<String>( Arrays.asList(
+ "hello", "Hello", "World", null, "Test"
+ ) );
+ boolean [] booleanArray = { true, false };
+ boolean [] booleanArray2 = {};
+ int [] intArray = { 1, 2, 3, 4, 5 };
+ int [] intArray2 = {};
+
+ // hashCode(Object)
+ assertEquals( 0, CollectionUtil.hashCode( (Object)null ) );
+ assertTrue( 0 != CollectionUtil.hashCode(obj) );
+ assertTrue( 0 != CollectionUtil.hashCode( (Object)booleanArray ) );
+ assertTrue( 0 != CollectionUtil.hashCode( (Object)booleanArray2) );
+ assertTrue( 0 != CollectionUtil.hashCode( (Object)intArray) );
+ assertTrue( 0 != CollectionUtil.hashCode( (Object)intArray2) );
+ assertEquals( CollectionUtil.hashCode(obj), CollectionUtil.hashCode(obj) );
+
+ // hashCode(boolean[])
+ assertEquals( 0, CollectionUtil.hashCode( (boolean[])null ) );
+ assertTrue( 0 != CollectionUtil.hashCode( booleanArray ) );
+ assertTrue( 0 != CollectionUtil.hashCode( booleanArray2) );
+ assertTrue( CollectionUtil.hashCode(booleanArray) != CollectionUtil.hashCode(booleanArray2) );
+ assertEquals( CollectionUtil.hashCode(booleanArray), CollectionUtil.hashCode(booleanArray) );
+
+ // hashCode(int[])
+ assertEquals( 0, CollectionUtil.hashCode( (int[])null ) );
+ assertTrue( 0 != CollectionUtil.hashCode( intArray ) );
+ assertTrue( 0 != CollectionUtil.hashCode( intArray2) );
+ assertTrue( CollectionUtil.hashCode(intArray) != CollectionUtil.hashCode(intArray2) );
+ assertEquals( CollectionUtil.hashCode(intArray), CollectionUtil.hashCode(intArray));
+ }
+
+ /**
+ * Test {@link CollectionUtil#equals(Collection...)}
+ * and {@link CollectionUtil#equals(Object[]...)}
+ *
+ * @throws Exception is case of failure in test
+ *
+ * @see {@link CollectionUtil#equals(Collection...)}
+ * @see {@link CollectionUtil#equals(Object[]...)}
+ */
+ @SuppressWarnings("unchecked")
+ @Test
+ public
+ void
+ test_equals()
+ throws Exception
+ {
+ final Object obj = (Object)new ArrayList<String>( Arrays.asList(
+ "hello", "Hello", "World", null, "Test"
+ ) );
+ final Object obj2 = (Object)Arrays.asList(
+ "hello", "Hello", "World", null, "Test"
+ );
+ final Boolean [] booleanArray = { true, false };
+ final Integer [] intArray = { 1, 2, 3, 4, 5 };
+ final Integer [] intArray2 = {};
+ final Object [] objectArray = { 1, 2, 3, 4, 5 };
+ final Object [] objectArray2 = { 1, 2, 3, 4, 5 };
+ final Vector<Object> list = new Vector<Object>( CollectionUtil.asList(objectArray) );
+
+ assertTrue( CollectionUtil.equals( (Object[])null, null) );
+ assertTrue( CollectionUtil.equals( (Collection<Object>)null, null) );
+
+ // equals(Object[]...)
+ assertTrue( CollectionUtil.equals( objectArray, objectArray2 ) );
+ assertTrue( CollectionUtil.equals( objectArray, (Object[])intArray ) );
+ assertFalse( CollectionUtil.equals( objectArray, (Object[])intArray2 ) );
+ assertFalse( CollectionUtil.equals( objectArray, (Object[])booleanArray ) );
+
+ // equals(COllection...)
+ assertTrue( CollectionUtil.equals( (Collection<?>)obj, (Collection<?>)obj2 ) );
+ assertFalse( CollectionUtil.equals( (Collection<?>)obj, (Collection<?>)list ) );
+ }
+
+ /**
+ * Test {@link CollectionUtil#swap(Object[], int, int)}
+ *
+ * @throws Exception is case of failure in test
+ *
+ * @see {@link CollectionUtil#swap(Object[], int, int)}
+ */
+ @Test
+ public
+ void
+ test_swap()
+ throws Exception
+ {
+ final Object [] objectArray = { 1, 2, 3, 4, 5 };
+
+ CollectionUtil.swap( objectArray, 0, 1 );
+ assertEquals( 2, objectArray[0] );
+ assertEquals( 1, objectArray[1] );
+
+ CollectionUtil.swap( objectArray, 1, 0 );
+ assertEquals( 1, objectArray[0] );
+ assertEquals( 2, objectArray[1] );
+
+ CollectionUtil.swap( objectArray, 0, 0 );
+ assertEquals( 1, objectArray[0] );
+ assertEquals( 2, objectArray[1] );
+
+ try {
+ CollectionUtil.swap( objectArray, 0, 5 );
+ fail( "swap must throw exception" );
+ } catch (Exception e) {
+ }
+
+ try {
+ CollectionUtil.swap( objectArray, -1, 0 );
+ fail( "swap must throw exception" );
+ } catch (Exception e) {
+ }
+
+ try {
+ CollectionUtil.swap( null, 0, 1 );
+ fail( "swap must throw exception" );
+ } catch (Exception e) {
+ }
+ }
+}
+
diff --git a/org.tizen.common/test/src/org/tizen/common/util/EFSUtilTest.java b/org.tizen.common/test/src/org/tizen/common/util/EFSUtilTest.java
new file mode 100644
index 000000000..27097d251
--- /dev/null
+++ b/org.tizen.common/test/src/org/tizen/common/util/EFSUtilTest.java
@@ -0,0 +1,240 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* Jihoon Song <jihoon80.song@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+
+package org.tizen.common.util;
+
+import java.net.URI;
+import java.net.URL;
+
+import org.junit.*;
+import org.tizen.common.Surrogate;
+import org.tizen.common.util.EFSUtil.DialogChoicer;
+
+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.runtime.IProgressMonitor;
+import org.eclipse.swt.widgets.Shell;
+
+import static org.junit.Assert.*;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+import static org.mockito.Mockito.verify;
+
+/**
+ * EFSUtilTest.
+ *
+ * Helper related to {@link EFSUtil}
+ *
+ * @author Jihoon Song{@literal <jihoon80.song@samsung.com>} (S-Core)
+ *
+ * @see EFSUtil
+ *
+ */
+public class EFSUtilTest {
+
+ /**
+ * Property key for URL handler
+ */
+ protected static final String PROP_PKG = "java.protocol.handler.pkgs";
+
+ protected static final String TEST_PATH = "test";
+ protected static final String TEST_URL = "cp:///" + TEST_PATH;
+
+ /**
+ * Old property value for URL handler
+ */
+ protected String oldConfig;
+
+
+ /**
+ * Set up URL handler and FileSystem before test
+ */
+ @Before
+ public void setUp() {
+ oldConfig = System.getProperty( PROP_PKG );
+ System.setProperty( PROP_PKG, "org.tizen.common.util.url" );
+
+ // prevent recreation mock-up when called
+ final IFileSystem mockFileSystem = mock(IFileSystem.class);
+
+ EFSUtil.setFileSystemSurrogate(new Surrogate<IFileSystem>() {
+ @Override
+ public IFileSystem getAdapter() {
+ return mockFileSystem;
+ }
+ });
+ }
+
+ /**
+ * Restore URL handler after test
+ */
+ @After
+ public void tearDown() {
+ if ( null == oldConfig ) {
+ System.getProperties().remove( PROP_PKG );
+ } else {
+ System.setProperty( PROP_PKG, oldConfig );
+ }
+ }
+
+ /**
+ * Test {@link EFSUtil#isExistResource(IFileStore)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see EFSUtil#isExistResource(IFileStore)
+ */
+ @Test
+ public void test_isExistResource_IFileStore() throws Exception {
+ // null check
+ IFileStore nullFileStore = null;
+ assertFalse( EFSUtil.isExistResource(nullFileStore) );
+
+
+ IFileInfo mockFileInfo = mock( IFileInfo.class );
+ IFileStore mockFileStore = mock( IFileStore.class );
+ when( mockFileStore.fetchInfo() ).thenReturn( mockFileInfo );
+
+ // true check
+ when( mockFileInfo.exists() ).thenReturn( true );
+ assertTrue( EFSUtil.isExistResource(mockFileStore) );
+
+ // false check
+ when( mockFileInfo.exists() ).thenReturn( false );
+ assertFalse( EFSUtil.isExistResource(mockFileStore) );
+ }
+
+ /**
+ * Test {@link EFSUtil#isExistResource(URI)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see EFSUtil#isExistResource(URI)
+ */
+ @Test
+ public void test_isExistResource_URI() throws Exception {
+ // null check
+ final URI nullURI = null;
+ when( EFSUtil.getFileSystem().getStore(nullURI) ).thenReturn( null );
+ assertFalse( EFSUtil.isExistResource(nullURI) );
+
+
+ IFileInfo mockFileInfo = mock( IFileInfo.class );
+ IFileStore mockFileStore = mock( IFileStore.class );
+ when( mockFileStore.fetchInfo() ).thenReturn( mockFileInfo );
+
+ final URI virtualURI = new URL(TEST_URL).toURI();
+ when( EFSUtil.getFileSystem().getStore(virtualURI) ).thenReturn( mockFileStore );
+
+ // true check
+ when( mockFileInfo.exists() ).thenReturn( true );
+ assertTrue( EFSUtil.isExistResource(virtualURI) );
+
+ // false check
+ when( mockFileInfo.exists() ).thenReturn( false );
+ assertFalse( EFSUtil.isExistResource(virtualURI) );
+ }
+
+ /**
+ * Test {@link EFSUtil#isExistResourceWithDialog(Shell, String, String, DialogChoicer, IFileStore)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see EFSUtil#isExistResourceWithDialog(Shell, String, String, DialogChoicer, IFileStore)
+ */
+ @Test
+ public void test_isExistResourceWithDialog() throws Exception {
+ Shell mockShell = mock( Shell.class );
+ IFileStore mockFileStore = mock( IFileStore.class );
+ IFileInfo mockFileInfo = mock (IFileInfo.class );
+ when(mockFileStore.fetchInfo()).thenReturn(mockFileInfo);
+
+ final Object[][] TEST_CASES = new Object[][] { // [TestCase] [Arguments..., ExpectResult]
+ new Object[] { mockShell, "Title", "Msg", DialogChoicer.Cancel, mockFileStore, true, DialogChoicer.Cancel },
+ new Object[] { mockShell, "Title", "Msg", DialogChoicer.Cancel, mockFileStore, false, DialogChoicer.Cancel },
+ new Object[] { mockShell, "Title", "Msg", DialogChoicer.NoToAll, mockFileStore, true, DialogChoicer.NoToAll },
+ new Object[] { mockShell, "Title", "Msg", DialogChoicer.NoToAll, mockFileStore, false, DialogChoicer.NoToAll },
+ new Object[] { mockShell, "Title", "Msg", DialogChoicer.YesToAll, mockFileStore, true, DialogChoicer.YesToAll },
+ new Object[] { mockShell, "Title", "Msg", DialogChoicer.YesToAll, mockFileStore, false, DialogChoicer.YesToAll },
+ new Object[] { mockShell, "Title", "Msg", DialogChoicer.Yes, mockFileStore, false, DialogChoicer.Yes },
+ new Object[] { mockShell, "Title", "Msg", DialogChoicer.No, mockFileStore, false, DialogChoicer.Yes }
+ // except dialog open scenarios
+ };
+
+ DialogChoicer existResourceWithDialog = null;
+
+ for (final Object[] TEST_CASE : TEST_CASES) {
+ final Shell shell = (Shell) TEST_CASE[0];
+ final String title = (String) TEST_CASE[1];
+ final String msg = (String) TEST_CASE[2];
+ final DialogChoicer choicer = (DialogChoicer) TEST_CASE[3];
+ final IFileStore fileStore = (IFileStore) TEST_CASE[4];
+ final boolean exist = (Boolean) TEST_CASE[5];
+ final DialogChoicer expected = (DialogChoicer) TEST_CASE[6];
+
+ when( mockFileInfo.exists() ).thenReturn(exist);
+ existResourceWithDialog = EFSUtil.isExistResourceWithDialog(
+ shell, title, msg, choicer, fileStore);
+ assertEquals( shell + ", " + title + ", " + msg + ", " + choicer + ", " +
+ fileStore.fetchInfo().exists() + " : " + expected, existResourceWithDialog, expected );
+ }
+ }
+
+
+ /**
+ * Test {@link EFSUtil#copy(URI, URI, int, IProgressMonitor)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see EFSUtil#copy(URI, URI, int, IProgressMonitor)
+ */
+ @Test
+ public void test_copy() throws Exception {
+ final URI virtualURI = new URL(TEST_URL).toURI();
+ final IProgressMonitor mockMonitor = mock(IProgressMonitor.class);
+
+ IFileStore mockFileStore = mock( IFileStore.class );
+ when( EFSUtil.getFileSystem().getStore(virtualURI) ).thenReturn( mockFileStore );
+
+ final Object[][] TEST_CASES = new Object[][] { // [TestCase] [Arguments..., ExpectResult]
+ new Object[] { virtualURI, virtualURI, EFS.OVERWRITE, mockMonitor },
+ new Object[] { virtualURI, virtualURI, EFS.SHALLOW, mockMonitor },
+ new Object[] { virtualURI, virtualURI, EFS.OVERWRITE | EFS.SHALLOW, mockMonitor }
+ };
+
+ for (final Object[] TEST_CASE : TEST_CASES) {
+ final URI source = (URI) TEST_CASE[0];
+ final URI destination = (URI) TEST_CASE[1];
+ final int options = (Integer) TEST_CASE[2];
+ final IProgressMonitor monitor = (IProgressMonitor) TEST_CASE[3];
+
+ EFSUtil.copy(source, destination, options, monitor);
+
+ verify( mockFileStore ).copy(mockFileStore, options, mockMonitor);
+ }
+ }
+}
diff --git a/org.tizen.common/test/src/org/tizen/common/util/FileUtilTest.java b/org.tizen.common/test/src/org/tizen/common/util/FileUtilTest.java
new file mode 100644
index 000000000..22e7b1897
--- /dev/null
+++ b/org.tizen.common/test/src/org/tizen/common/util/FileUtilTest.java
@@ -0,0 +1,113 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* BonYong Lee <bonyong.lee@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+package org.tizen.common.util;
+
+import static org.junit.Assert.*;
+
+import java.io.ByteArrayInputStream;
+import java.io.InputStream;
+
+import org.junit.Test;
+
+/**
+ * FileUtilTest
+ *
+ * Test case for {@link FileUtil}
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ *
+ * @see FileUtil
+ */
+public class FileUtilTest {
+
+ /**
+ * Test {@link FileUtil#getFileExtension(String)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see {@link FileUtil#getFileExtension(String)}
+ */
+ @Test
+ public void test_getFileExtension() throws Exception {
+ final Object[][] TEST_CASES = new Object[][] {
+ new Object[] { "aaaa.exe", "exe" },
+ new Object[] { "index.html", "html" },
+ new Object[] { "index.test.html", "html" },
+ new Object[] { "index..html", "html" },
+ new Object[] { ".profile", "profile" },
+ new Object[] { "ReadMe ", null },
+ new Object[] { "ReadMe", null },
+ new Object[] { "ReadMe. ", " " },
+ new Object[] { "ReadMe. test", " test" }
+ };
+
+ int i = 0;
+ for ( final Object[] TEST_CASE : TEST_CASES )
+ {
+ final String fileName = (String) TEST_CASE[0];
+ final String expected = (String) TEST_CASE[1];
+ final String result = FileUtil.getFileExtension( fileName );
+
+ assertEquals( ++i + "th Test case :<" + fileName + ", " + expected + ">", expected, result );
+ }
+ }
+
+ /**
+ * Test {@link FileUtil#readTextStream(InputStream input, String encoding)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see {@link FileUtil#readTextStream(InputStream input, String encoding)}
+ */
+ @Test
+ public void test_readTextStream() throws Exception {
+ String text = "Test Text 123";
+ String unicodeText = "\uD55C\uAE00\uD14C\uC2A4\uD2B8";
+
+ try {
+ FileUtil.readTextStream(null, null);
+ fail( "readTextStream must throw exception" );
+ } catch (Exception e) {
+ }
+
+ InputStream input = new ByteArrayInputStream(text.getBytes());
+ String content = FileUtil.readTextStream(input, null);
+ assertEquals(text, content);
+
+ InputStream unicodeInput = new ByteArrayInputStream(unicodeText.getBytes("UTF-8"));
+ String unicodeContent = FileUtil.readTextStream(unicodeInput, "UTF-8");
+ assertEquals(unicodeText, unicodeContent);
+ String isoContent = FileUtil.readTextStream(unicodeInput, "ISO-8859-1");
+ assertNotSame(unicodeText, isoContent);
+
+ if (input != null) {
+ input.close();
+ }
+ if (unicodeInput != null) {
+ unicodeInput.close();
+ }
+ }
+
+}
diff --git a/org.tizen.common/test/src/org/tizen/common/util/FilenameUtilTest.java b/org.tizen.common/test/src/org/tizen/common/util/FilenameUtilTest.java
new file mode 100644
index 000000000..42ffdf2ff
--- /dev/null
+++ b/org.tizen.common/test/src/org/tizen/common/util/FilenameUtilTest.java
@@ -0,0 +1,256 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* BonYong Lee <bonyong.lee@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+package org.tizen.common.util;
+
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+
+import java.io.File;
+
+import org.junit.Test;
+
+
+/**
+ * FilenameUtilTest
+ *
+ * Test case for {@link FilenameUtil}
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ *
+ * @see FilenameUtil
+ */
+public class
+FilenameUtilTest
+{
+ /**
+ * Test {@link FilenameUtil#getCanonicalFragments(String)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see FilenameUtil#getCanonicalFragments(String)
+ */
+ @Test
+ public
+ void
+ test_getCanonicalFragments()
+ throws Exception
+ {
+ final Object[][] TEST_CASES = new Object[][] {
+ new Object[] { "/aaa/bbb/ccc", new String[] { "aaa", "bbb", "ccc" } },
+ new Object[] { File.separator + "aaa" + File.separator + "bbb" + File.separator + "ccc", new String[] { "aaa", "bbb", "ccc" } },
+ };
+
+ int iTest = 0;
+ for ( final Object[] TEST_CASE : TEST_CASES )
+ {
+ ++iTest;
+ final String input = (String) TEST_CASE[0];
+ final String[] expected = (String[]) TEST_CASE[1];
+
+ assertArrayEquals(
+ iTest + " th test failed. input :<" + input + ">",
+ expected,
+ FilenameUtil.getCanonicalFragments( input )
+ );
+ }
+ }
+
+
+ /**
+ * Test {@link FilenameUtil#addTailingPath(String, String)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see FilenameUtil#addTailingPath(String, String)
+ */
+ @Test
+ public
+ void
+ test_addTailingPath()
+ throws Exception
+ {
+ final Object[][] TEST_CASES = new Object[][] {
+ new Object[] { "/aaa/bbb/ccc", "aaa", "/aaa/bbb/ccc/aaa" },
+ new Object[] { "/aaa/bbb/ccc/", "aaa", "/aaa/bbb/ccc/aaa" },
+ new Object[] { "/aaa/bbb/ccc/", "/aaa", "/aaa/bbb/ccc/aaa" },
+ };
+
+ int iTest = 0;
+ for ( final Object[] TEST_CASE : TEST_CASES )
+ {
+ ++iTest;
+ final String path1 = (String) TEST_CASE[0];
+ final String path2 = (String) TEST_CASE[1];
+ final String expected = (String) TEST_CASE[2];
+
+ assertEquals(
+ iTest + " th test failed. input :<" + path1 + "," + path2 + ">",
+ expected,
+ FilenameUtil.addTailingPath( path1, path2 )
+ );
+ }
+ }
+
+ /**
+ * Test {@link FilenameUtil#removeTailingPath(String, int)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see FilenameUtil#removeTailingPath(String, int)
+ */
+ @Test
+ public
+ void
+ test_removeTailingPath()
+ throws Exception
+ {
+ final Object[][] TEST_CASES = new Object[][] {
+ new Object[] { "/aaa/bbb/ccc", 1, "/aaa/bbb" },
+ new Object[] { File.separator + "aaa" + File.separator + "bbb" + File.separator + "ccc", 1, "/aaa/bbb" },
+ };
+
+ int iTest = 0;
+ for ( final Object[] TEST_CASE : TEST_CASES )
+ {
+ ++iTest;
+ final String input = (String) TEST_CASE[0];
+ final int nRemove = (Integer) TEST_CASE[1];
+ final String expected = (String) TEST_CASE[2];
+
+ assertEquals(
+ iTest + " th test failed. input :<" + input + ">",
+ expected,
+ FilenameUtil.removeTailingPath( input, nRemove )
+ );
+ }
+ }
+
+ /**
+ * Test {@link FilenameUtil#getTailingPath(String, int)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see FilenameUtil#getTailingPath(String, int)
+ */
+ @Test
+ public
+ void
+ test_getTailingPath()
+ throws Exception
+ {
+ final Object[][] TEST_CASES = new Object[][] {
+ new Object[] { "/aaa/bbb/ccc", 1, "ccc" },
+ new Object[] { "/aaa/bbb/ccc/", 1, "ccc" },
+ new Object[] { "/aaa/bbb/ccc", 2, "bbb/ccc" },
+ new Object[] { File.separator + "aaa" + File.separator + "bbb" + File.separator + "ccc", 1, "ccc" },
+ };
+
+ int iTest = 0;
+ for ( final Object[] TEST_CASE : TEST_CASES )
+ {
+ ++iTest;
+ final String input = (String) TEST_CASE[0];
+ final int nRemove = (Integer) TEST_CASE[1];
+ final String expected = (String) TEST_CASE[2];
+
+ assertEquals(
+ iTest + " th test failed. input :<" + input + ">",
+ expected,
+ FilenameUtil.getTailingPath( input, nRemove )
+ );
+ }
+ }
+
+ /**
+ * Test {@link FilenameUtil#getFilename(String)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see FilenameUtil#getFilename(String)
+ */
+ @Test
+ public
+ void
+ test_getFilename()
+ throws Exception
+ {
+ final Object[][] TEST_CASES = new Object[][] {
+ new Object[] { "/aaa/bbb/ccc", "ccc" },
+ new Object[] { "/aaa/bbb/ccc.jar", "ccc.jar" },
+ new Object[] { File.separator + "aaa" + File.separator + "bbb" + File.separator + "ccc", "ccc" },
+ };
+
+ int iTest = 0;
+ for ( final Object[] TEST_CASE : TEST_CASES )
+ {
+ ++iTest;
+ final String input = (String) TEST_CASE[0];
+ final String expected = (String) TEST_CASE[1];
+
+ assertEquals(
+ iTest + " th test failed. input :<" + input + ">",
+ expected,
+ FilenameUtil.getFilename( input )
+ );
+ }
+ }
+
+ /**
+ * Test {@link FilenameUtil#getExtension(String)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see FilenameUtil#getExtension(String)
+ */
+ @Test
+ public
+ void
+ test_getExtension()
+ throws Exception
+ {
+ final Object[][] TEST_CASES = new Object[][] {
+ new Object[] { "test.txt", "txt" },
+ new Object[] { "ccc.jar", "jar" },
+ new Object[] { ".aaa", "aaa" },
+ new Object[] { "aaa", "" },
+ };
+
+ int iTest = 0;
+ for ( final Object[] TEST_CASE : TEST_CASES )
+ {
+ ++iTest;
+ final String input = (String) TEST_CASE[0];
+ final String expected = (String) TEST_CASE[1];
+
+ assertEquals(
+ iTest + " th test failed. input :<" + input + ">",
+ expected,
+ FilenameUtil.getExtension( input )
+ );
+ }
+ }
+
+
+}
diff --git a/org.tizen.common/test/src/org/tizen/common/util/FilterIteratorTest.java b/org.tizen.common/test/src/org/tizen/common/util/FilterIteratorTest.java
new file mode 100644
index 000000000..931e4d64e
--- /dev/null
+++ b/org.tizen.common/test/src/org/tizen/common/util/FilterIteratorTest.java
@@ -0,0 +1,70 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* BonYong Lee <bonyong.lee@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+package org.tizen.common.util;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+
+import org.junit.Test;
+
+
+/**
+ * FilterIteratorTest
+ *
+ * Test case for {@link FilterIterator}
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ *
+ * @see FilterIterator
+ */
+public class FilterIteratorTest
+{
+ /**
+ * Test {@link FilterIterator#isAcceptable(Object)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see {@link FilterIterator#isAcceptable(Object)}
+ */
+ @Test
+ public void test_isAcceptable() throws Exception
+ {
+ final ArrayList<String> collection = new ArrayList<String>(
+ Arrays.asList( "Hello", "World", null )
+ );
+ final FilterIterator<String> iterator = new FilterIterator<String>( collection );
+
+ assertTrue( iterator.hasNext() );
+ assertEquals( "Hello", iterator.next() );
+ assertTrue( iterator.hasNext() );
+ assertEquals( "World", iterator.next() );
+ assertFalse( iterator.hasNext() );
+ }
+
+}
diff --git a/org.tizen.common/test/src/org/tizen/common/util/FreeMarkerUtilTest.java b/org.tizen.common/test/src/org/tizen/common/util/FreeMarkerUtilTest.java
new file mode 100644
index 000000000..f1f27729a
--- /dev/null
+++ b/org.tizen.common/test/src/org/tizen/common/util/FreeMarkerUtilTest.java
@@ -0,0 +1,62 @@
+package org.tizen.common.util;
+
+import static org.junit.Assert.*;
+
+import java.io.Writer;
+import java.util.HashMap;
+import java.util.Locale;
+import java.util.Map;
+
+import org.junit.Test;
+
+import freemarker.template.Configuration;
+import freemarker.template.DefaultObjectWrapper;
+import freemarker.template.Template;
+
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+import static org.mockito.Mockito.verify;
+
+
+public class FreeMarkerUtilTest {
+
+ /**
+ * Test {@link FreeMarkerUtil#getDefaultConfiguration()}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see FreeMarkerUtil#getDefaultConfiguration()
+ */
+ @Test
+ public void test_getDefaultConfiguration() throws Exception {
+ Configuration defaultConfiguration = FreeMarkerUtil.getDefaultConfiguration();
+
+ String encoding = defaultConfiguration.getEncoding(Locale.getDefault());
+ assertTrue(encoding.equals("8859_1"));
+
+ assertTrue(defaultConfiguration.getObjectWrapper() instanceof DefaultObjectWrapper);
+ }
+
+ /**
+ * Test {@link FreeMarkerUtil#generateDocument(Map, Configuration, String, Writer)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see FreeMarkerUtil#generateDocument(Map, Configuration, String, Writer)
+ */
+ @Test
+ public void test_generateDocument() throws Exception {
+ final String templateFile = "zz";
+ final Map<String, Object> root = new HashMap<String, Object>();
+ final Writer mockWriter = mock( Writer.class );
+
+ final Configuration mockCfg = mock (Configuration.class);
+ final Template mockTemplate = mock( Template.class );
+ when(mockCfg.getTemplate(templateFile)).thenReturn(mockTemplate);
+
+ FreeMarkerUtil.generateDocument(root, mockCfg, templateFile, mockWriter);
+ verify(mockCfg).getTemplate(templateFile);
+ verify(mockTemplate).process(root, mockWriter);
+ verify(mockWriter).close();
+ }
+}
diff --git a/org.tizen.common/test/src/org/tizen/common/util/HostUtilTest.java b/org.tizen.common/test/src/org/tizen/common/util/HostUtilTest.java
new file mode 100644
index 000000000..1b81a55e1
--- /dev/null
+++ b/org.tizen.common/test/src/org/tizen/common/util/HostUtilTest.java
@@ -0,0 +1,117 @@
+package org.tizen.common.util;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+public class HostUtilTest {
+
+ private String packageName = HostUtilTest.class.getPackage().getName().replace('.', '/');
+ private String fileName = "test";
+ private String filePath = ClassLoader.getSystemResource(packageName + '/').getPath();
+ private String fullPath = filePath + fileName;
+
+ @Before
+ public void setUp() {
+
+ }
+
+ @After
+ public void tearDown() {
+
+ }
+
+ /**
+ * Test {@link HostUtil#getContents( String)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see HostUtil#getContents( String)
+ */
+ @Test
+ public void test_getContents() throws Exception {
+ Assert.notNull(HostUtil.getContents(fullPath));
+ Assert.isNull(HostUtil.getContents(null));
+ Assert.isNull(HostUtil.getContents("nullPath"));
+ }
+
+ /**
+ * Test {@link HostUtil#exists( String)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see HostUtil#exists( String)
+ */
+ @Test
+ public void test_exists() throws Exception {
+ Assert.isTrue(HostUtil.exists(fullPath));
+ Assert.isFalse(HostUtil.exists(null));
+ Assert.isFalse(HostUtil.exists("nullPath"));
+ }
+
+ /**
+ * Test {@link HostUtil#execute( String)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see HostUtil#execute( String)
+ */
+ @Test
+ public void test_execute() throws Exception {
+ Assert.isTrue(HostUtil.execute("cd"));
+ Assert.isFalse(HostUtil.execute(null));
+ Assert.isFalse(HostUtil.execute("notcommand"));
+ }
+
+ /**
+ * Test {@link HostUtil#batchExecute( String)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see HostUtil#batchExecute( String)
+ */
+ @Test
+ public void test_batchExecute() throws Exception {
+ Assert.isFalse(HostUtil.batchExecute(null));
+ Assert.isTrue(HostUtil.batchExecute("cd"));
+ Assert.isFalse(HostUtil.batchExecute("notcommand"));
+ }
+
+ /**
+ * Test {@link HostUtil#returnExecute( String)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see HostUtil#returnExecute( String)
+ */
+ @Test
+ public void test_returnExecute1() throws Exception {
+ Assert.isNull(HostUtil.returnExecute(null));
+ Assert.notNull(HostUtil.returnExecute("cd"));
+ }
+
+ /**
+ * Test {@link HostUtil#returnExecute( String, String)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see HostUtil#returnExecute( String, String)
+ */
+ @Test
+ public void test_returnExecute2() throws Exception {
+ Assert.isNull(HostUtil.returnExecute(null, filePath));
+ Assert.notNull(HostUtil.returnExecute("cd", filePath));
+ }
+
+ /**
+ * Test {@link HostUtil#executeWithConsole( String, String)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see HostUtil#executeWithConsole( String, String)
+ */
+ @Test(expected = Exception.class)
+ public void test_executeWithConsole() throws Exception {
+ HostUtil.executeWithConsole("notcommand", "viewname");
+ }
+}
diff --git a/org.tizen.common/test/src/org/tizen/common/util/IOUtilTest.java b/org.tizen.common/test/src/org/tizen/common/util/IOUtilTest.java
new file mode 100644
index 000000000..4254e7f86
--- /dev/null
+++ b/org.tizen.common/test/src/org/tizen/common/util/IOUtilTest.java
@@ -0,0 +1,242 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* BonYong Lee <bonyong.lee@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/package org.tizen.common.util;
+
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.Closeable;
+import java.io.Flushable;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.Reader;
+import java.io.StringReader;
+import java.io.StringWriter;
+
+import org.junit.Test;
+
+
+/**
+ * IOUtilTest.
+ *
+ * Test case for {@link IOUtil}
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ *
+ * @see IOUtil
+ *
+ */
+public class IOUtilTest
+{
+ /**
+ * Test {@link IOUtil#tryClose(Object...)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see {@link IOUtil#tryClose(Object...)}
+ */
+ @Test
+ public
+ void
+ test_tryClose()
+ throws Exception
+ {
+ final Object[][] TEST_CASES = new Object[][] {
+ new Object[] { null },
+ new Object[] { new Closeable[] { new ByteArrayOutputStream(), new ByteArrayOutputStream() } },
+ new Object[] { new Closeable[] { null } },
+ new Object[] { new Closeable[] { null, null, null } },
+ new Object[] { new Closeable[] { null, new ByteArrayOutputStream() } },
+ new Object[] { new Closeable[] { new ByteArrayOutputStream(), null } },
+ new Object[] { new Closeable[] { new ByteArrayOutputStream(), null } },
+ new Object[] { new Closeable[] { new ByteArrayOutputStream(), null, new ByteArrayOutputStream() } },
+ };
+
+ int iTestCase = 0;
+ for ( final Object[] TEST_CASE : TEST_CASES )
+ {
+ ++iTestCase;
+
+ try
+ {
+ IOUtil.tryClose( TEST_CASE[0] );
+ }
+ catch ( final Throwable e )
+ {
+ fail( iTestCase + " th test case failed" );
+ }
+ }
+
+ /* Mock Object using Mockito */
+ InputStream in = mock( InputStream.class );
+ IOUtil.tryClose( in );
+ verify( in ).close();
+ }
+
+ /**
+ * Test {@link IOUtil#tryFlush(Flushable...)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see {@link IOUtil#tryFlush(Flushable...)}
+ */
+ @Test
+ public
+ void
+ test_tryFlush()
+ throws Exception
+ {
+ final Object[][] TEST_CASES = new Object[][] {
+ new Object[] { null },
+ new Object[] { new Flushable[] { new ByteArrayOutputStream(), new ByteArrayOutputStream() } },
+ new Object[] { new Flushable[] { null } },
+ new Object[] { new Flushable[] { null, null, null } },
+ new Object[] { new Flushable[] { null, new ByteArrayOutputStream() } },
+ new Object[] { new Flushable[] { new ByteArrayOutputStream(), null } },
+ new Object[] { new Flushable[] { new ByteArrayOutputStream(), null } },
+ new Object[] { new Flushable[] { new ByteArrayOutputStream(), null, new ByteArrayOutputStream() } },
+ };
+
+ int iTestCase = 0;
+ for ( final Object[] TEST_CASE : TEST_CASES )
+ {
+ ++iTestCase;
+ final Flushable[] flushables = (Flushable[]) TEST_CASE[0];
+
+ try
+ {
+ IOUtil.tryFlush( flushables );
+ }
+ catch ( final Throwable e )
+ {
+ fail( iTestCase + " th test case failed" );
+ }
+ }
+
+ /* Mock Object using Mockito */
+ OutputStream out = mock( OutputStream.class );
+ IOUtil.tryFlush( out );
+ verify( out ).flush();
+ }
+
+
+ /**
+ * Test {@link IOUtil#redirect(InputStream, OutputStream)},
+ * {@link IOUtil#redirect(java.io.Reader, StringBuffer)},
+ * {@link IOUtil#redirect(java.io.Reader, StringBuilder)}
+ * and {@link IOUtil#redirect(java.io.Reader, java.io.Writer)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see IOUtil#redirect(InputStream, OutputStream)
+ * @see IOUtil#redirect(java.io.Reader, StringBuffer)
+ * @see IOUtil#redirect(java.io.Reader, StringBuilder)
+ * @see IOUtil#redirect(java.io.Reader, java.io.Writer)
+ */
+ @Test
+ public
+ void
+ test_redirect()
+ throws Exception
+ {
+ final String[] TEST_CASES = new String[] {
+ "Hello, World",
+ };
+
+ int iTestCase = 0;
+ for ( final String TEST_CASE : TEST_CASES )
+ {
+ ++iTestCase;
+
+ final ByteArrayInputStream in = new ByteArrayInputStream( TEST_CASE.getBytes() );
+ final ByteArrayOutputStream out = new ByteArrayOutputStream();
+ IOUtil.redirect( in, out );
+ assertArrayEquals( iTestCase + " th test case failed :" + TEST_CASE, TEST_CASE.getBytes(), out.toByteArray() );
+
+ final StringReader reader = new StringReader( TEST_CASE );
+ final StringWriter writer = new StringWriter();
+ IOUtil.redirect( reader, writer );
+ assertEquals( iTestCase + " th test case failed :" + TEST_CASE, TEST_CASE, writer.toString() );
+
+ final StringReader reader2 = new StringReader( TEST_CASE );
+ final StringBuilder builder = new StringBuilder();
+ IOUtil.redirect( reader2, builder );
+ assertEquals( iTestCase + " th test case failed :" + TEST_CASE, TEST_CASE, builder.toString() );
+
+ final StringReader reader3 = new StringReader( TEST_CASE );
+ final StringBuffer buffer = new StringBuffer();
+ IOUtil.redirect( reader3, buffer );
+ assertEquals( iTestCase + " th test case failed :" + TEST_CASE, TEST_CASE, buffer.toString() );
+
+ }
+ }
+
+ /**
+ * Test {@link IOUtil#getBytes(InputStream)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see IOUtil#getBytes(InputStream)
+ */
+ @Test
+ public
+ void
+ test_getBytes()
+ throws Exception
+ {
+ assertNotNull( IOUtil.getBytes( new ByteArrayInputStream( "Hello".getBytes() ) ) );
+ assertTrue( 0 < IOUtil.getBytes( new ByteArrayInputStream( "Hello".getBytes() ) ).length );
+ }
+
+
+ /**
+ * Test {@link IOUtil#getString(java.io.Reader)},
+ * {@link IOUtil#getString(java.io.Reader, boolean)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see IOUtil#getString(java.io.Reader)
+ * @see IOUtil#getString(java.io.Reader, boolean)
+ */
+ @Test
+ public
+ void
+ test_getString()
+ throws Exception
+ {
+ assertEquals( "", IOUtil.getString( (Reader) null ) );
+ assertEquals( "Hello", IOUtil.getString( new StringReader("Hello" ) ) );
+
+ assertEquals( "", IOUtil.getString( (StringReader) null, true ) );
+ assertEquals( "Hello", IOUtil.getString( new StringReader("Hello" ), true ) );
+ }
+
+}
diff --git a/org.tizen.common/test/src/org/tizen/common/util/ImageUtilTest.java b/org.tizen.common/test/src/org/tizen/common/util/ImageUtilTest.java
new file mode 100644
index 000000000..5894536fc
--- /dev/null
+++ b/org.tizen.common/test/src/org/tizen/common/util/ImageUtilTest.java
@@ -0,0 +1,276 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* BonYong Lee <bonyong.lee@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+package org.tizen.common.util;
+
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import java.net.URL;
+
+import org.eclipse.core.runtime.Plugin;
+import org.eclipse.jface.resource.ImageDescriptor;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.graphics.ImageData;
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mockito;
+import org.osgi.framework.Bundle;
+import org.tizen.common.SurrogateWithArgument;
+
+
+/**
+ * ImageUtilTest
+ *
+ * Test case for {@link ImageUtil}
+ *
+ * LookAtMe : "SetUp" & "TearDown" pattern for test
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ *
+ * @see ImageUtil
+ */
+public class ImageUtilTest
+{
+ /**
+ * Property key for URL handler
+ */
+ protected static final String PROP_PKG = "java.protocol.handler.pkgs";
+
+ protected static final String TEST_PATH = ImageUtilTest.class.getSimpleName() + ".png";
+ protected static final String TEST_URL = "cp:///" + TEST_PATH;
+
+ /**
+ * Old property value for URL handler
+ */
+ protected String oldConfig;
+
+ /**
+ * Set up URL handler before test
+ */
+ @SuppressWarnings("unchecked")
+ @Before
+ public void setUp()
+ {
+ oldConfig = System.getProperty( PROP_PKG );
+ System.setProperty( PROP_PKG, "org.tizen.common.util.url" );
+
+ ImageUtil.platformSurrogate = mock(SurrogateWithArgument.class);
+ ImageUtil.pluginSurrogate = mock(SurrogateWithArgument.class);
+
+ }
+
+ /**
+ * Restore URL handler after test
+ */
+ @After
+ public void tearDown()
+ {
+ ImageUtil.pluginSurrogate = null;
+ ImageUtil.platformSurrogate = null;
+
+ if ( null == oldConfig )
+ {
+ System.getProperties().remove( PROP_PKG );
+ return ;
+ }
+ System.setProperty( PROP_PKG, oldConfig );
+ }
+
+ /**
+ * Test {@link ImageUtil#getImageDescriptor(Bundle, String)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see ImageUtil#getImageDescriptor(Bundle, String)
+ */
+ @Test
+ public
+ void
+ test_getImageDescriptor1()
+ throws Exception
+ {
+ final Bundle bundleMockup = mock( Bundle.class );
+ final URL virtualPathUrl = new URL( TEST_URL );
+
+ when( bundleMockup.getEntry( TEST_PATH ) ).thenReturn( virtualPathUrl );
+ final ImageDescriptor imgDes =
+ ImageUtil.getImageDescriptor( bundleMockup, TEST_PATH );
+
+ Assert.assertNotNull(imgDes.createImage(false));
+ }
+
+ /**
+ * Test {@link ImageUtil#getImageDescriptor(String, String)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see ImageUtil#getImageDescriptor(String, String)
+ */
+ @Test
+ public void test_getImageDescriptor2() throws Exception {
+ final Bundle bundleMockup = mock( Bundle.class );
+ final URL virtualPathUrl = new URL( TEST_URL );
+ when( bundleMockup.getEntry( TEST_PATH ) ).thenReturn( virtualPathUrl );
+ final String pluginID = "testID";
+ when(ImageUtil.platformSurrogate.getAdapter(pluginID)).thenReturn(bundleMockup);
+ final ImageDescriptor imgDes = ImageUtil.getImageDescriptor(pluginID, TEST_PATH);
+
+ final Image img = imgDes.createImage(false);
+
+ Assert.assertNotNull(img);
+ }
+
+ /**
+ * Test {@link ImageUtil#getImageDescriptor(Plugin, String)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see ImageUtil#getImageDescriptor(Plugin, String)
+ */
+ @Test
+ public void test_getImageDescriptor3() throws Exception {
+ final Bundle bundleMockup = mock( Bundle.class );
+ final URL virtualPathUrl = new URL( TEST_URL );
+ when( bundleMockup.getEntry( TEST_PATH ) ).thenReturn( virtualPathUrl );
+ final Plugin pluginMockup = mock(Plugin.class);
+ when(ImageUtil.pluginSurrogate.getAdapter(pluginMockup)).thenReturn(bundleMockup);
+ final ImageDescriptor imgDes = ImageUtil.getImageDescriptor(pluginMockup, TEST_PATH);
+ final Image img = imgDes.createImage(false);
+
+ Assert.assertNotNull(img);
+ }
+
+ /**
+ * Test {@link ImageUtil#getImage(ImageDescriptor)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see ImageUtil#getImage(ImageDescriptor)
+ */
+ @Test
+ public void test_getImage1() throws Exception {
+ final ImageDescriptor imgMock = mock(ImageDescriptor.class);
+
+ ImageUtil.getImage(imgMock);
+ Mockito.verify(imgMock).createImage();
+ }
+
+ /**
+ * Test {@link ImageUtil#getImageData(ImageDescriptor)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see ImageUtil#getImageData(ImageDescriptor)
+ */
+ @Test
+ public void test_getImageData1() throws Exception {
+ final ImageDescriptor imgMock = mock(ImageDescriptor.class);
+
+ ImageUtil.getImageData(imgMock);
+ Mockito.verify(imgMock).getImageData();
+ }
+
+ /**
+ * Test {@link ImageUtil#getImage(Plugin, String)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see ImageUtil#getImage(Plugin, String)
+ */
+ @Test
+ public void test_getImage2() throws Exception {
+ final Bundle bundleMockup = mock( Bundle.class );
+ final URL virtualPathUrl = new URL( TEST_URL );
+ when( bundleMockup.getEntry( TEST_PATH ) ).thenReturn( virtualPathUrl );
+ final Plugin pluginMockup = mock(Plugin.class);
+ when(ImageUtil.pluginSurrogate.getAdapter(pluginMockup)).thenReturn(bundleMockup);
+
+ Image img = ImageUtil.getImage(pluginMockup, TEST_PATH);
+
+ Assert.assertNotNull(img);
+ }
+
+ /**
+ * Test {@link ImageUtil#getImageData(Plugin, String)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see ImageUtil#getImageData(Plugin, String)
+ */
+ @Test
+ public void test_getImageData2() throws Exception {
+ final Bundle bundleMockup = mock( Bundle.class );
+ final URL virtualPathUrl = new URL( TEST_URL );
+ when( bundleMockup.getEntry( TEST_PATH ) ).thenReturn( virtualPathUrl );
+ final Plugin pluginMockup = mock(Plugin.class);
+ when(ImageUtil.pluginSurrogate.getAdapter(pluginMockup)).thenReturn(bundleMockup);
+
+ ImageData imgData = ImageUtil.getImageData(pluginMockup, TEST_PATH);
+
+ Assert.assertNotNull( imgData );
+ }
+
+ /**
+ * Test {@link ImageUtil#getImage(String, String)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see ImageUtil#getImage(String, String)
+ */
+ @Test
+ public void test_getImage3() throws Exception {
+ final String pluginID = "testID";
+ final Bundle bundleMockup = mock( Bundle.class );
+ final URL virtualPathUrl = new URL( TEST_URL );
+ when( bundleMockup.getEntry( TEST_PATH ) ).thenReturn( virtualPathUrl );
+ when(ImageUtil.platformSurrogate.getAdapter(pluginID)).thenReturn(bundleMockup);
+
+ Image img = ImageUtil.getImage(pluginID, TEST_PATH);
+
+ Assert.assertNotNull(img);
+ }
+
+ /**
+ * Test {@link ImageUtil#getImageData(String, String)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see ImageUtil#getImageData(String, String)
+ */
+ @Test
+ public void test_getImageData3() throws Exception {
+ final String pluginID = "testID";
+ final Bundle bundleMockup = mock( Bundle.class );
+ final URL virtualPathUrl = new URL( TEST_URL );
+ when( bundleMockup.getEntry( TEST_PATH ) ).thenReturn( virtualPathUrl );
+ when(ImageUtil.platformSurrogate.getAdapter(pluginID)).thenReturn(bundleMockup);
+
+ ImageData imgData = ImageUtil.getImageData(pluginID, TEST_PATH);
+ Assert.assertNotNull( imgData );
+ }
+
+}
diff --git a/org.tizen.common/test/src/org/tizen/common/util/ImageUtilTest.png b/org.tizen.common/test/src/org/tizen/common/util/ImageUtilTest.png
new file mode 100644
index 000000000..d70328403
--- /dev/null
+++ b/org.tizen.common/test/src/org/tizen/common/util/ImageUtilTest.png
Binary files differ
diff --git a/org.tizen.common/test/src/org/tizen/common/util/LocalPortCheckerTest.java b/org.tizen.common/test/src/org/tizen/common/util/LocalPortCheckerTest.java
new file mode 100644
index 000000000..549e8e750
--- /dev/null
+++ b/org.tizen.common/test/src/org/tizen/common/util/LocalPortCheckerTest.java
@@ -0,0 +1,105 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* BonYong Lee <bonyong.lee@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+package org.tizen.common.util;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import java.util.Random;
+
+import org.junit.Test;
+
+
+/**
+ * LocalPortCheckerTest
+ *
+ * Test case for {@link LocalPortChecker}
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ *
+ * @see LocalPortChecker
+ */
+public class LocalPortCheckerTest
+{
+
+ /**
+ * Test {@link LocalPortChecker#isPortInRange(int)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see LocalPortChecker#isPortInRange(int)
+ */
+ @Test
+ public void test_isPortInRange() throws Exception
+ {
+ for ( int i = 0 ; i < 65536 ; ++i )
+ {
+ assertTrue( LocalPortChecker.isPortInRange( i ) );
+ }
+ assertFalse( LocalPortChecker.isPortInRange( -1 ) );
+ assertFalse( LocalPortChecker.isPortInRange( 65536 ) );
+ }
+
+ /**
+ * Test {@link LocalPortChecker#isPortAvailable(int)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see LocalPortChecker#isPortAvailable(int)
+ */
+ @Test
+ public void test_isPortAvailable() throws Exception
+ {
+ assertFalse( LocalPortChecker.isPortAvailable( -1 ) );
+ assertTrue( LocalPortChecker.isPortAvailable( 0 ) );
+ assertFalse( LocalPortChecker.isPortAvailable( 65538 ) );
+ }
+
+ /**
+ * Test {@link LocalPortChecker#getAvailableLocalPort(int, int)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see LocalPortChecker#getAvailableLocalPort(int, int)
+ */
+ @Test
+ public void test_getAvailableLocalPort() throws Exception
+ {
+ final Random r = new Random( System.currentTimeMillis() );
+ final int MIN = 10000;
+ final int MAX = 65535;
+
+ for ( int i = 0 ; i < 1000 ; ++i )
+ {
+ final int basePort = r.nextInt( MAX - MIN ) + MIN;
+ final int inc = r.nextInt( 5 ) - 2;
+
+ int port = LocalPortChecker.getAvailableLocalPort( inc, basePort );
+ assertEquals( "base port :" + basePort + ", inc :" + inc + ", real port :" + port, ( basePort == port ), LocalPortChecker.isPortAvailable( basePort ) );
+ }
+ }
+
+}
diff --git a/org.tizen.common/test/src/org/tizen/common/util/MapUtilTest.java b/org.tizen.common/test/src/org/tizen/common/util/MapUtilTest.java
new file mode 100644
index 000000000..58feb4b77
--- /dev/null
+++ b/org.tizen.common/test/src/org/tizen/common/util/MapUtilTest.java
@@ -0,0 +1,205 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* ChangHyun Lee <changhyun1.lee@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+
+package org.tizen.common.util;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Properties;
+
+import org.junit.Test;
+
+
+/**
+ * MapUtilTest.
+ *
+ * Test case for {@link MapUtil}
+ *
+ * @author Changhyun Lee{@literal <changhyun1.lee@samsung.com>} (S-Core)
+ *
+ * @see MapUtil
+ *
+ */
+public class MapUtilTest {
+ /**
+ * Test {@link MapUtil#length(Map)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see MapUtil#length(Map)
+ */
+ @Test
+ public void test_length() throws Exception {
+ assertEquals(0, MapUtil.length(null));
+ Map<String, String> map = new HashMap<String, String>();
+ map.put("aaa", "111");
+ map.put("bbb", "222");
+ assertEquals(map.size(), MapUtil.length(map));
+ }
+
+ /**
+ * Test {@link MapUtil#isEmpty(Map)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see MapUtil#isEmpty(Map)
+ */
+ @Test
+ public void test_isEmpty() throws Exception {
+ assertTrue(MapUtil.isEmpty(null));
+
+ Map<String, String> map = new HashMap<String, String>();
+ assertTrue(MapUtil.isEmpty(map));
+
+ map.put("aaa", "111");
+ map.put("bbb", "222");
+ assertFalse(MapUtil.isEmpty(map));
+ }
+
+ /**
+ * Test {@link MapUtil#asMap(Object[], Object[])
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see MapUtil#asMap(Object[], Object[])
+ */
+ @Test
+ public void test_asMap1() throws Exception {
+ String[] keys = {"aaa", "bbb", "ccc"};
+ String[] values = {"111", "222", "333"};
+ String[] values2 = {"111", "222"};
+
+ assertTrue(MapUtil.asMap(null, null) != null);
+ assertTrue(MapUtil.asMap(keys, null) != null);
+ assertTrue(MapUtil.asMap(null, values) != null);
+
+ Map<String, String> map1 = MapUtil.asMap(keys, values);
+ assertEquals(map1.size(), 3);
+ Map<String, String> map2 = MapUtil.asMap(keys, values2);
+ assertEquals(map2.size(), 2);
+ Map<String, String> map3 = MapUtil.asMap(null, null);
+ assertEquals(map3.size(), 0);
+ }
+
+ /**
+ * Test {@link MapUtil#asMap(Object[][] objs)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see {@link MapUtil#asMap(Object[][] objs)}
+ */
+ @Test
+ public void test_asMap2() throws Exception {
+ final Object[][] TEST_CASES = new Object[][] {
+ new Object[] { "aaa", "111" },
+ new Object[] { "bbb", "222" },
+ };
+
+ final Object[][] TEST_CASES2 = new Object[][] {
+ new Object[] {"aaa"},
+ new Object[] {null},
+ new Object[] { "aaa", "111" },
+ new Object[] { "bbb", "222" },
+ };
+
+ assertTrue(MapUtil.asMap(null) != null);
+
+ Map<Object, Object> map1 = MapUtil.asMap(TEST_CASES);
+ assertTrue(map1 != null);
+ assertEquals(map1.size(), 2);
+ int iTestCase = 0;
+ for ( final Object[] TEST_CASE : TEST_CASES ) {
+ ++iTestCase;
+ final Object[] object = TEST_CASE;
+ assertEquals(iTestCase + " th test case", object[1], map1.get(object[0]));
+ }
+
+ Map<Object, Object> map2 = MapUtil.asMap(TEST_CASES2);
+ assertTrue(map2 != null);
+ assertEquals(map2.size(), 2);
+ }
+
+ /**
+ * Test {@link MapUtil#mergePropertiesIntoMap(Properties, Map)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see MapUtil#mergePropertiesIntoMap(Properties, Map)
+ */
+ @Test
+ public void test_mergePropertiesIntoMap() throws Exception {
+ Properties properties = new Properties();
+ properties.setProperty("aaa", "111");
+ properties.setProperty("bbb", "222");
+
+ HashMap<Object, Object> map = new HashMap<Object, Object>();
+
+ try {
+ MapUtil.mergePropertiesIntoMap(null, null);
+ fail( "mergePropertiesIntoMap must throw exception" );
+ } catch (Exception e) {
+ }
+
+ try {
+ MapUtil.mergePropertiesIntoMap(properties, null);
+ fail( "mergePropertiesIntoMap must throw exception" );
+ } catch (Exception e) {
+ }
+
+ MapUtil.mergePropertiesIntoMap(null, map);
+
+ assertEquals(map.size(), 0);
+ MapUtil.mergePropertiesIntoMap(properties, map);
+ assertEquals(map.size(), 2);
+ assertEquals(properties.getProperty("aaa"), map.get("aaa"));
+ assertEquals(properties.getProperty("bbb"), map.get("bbb"));
+ }
+
+ /**
+ * Test {@link MapUtil#toString(Map)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see MapUtil#toString(Map)
+ */
+ @Test
+ public void test_toString() throws Exception {
+ final Map<String, String> testTarget = new HashMap<String, String>();
+ testTarget.put( "testKey", "testValue" );
+
+ final String string = MapUtil.toString( testTarget );
+
+ assertTrue( string.contains( "testKey" ) );
+ assertTrue( string.contains( "testValue" ) );
+
+ assertNotNull( MapUtil.toString( null ) );
+ }
+}
diff --git a/org.tizen.common/src/org/tizen/common/control/NotSupportedTypeException.java b/org.tizen.common/test/src/org/tizen/common/util/MockRunner.java
index 64cfa87c8..a4d73ade0 100644
--- a/org.tizen.common/src/org/tizen/common/control/NotSupportedTypeException.java
+++ b/org.tizen.common/test/src/org/tizen/common/util/MockRunner.java
@@ -4,7 +4,7 @@
* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
*
* Contact:
-* Kangho Kim <kh5325.kim@samsung.com>
+* BonYong Lee <bonyong.lee@samsung.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -22,14 +22,25 @@
* - S-Core Co., Ltd
*
*/
-package org.tizen.common.control;
+package org.tizen.common.util;
-public class NotSupportedTypeException extends Exception {
+/**
+ * MockRunner
+ *
+ * Mock object for {@link Runnable}
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ */
+public class
+MockRunner
+implements Runnable
+{
+
+ boolean bExecute = false;
- public NotSupportedTypeException(){
- super();
- }
- public NotSupportedTypeException(String message){
- super(message);
+ public void run() {
+ ThreadUtil.trySleep( 50 );
+ bExecute = true;
}
+
}
diff --git a/org.tizen.common/test/src/org/tizen/common/util/ObjectUtilTest.java b/org.tizen.common/test/src/org/tizen/common/util/ObjectUtilTest.java
new file mode 100644
index 000000000..23c40ecdb
--- /dev/null
+++ b/org.tizen.common/test/src/org/tizen/common/util/ObjectUtilTest.java
@@ -0,0 +1,140 @@
+/*
+ * Common
+ *
+ * Copyright (c) 2000 - 2012 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * BonYong Lee <bonyong.lee@samsung.com>
+ * TaeYoung son <taeyoung2.son@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common.util;
+
+import static org.junit.Assert.assertEquals;
+
+import org.junit.Test;
+
+/**
+ * ObjectUtilTest.
+ *
+ * Helper related to {@link ObjectUtil}
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ * @author TaeYoung Son{@literal <taeyoung2.son@samsung.com>} (S-Core)
+ *
+ * @see ObjectUtil
+ *
+ */
+public class ObjectUtilTest {
+ @Test
+ public void test_nvl() throws Exception {
+ final Object[][] TEST_CASES = new Object[][] {
+ new Object[] { null, null },
+ new Object[] { new Object[] { null }, null },
+ new Object[] { new Object[] { "hello" }, "hello" },
+ new Object[] { new Object[] { null, null, "b" }, "b" },
+ new Object[] { new Object[] { null, "a", "b" }, "a" } };
+
+ int nTestCase = 0;
+ for (final Object[] TEST_CASE : TEST_CASES) {
+ nTestCase++;
+ final Object[] input = (Object[]) TEST_CASE[0];
+ final Object expected = TEST_CASE[1];
+
+ assertEquals(nTestCase + "th test case failed." + "\n input : "
+ + input + "\n", expected, ObjectUtil.nvl(input));
+ }
+ }
+
+ @Test
+ public void test_equals() {
+ final Object[][] TEST_CASES = new Object[][] {
+ new Object[] { null, null, true },
+ new Object[] { null, "a", false },
+ new Object[] { "a", null, false },
+ new Object[] { "a", "a", true },
+ new Object[] { "a", new String("a"), true },
+ new Object[] { "a", "b", false },
+ new Object[] { new char[] { 'a', 'a', 'b' },
+ new char[] { 'a', 'a', 'b' }, true },
+ new Object[] { new int[] { 1, 2, 3 }, new int[] { 1, 3, 2 },
+ false } };
+
+ int nTestCase = 0;
+ for (final Object[] TEST_CASE : TEST_CASES) {
+ nTestCase++;
+ final Object input1 = (Object) TEST_CASE[0];
+ final Object input2 = (Object) TEST_CASE[1];
+ final Object expected = TEST_CASE[2];
+ assertEquals(nTestCase + "th test case failed."
+ + "\n first input : " + input1 + "\n" + "second input : "
+ + input2 + "\n", expected,
+ ObjectUtil.equals(input1, input2));
+ }
+ }
+
+ @Test
+ public void test_hexFormat() {
+ final Object[][] TEST_CASES = new Object[][] {
+ new Object[] { 0, 0, "0" },
+ new Object[] { 0, 2, "00" },
+ new Object[] { 15, 1, "f" },
+ new Object[] { 15, 3, "00f" },
+ new Object[] { 2147483647, 10, "007fffffff" },
+ new Object[] { -2147483647, 10, "0080000001" },
+ new Object[] { -1, 1, "ffffffff" }
+ };
+
+ int nTestCase = 0;
+ for (final Object[] TEST_CASE : TEST_CASES) {
+ nTestCase++;
+ final Object input1 = TEST_CASE[0];
+ final Object input2 = TEST_CASE[1];
+ final Object expected = TEST_CASE[2];
+
+ assertEquals(nTestCase + "th test case failed."
+ + "\n first input : " + input1.toString() + "\n" + "second input : "
+ + input2.toString() + "\n", (String)expected,
+ ObjectUtil.hexFormat((Integer)input1, ((Integer)input2).intValue()));
+ }
+
+ }
+
+ @Test
+ public void test_toString() {
+ final Object[][] TEST_CASES = new Object[][] {
+ new Object[] { null, "<<null>>" },
+ new Object[] { "null", "String@C587" },
+ new Object[] { "a", "String@0061" },
+ new Object[] { "A", "String@0041" },
+ new Object[] { 1, "Integer@0001" },
+ new Object[] { 10, "Integer@000A" },
+ new Object[] { -1, "Integer@FFFF" },
+ };
+
+ int nTestCase = 0;
+ for (final Object[] TEST_CASE : TEST_CASES) {
+ nTestCase++;
+ final Object input = TEST_CASE[0];
+ final Object expected = TEST_CASE[1];
+
+ assertEquals(nTestCase + "th test case failed." + "\n input : "
+ + input + "\n", expected, ObjectUtil.toString(input));
+ }
+ }
+}
diff --git a/org.tizen.common/test/src/org/tizen/common/util/ParsingUtilTest.java b/org.tizen.common/test/src/org/tizen/common/util/ParsingUtilTest.java
new file mode 100644
index 000000000..f456715df
--- /dev/null
+++ b/org.tizen.common/test/src/org/tizen/common/util/ParsingUtilTest.java
@@ -0,0 +1,108 @@
+/*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common.util;
+
+import static org.junit.Assert.assertEquals;
+
+import org.junit.Test;
+
+
+/**
+ * ParsingUtilTest
+ *
+ * Test case for {@link ParsingUtil}
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ *
+ * @see ParsingUtil
+ */
+public class ParsingUtilTest
+{
+ /**
+ * Test {@link ParsingUtil#parseBoolean(String, boolean)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see ParsingUtil#parseBoolean(String, boolean)
+ */
+ @Test
+ public void test_parseBoolean() throws Exception
+ {
+ assertEquals( true, ParsingUtil.parseBoolean( "true", false ) );
+ assertEquals( false, ParsingUtil.parseBoolean( null, false ) );
+ assertEquals( true, ParsingUtil.parseBoolean( null, true ) );
+ assertEquals( false, ParsingUtil.parseBoolean( "xxxx", false ) );
+ assertEquals( true, ParsingUtil.parseBoolean( "xxxx", true ) );
+ assertEquals( true, ParsingUtil.parseBoolean( "Y", false ) );
+ assertEquals( true, ParsingUtil.parseBoolean( "1", false ) );
+ }
+
+ /**
+ * Test {@link ParsingUtil#parseInt(String, int)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see ParsingUtil#parseInt(String, int)
+ */
+ @Test
+ public void test_parseInt() throws Exception
+ {
+ assertEquals( 3, ParsingUtil.parseInt( "3", 0 ) );
+ assertEquals( 2, ParsingUtil.parseInt( "2", 0 ) );
+ assertEquals( 16, ParsingUtil.parseInt( "0x10", 0 ) );
+ assertEquals( 8, ParsingUtil.parseInt( "010", 0 ) );
+ }
+
+ /**
+ * Test {@link ParsingUtil#parseLong(String, long)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see ParsingUtil#parseLong(String, long)
+ */
+ @Test
+ public void test_parseLong() throws Exception
+ {
+ assertEquals( 3, ParsingUtil.parseLong( "3", 0 ) );
+ assertEquals( 2, ParsingUtil.parseLong( "2", 0 ) );
+ assertEquals( 16, ParsingUtil.parseLong( "0x10", 0 ) );
+ assertEquals( 8, ParsingUtil.parseLong( "010", 0 ) );
+ }
+
+ /**
+ * Test {@link ParsingUtil#parseDouble(String, double)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see ParsingUtil#parseDouble(String, double)
+ */
+ @Test
+ public void test_parseDouble() throws Exception
+ {
+ assertEquals( 3.0, ParsingUtil.parseDouble( "3", 0 ), 0 );
+ assertEquals( 2.0, ParsingUtil.parseDouble( "2", 0 ), 0 );
+ }
+
+}
diff --git a/org.tizen.common/test/src/org/tizen/common/util/PluginUtilTest.java b/org.tizen.common/test/src/org/tizen/common/util/PluginUtilTest.java
new file mode 100644
index 000000000..5c1f6ee78
--- /dev/null
+++ b/org.tizen.common/test/src/org/tizen/common/util/PluginUtilTest.java
@@ -0,0 +1,111 @@
+package org.tizen.common.util;
+
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import org.eclipse.core.runtime.IConfigurationElement;
+import org.eclipse.core.runtime.IExtension;
+import org.eclipse.core.runtime.IExtensionPoint;
+import org.eclipse.core.runtime.IExtensionRegistry;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mockito;
+import org.tizen.common.Surrogate;
+
+/**
+ * PluginUtilTest.
+ *
+ * Test case for {@link PluginUtil}
+ *
+ * @author Ho Namkoong{@literal <ho.namkoong@samsung.com>} (S-Core)
+ *
+ * @see PluginUtil
+ */
+public class PluginUtilTest {
+
+ /**
+ * mock up test extension point id
+ */
+ private static final String TEST_EXT_ID = "test-ep";
+
+ /**
+ * mock up test class id
+ */
+ private static final String TEST_CLS_ID = "test-class";
+
+ @SuppressWarnings("unchecked")
+ @Before
+ public void setUp() throws Exception {
+ PluginUtil.platformSurrogate = mock(Surrogate.class);
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ PluginUtil.platformSurrogate = null;
+ }
+
+ /**
+ * Test {@link PluginUtil#loadClasses(String)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see PluginUtil#loadClasses(String)
+ */
+ @Test
+ public void testLoadClasses() throws Exception {
+
+ final IExtensionRegistry registry = mock(IExtensionRegistry.class);
+ when(PluginUtil.platformSurrogate.getAdapter()).thenReturn(registry);
+
+ final IExtensionPoint ep = mock(IExtensionPoint.class);
+ when(registry.getExtensionPoint(TEST_EXT_ID)).thenReturn(ep);
+
+ IExtension[] exts = new IExtension[1];
+ when(ep.getExtensions()).thenReturn(exts);
+
+ final IExtension ext = mock(IExtension.class);
+ exts[0] = ext;
+
+ final IConfigurationElement config = mock(IConfigurationElement.class);
+ final IConfigurationElement[] configs = new IConfigurationElement[1];
+ when(ext.getConfigurationElements()).thenReturn(configs);
+ configs[0] = config;
+
+ PluginUtil.loadClasses(TEST_EXT_ID);
+ Mockito.verify(config).createExecutableExtension("class");
+ }
+
+ /**
+ * Test {@link PluginUtil#loadClass(String, String)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see PluginUtil#loadClass(String, String)
+ */
+ @Test
+ public void testLoadClass() throws Exception {
+
+ final IExtensionRegistry registry = mock(IExtensionRegistry.class);
+ when(PluginUtil.platformSurrogate.getAdapter()).thenReturn(registry);
+
+ final IExtensionPoint ep = mock(IExtensionPoint.class);
+ when(registry.getExtensionPoint(TEST_EXT_ID)).thenReturn(ep);
+
+ IExtension[] exts = new IExtension[1];
+ when(ep.getExtensions()).thenReturn(exts);
+
+ final IExtension ext = mock(IExtension.class);
+ exts[0] = ext;
+
+ final IConfigurationElement config = mock(IConfigurationElement.class);
+ when(config.getAttribute("id")).thenReturn(TEST_CLS_ID);
+ final IConfigurationElement[] configs = new IConfigurationElement[1];
+ when(ext.getConfigurationElements()).thenReturn(configs);
+ configs[0] = config;
+
+ PluginUtil.loadClass(TEST_EXT_ID, TEST_CLS_ID);
+ Mockito.verify(config).createExecutableExtension("class");
+ }
+
+}
diff --git a/org.tizen.common/test/src/org/tizen/common/util/SWTUtilTest.java b/org.tizen.common/test/src/org/tizen/common/util/SWTUtilTest.java
new file mode 100644
index 000000000..bf3cce3b1
--- /dev/null
+++ b/org.tizen.common/test/src/org/tizen/common/util/SWTUtilTest.java
@@ -0,0 +1,123 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* BonYong Lee <bonyong.lee@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+package org.tizen.common.util;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+import org.eclipse.swt.widgets.Display;
+import org.junit.Test;
+
+
+
+/**
+ * SWTUtilTest.
+ *
+ * Test case for {@link SWTUtil}
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ *
+ * @see SWTUtil
+ */
+public class SWTUtilTest
+{
+ /**
+ * Test {@link SWTUtil#getDisplay()}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see {@link SWTUtil#getDisplay()}
+ */
+ @Test
+ public void test_getDisplay() throws Exception {
+ Display dp = SWTUtil.getDisplay();
+ assertNotNull( dp );
+ dp.dispose();
+ }
+
+ /**
+ * Test {@link SWTUtil#asynExec()}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see {@link SWTUtil#asynExec()}
+ */
+ @Test
+ public void test_asynExec() throws Exception {
+ MockRunner runnable = new MockRunner();
+ assertFalse( runnable.bExecute );
+ Display dp = SWTUtil.getDisplay();
+ SWTUtil.asyncExec( dp, runnable );
+ assertFalse( runnable.bExecute );
+
+ long start = System.currentTimeMillis();
+ while ( !runnable.bExecute && (System.currentTimeMillis() - start) < 100 )
+ {
+ if ( !dp.readAndDispatch() )
+ {
+ dp.sleep();
+ }
+ }
+ assertTrue( runnable.bExecute );
+ }
+
+ /**
+ * Test {@link SWTUtil#isHtmlFile()}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see {@link SWTUtil#isHtmlFile()}
+ */
+ @Test
+ public void test_isHtmlFile() throws Exception {
+ final Object[][] TEST_CASES = new Object[][] {
+ new Object[] { "aaaa.exe", false },
+ new Object[] { "index.html", true },
+ new Object[] { "index.test.html", true },
+ new Object[] { "index..html", true },
+ new Object[] { ".profile", false },
+ new Object[] { "ReadMe ", false },
+ new Object[] { "ReadMe", false },
+ new Object[] { "ReadMe. ", false },
+ new Object[] { "ReadMe. test", false }
+ };
+
+ for ( final Object[] TEST_CASE : TEST_CASES )
+ {
+ final String fileName = (String) TEST_CASE[0];
+ final boolean expected = (Boolean) TEST_CASE[1];
+
+
+ /*
+ * LookAtMe : Attach title when looping test case
+ */
+ assertEquals( "input :" + fileName, expected, SWTUtil.isHtmlFile( fileName ) );
+ }
+
+ }
+
+}
diff --git a/org.tizen.common/test/src/org/tizen/common/util/StringUtilTest.java b/org.tizen.common/test/src/org/tizen/common/util/StringUtilTest.java
new file mode 100644
index 000000000..e95191c9f
--- /dev/null
+++ b/org.tizen.common/test/src/org/tizen/common/util/StringUtilTest.java
@@ -0,0 +1,459 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* BonYong Lee <bonyong.lee@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+package org.tizen.common.util;
+
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import org.junit.Test;
+
+/**
+ * StringUtilTest
+ *
+ * Test case for {@link StringUtil}
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ *
+ * @see StringUtil
+ */
+public class
+StringUtilTest
+{
+ /**
+ * @throws Exception in case of failure in test
+ *
+ * @see StringUtil#nvl(String...)
+ */
+ @Test
+ public
+ void
+ test_nvl()
+ throws Exception
+ {
+ final Object[][] TEST_CASES = new Object[][] {
+ new Object[] { "", new String[] { null, null } },
+ new Object[] { "Hello", new String[] { "Hello", "World" } },
+ new Object[] { "World", new String[] { null, "World" } },
+ new Object[] { "hello", new String[] { null, "hello" } },
+ new Object[] { "hello", new String[] { "hello", "world" } },
+ new Object[] { "hello", new String[] { null, null, "hello", "world" } },
+ };
+
+ for ( final Object[] TEST_CASE : TEST_CASES )
+ {
+ final String expected = (String) TEST_CASE[0];
+ final String[] input = (String[]) TEST_CASE[1];
+ assertEquals( expected, StringUtil.nvl( input ) );
+ }
+ }
+
+ /**
+ * @throws Exception in case of failure in test
+ *
+ * @see {@link StringUtil#trimLeadingWhitespace(String)}
+ */
+ @Test
+ public void
+ test_trimLeadingWhitespace()
+ throws Exception
+ {
+ final Object[][] TEST_CASES = new Object[][] {
+ new Object[] { "", "" },
+ new Object[] { "", " " },
+ new Object[] { null, null },
+ new Object[] { "Hello", " Hello" },
+ new Object[] { "H ", " H " },
+ };
+
+ for ( final Object[] TEST_CASE : TEST_CASES )
+ {
+ final String expected = (String) TEST_CASE[0];
+ final String input = (String) TEST_CASE[1];
+ assertEquals( expected, StringUtil.trimLeading( input ) );
+ }
+ }
+
+ /**
+ * @throws Exception in case of failure in test
+ *
+ * @see {@link StringUtil#trimLeadingWhitespace(String)}
+ */
+ @Test
+ public void
+ test_trimTrailingWhitespace()
+ throws Exception
+ {
+ final Object[][] TEST_CASES = new Object[][] {
+ new Object[] { "", "" },
+ new Object[] { "", " " },
+ new Object[] { null, null },
+ new Object[] { "Hello", "Hello " },
+ new Object[] { " H", " H " },
+ };
+
+ for ( final Object[] TEST_CASE : TEST_CASES )
+ {
+ final String expected = (String) TEST_CASE[0];
+ final String input = (String) TEST_CASE[1];
+ assertEquals( expected, StringUtil.trimTrailing( input ) );
+ }
+ }
+
+ /**
+ * @throws Exception in case of failure in test
+ *
+ * @see {@link StringUtil#trimLeadingCharacter(String, char)}
+ */
+ @Test
+ public void
+ test_trimLeadingCharacter()
+ throws Exception
+ {
+ final Object[][] TEST_CASES = new Object[][] {
+ new Object[] { "", "", '-' },
+ new Object[] { " ", " ", '-' },
+ new Object[] { null, null, '-' },
+ new Object[] { "Hello ", "---Hello ", '-' },
+ new Object[] { " H ", " H ", '-' },
+ };
+
+ for ( final Object[] TEST_CASE : TEST_CASES )
+ {
+ final String expected = (String) TEST_CASE[0];
+ final String input = (String) TEST_CASE[1];
+ final char trimChar = (Character) TEST_CASE[2];
+ assertEquals(
+ expected,
+ StringUtil.trimLeadingCharacter( input, trimChar )
+ );
+ }
+ }
+
+ /**
+ * @throws Exception in case of failure in test
+ *
+ * @see {@link StringUtil#trimTrailingCharacter(String, char)
+ */
+ @Test
+ public void
+ test_trimTrailingCharacter()
+ throws Exception
+ {
+ final Object[][] TEST_CASES = new Object[][] {
+ new Object[] { "", "", '-' },
+ new Object[] { " ", " ", '-' },
+ new Object[] { null, null, '-' },
+ new Object[] { "Hello", "Hello---", '-' },
+ new Object[] { " H-- ", " H-- ", '-' },
+ new Object[] { " H", " H--", '-' },
+ };
+
+ for ( final Object[] TEST_CASE : TEST_CASES )
+ {
+ final String expected = (String) TEST_CASE[0];
+ final String input = (String) TEST_CASE[1];
+ final char trimChar = (Character) TEST_CASE[2];
+ assertEquals(
+ expected,
+ StringUtil.trimTrailingCharacter( input, trimChar )
+ );
+ }
+ }
+
+ /**
+ * @throws Exception in case of failure in test
+ *
+ * @see {@link StringUtil#trimCharacter(String, char)}
+ */
+ @Test
+ public
+ void
+ test_trimCharacter()
+ throws Exception
+ {
+ final Object[][] TEST_CASES = new Object[][] {
+ new Object[] { "", "", '-' },
+ new Object[] { " ", " ", '-' },
+ new Object[] { null, null, '-' },
+ new Object[] { "Hello", "Hello---", '-' },
+ new Object[] { " H-- ", " H-- ", '-' },
+ new Object[] { " H", " H--", '-' },
+ new Object[] { " H", "-- H--", '-' },
+ new Object[] { "H", "--H--", '-' },
+ new Object[] { " - H", "-- - H--", '-' },
+ };
+
+ for ( final Object[] TEST_CASE : TEST_CASES )
+ {
+ final String expected = (String) TEST_CASE[0];
+ final String input = (String) TEST_CASE[1];
+ final char trimChar = (Character) TEST_CASE[2];
+ assertEquals(
+ expected,
+ StringUtil.trimCharacter( input, trimChar )
+ );
+ }
+
+ }
+
+ /**
+ * @throws Exception in case of failure in test
+ *
+ * @see StringUtil#getWord(String, int)
+ */
+ @Test
+ public void
+ test_getWord()
+ throws Exception
+ {
+ final Object[][] TEST_CASES = new Object[][] {
+ new Object[] { "I am a boy", 0, "I" },
+ new Object[] { "I am a boy", 1, "I" },
+ new Object[] { "I am a boy", 2, "am" },
+ new Object[] { "I am a boy", 3, "am" },
+ new Object[] { "I am a boy", 4, "am" },
+ new Object[] { "I am a boy", 5, "a" },
+ new Object[] { "I am a boy", 6, "a" },
+ new Object[] { "I am a boy", 7, "boy" },
+ new Object[] { "I am a boy", 8, "boy" },
+ new Object[] { "I am a boy", 9, "boy" },
+ new Object[] { "I am a boy", 10, "boy" },
+ new Object[] { "I am a boy", 11, "" },
+ };
+
+ for ( final Object[] TEST_CASE : TEST_CASES )
+ {
+ final String doc = (String) TEST_CASE[0];
+ final int index = (Integer) TEST_CASE[1];
+ final String expected = (String) TEST_CASE[2];
+ assertEquals(
+ expected,
+ StringUtil.getWord( doc, index )
+ );
+ }
+ }
+
+ /**
+ * @throws Exception in case of failure in test
+ *
+ * @see StringUtil#getPreviousWord(String, int)
+ */
+ @Test
+ public void
+ test_getPreviousWord()
+ throws Exception
+ {
+ final Object[][] TEST_CASES = new Object[][] {
+ new Object[] { "I am a boy ", 0, "" },
+ new Object[] { "I am a boy ", 1, "I" },
+ new Object[] { "I am a boy ", 2, "" },
+ new Object[] { "I am a boy ", 3, "a" },
+ new Object[] { "I am a boy ", 4, "am" },
+ new Object[] { "I am a boy ", 5, "" },
+ new Object[] { "I am a boy ", 6, "a" },
+ new Object[] { "I am a boy ", 7, "" },
+ new Object[] { "I am a boy ", 8, "b" },
+ new Object[] { "I am a boy ", 9, "bo" },
+ new Object[] { "I am a boy ", 10, "boy" },
+ new Object[] { "I am a boy ", 11, "" },
+ new Object[] { "I am a boy ", 12, "" },
+ new Object[] { "#{\ntest", 2, "#{" },
+ };
+
+ for ( final Object[] TEST_CASE : TEST_CASES )
+ {
+ final String doc = (String) TEST_CASE[0];
+ final int index = (Integer) TEST_CASE[1];
+ final String expected = (String) TEST_CASE[2];
+ assertEquals(
+ expected,
+ StringUtil.getPreviousWord( doc, index )
+ );
+ }
+ }
+
+ /**
+ * Test {@link StringUtil#getLastSegment(String, String)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see {@link StringUtil#getLastSegment(String, String)}
+ */
+ @Test
+ public
+ void
+ test_getLastSegement()
+ throws Exception
+ {
+ final Object[][] TEST_CASES = new Object[][] {
+ new Object[] { null, " ", "" },
+ new Object[] { "I am a boy", " ", "boy" },
+ new Object[] { "I am a boy", " ", "boy" },
+ new Object[] { "I am a boy ", " ", "" },
+ new Object[] { "a,b,c,d", ",", "d" },
+ };
+
+ for ( final Object[] TEST_CASE : TEST_CASES )
+ {
+ final String doc = (String) TEST_CASE[0];
+ final String separator = (String) TEST_CASE[1];
+ final String expected = (String) TEST_CASE[2];
+ assertEquals(
+ expected,
+ StringUtil.getLastSegment( doc, separator )
+ );
+ }
+ }
+
+ /**
+ * Test {@link StringUtil#getLastSegment(String, String)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see {@link StringUtil#getLastSegment(String, String)}
+ */
+ @Test
+ public
+ void
+ test_removeLastSegement()
+ throws Exception
+ {
+ final Object[][] TEST_CASES = new Object[][] {
+ new Object[] { null, " ", "" },
+ new Object[] { "I am a boy", " ", "I am a" },
+ new Object[] { "I am a boy", " ", "I am a " }, // FIXME ?
+ new Object[] { "I am a boy ", " ", "I am a boy" },
+ new Object[] { "a,b,c,d", ",", "a,b,c" },
+ };
+
+ for ( final Object[] TEST_CASE : TEST_CASES )
+ {
+ final String doc = (String) TEST_CASE[0];
+ final String separator = (String) TEST_CASE[1];
+ final String expected = (String) TEST_CASE[2];
+ assertEquals(
+ expected,
+ StringUtil.removeLastSegment( doc, separator )
+ );
+ }
+ }
+
+ /**
+ * Test {@link StringUtil#split(String, String)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see {@link StringUtil#split(String, String)}
+ */
+ @Test
+ public
+ void
+ test_split()
+ throws Exception
+ {
+ final Object[][] TEST_CASES = new Object[][] {
+ new Object[] { "aa.bbb.ccc", ".", new String[] { "aa", "bbb", "ccc" } }
+ };
+
+ for ( final Object[] TEST_CASE : TEST_CASES )
+ {
+ final String input = (String) TEST_CASE[0];
+ final String delimiters = (String) TEST_CASE[1];
+ final String[] expected = (String[]) TEST_CASE[2];
+
+ assertArrayEquals( expected, StringUtil.split( input, delimiters ) );
+ }
+ }
+
+ /**
+ * Test {@link StringUtil#enumNameToStringArray(T[] values)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see {@link StringUtil#enumNameToStringArray(T[] values)}
+ */
+ @Test
+ public void test_enumNameToStringArray() throws Exception {
+ TestEnumCase [] enums = TestEnumCase.values();
+ String [] values = StringUtil.enumNameToStringArray(enums);
+ assertTrue(enums.length == values.length);
+
+ StringBuilder enumBuilder = new StringBuilder();
+ for (TestEnumCase testEnumCase : enums) {
+ enumBuilder.append(testEnumCase.name());
+ }
+
+ StringBuilder utilBuilder = new StringBuilder();
+ for (String string : values) {
+ utilBuilder.append(string);
+ }
+ assertEquals(enumBuilder.toString(), utilBuilder.toString());
+ }
+
+ /**
+ * Test {@link StringUtil#removeStart(String, String)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see {@link StringUtil#removeStart(String, String)}
+ */
+ @Test
+ public void
+ test_removeStart()
+ throws Exception
+ {
+ String str = "abcdefg";
+ String remove1 = "a";
+ String remove2 = "abc";
+ String remove3 = "def";
+
+ // null test
+ assertEquals( str, StringUtil.removeStart( str, null ) );
+ assertEquals( null, StringUtil.removeStart( null, remove1 ) );
+ assertEquals( null, StringUtil.removeStart( null, null ) );
+
+ // start with
+ assertEquals( "bcdefg", StringUtil.removeStart(str, remove1 ) );
+ assertEquals( "defg", StringUtil.removeStart(str, remove2 ) );
+
+ // not start with
+ assertEquals( str, StringUtil.removeStart(str, remove3 ) );
+ }
+
+ public enum TestEnumCase {
+ ABC("ABC"),
+ DEF("DEF"),
+ GHI("GHI"),
+ JKL("JKL");
+ private String value;
+ TestEnumCase(String v) {
+ value = v;
+ }
+ public String value() {
+ return value;
+ }
+ }
+}
diff --git a/org.tizen.common/test/src/org/tizen/common/util/ThreadUtilTest.java b/org.tizen.common/test/src/org/tizen/common/util/ThreadUtilTest.java
new file mode 100644
index 000000000..62f89167b
--- /dev/null
+++ b/org.tizen.common/test/src/org/tizen/common/util/ThreadUtilTest.java
@@ -0,0 +1,70 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* BonYong Lee <bonyong.lee@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+package org.tizen.common.util;
+
+import static org.junit.Assert.*;
+
+import org.junit.Test;
+
+
+/**
+ * ThreadUtilTest
+ *
+ * Test case for {@link ThreadUtil}
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ *
+ * @see ThreadUtil
+ */
+public class ThreadUtilTest {
+
+ /**
+ * Test {@link ThreadUtil#trySleep(long)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see {@link ThreadUtil#trySleep(long)}
+ */
+ @Test
+ public void test_trySleep() throws Exception {
+ final Object[][] TEST_CASES = new Object[][] {
+ new Object[] { 100, 100 },
+ new Object[] { 0, 0 },
+ new Object[] { -100, 0 }
+ };
+
+ for ( final Object[] TEST_CASE : TEST_CASES )
+ {
+ final int milliseconds = (Integer) TEST_CASE[0];
+ final int expected = (Integer) TEST_CASE[1];
+
+ long start = System.currentTimeMillis();
+ ThreadUtil.trySleep( milliseconds );
+ long end = System.currentTimeMillis();
+
+ assertTrue( "input :" + milliseconds + ", expected :" + expected, expected <= ( end - start ) );
+ }
+ }
+}
diff --git a/org.tizen.common/test/src/org/tizen/common/util/ValidationUtilTest.java b/org.tizen.common/test/src/org/tizen/common/util/ValidationUtilTest.java
new file mode 100644
index 000000000..4fe6bbc14
--- /dev/null
+++ b/org.tizen.common/test/src/org/tizen/common/util/ValidationUtilTest.java
@@ -0,0 +1,146 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* ChangHyun Lee <changhyun1.lee@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+
+package org.tizen.common.util;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import org.junit.Test;
+
+/**
+ * ValidationUtilTest.
+ *
+ * Test case for {@link ValidationUtil}
+ *
+ * @author Changhyun Lee{@literal <changhyun1.lee@samsung.com>} (S-Core)
+ *
+ * @see ValidationUtil
+ *
+ */
+public class ValidationUtilTest {
+
+ /**
+ * Test {@link ValidationUtil#checkForEmail(String value)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see {@link ValidationUtil#checkForEmail(String value)}
+ */
+ @Test
+ public void test_checkForEmail() throws Exception {
+ final String[] validedEmail = {
+ "changhyun1.lee@samsung.com",
+ "12345@exmaple.com",
+ "abcde@exmaple.com",
+ "!a!b#c%d@example.com",
+ "_abcd@example.com",
+ "niceandsimple@example.com",
+ "simplewithsymbol@example.com",
+ "less.common@example.com",
+ "a.little.more.unusual@dept.example.com"
+ };
+ for (String email : validedEmail) {
+ assertTrue(ValidationUtil.checkForEmail(email));
+ }
+
+ final String[] InvalidedEmail = {
+ "changhyun1.lee@samsung",
+ "changhyun1.leesamsung.com",
+ "changhyun1.lee@samsung.com/",
+ "changhyun1.lee@samsung.com!",
+ "@samsung.com",
+ "12345!exmaple.com",
+ "!a!b#c%d@example.co!m",
+ "_abcd@example_com",
+ "user@[IPv6:2001:db8:1ff::a0b:dbd0]",
+ "\"much.more unusual\"@example.com",
+ "\"very.unusual.@.unusual.com\"@example.com",
+ "\"very.(),:;<>[]\".VERY.\"very@\\ \"very\".unusual\"@strange.example.com",
+ "0@a",
+ "\"!#$%&'*+-/=?^_`{}|~@example.org",
+ "\"()<>[]:,;@\\\"!#$%&'*+-/=?^_`{}| ~ ? ^_`{}|~.a\"@example.org",
+ "\"\"@example.org",
+ "postbox@com", // top-level domains are invalid hostnames
+ "Abc.example.com", // an @ character must separate the local and domain parts
+ "Abc.@example.com", // character dot(.) is last in local part
+ "Abc..123@example.com", // character dot(.) is double
+ "A@b@c@example.com ", // only one @ is allowed outside quotation marks
+ "a\"b(c)d,e:f;g<h>i[j\\k]l@example.com", // none of the special characters in this local part is allowed outside quotation marks
+ "just\"not\"right@example.com", // quoted strings must be dot separated, or the only element making up the local-part
+ "this is\"not\\allowed@example.com", // spaces, quotes, and backslashes may only exist when within quoted strings and preceded by a slash
+ "this\\ still\"not\\allowed@example.com" // even if escaped (preceded by a backslash), spaces, quotes, and backslashes must still be contained by quotes
+ };
+ for (String email : InvalidedEmail) {
+ assertFalse(ValidationUtil.checkForEmail(email));
+ }
+ }
+
+ /**
+ * Test {@link ValidationUtil#checkForURL(String value)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see {@link ValidationUtil#checkForURL(String value)}
+ */
+ @Test
+ public void test_checkForURL() throws Exception {
+ final String[] validedURL = {"http://tizen.org", "http://www.tizen.org", "http://tizen.org/", "http://tizen.org/id", "http://myapp"};
+ for (String url : validedURL) {
+ assertTrue(ValidationUtil.checkForURL(url));
+ }
+
+ final String[] invalidedURL = {"http:/tizen.org", "tizen.org", "www.tizen.org", "http://tizen.org/!", "http://tizen.org/id^", "http://tizen.org/id*"};
+ for (String url : invalidedURL) {
+ assertFalse(ValidationUtil.checkForURL(url));
+ }
+ }
+
+ /**
+ * Test {@link ValidationUtil#checkForFileExtension(String value, String[] extensions)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see {@link ValidationUtil#checkForFileExtension(String value, String[] extensions)}
+ */
+ @Test
+ public void test_checkForFileExtension() throws Exception {
+ final String[] extensions = {".html", ".js", ".css"};
+ assertTrue(ValidationUtil.checkForFileExtension("file.html", extensions));
+ assertTrue(ValidationUtil.checkForFileExtension("123.html", extensions));
+ assertTrue(ValidationUtil.checkForFileExtension("file.js", extensions));
+ assertTrue(ValidationUtil.checkForFileExtension("123.js", extensions));
+ assertTrue(ValidationUtil.checkForFileExtension("file.css", extensions));
+ assertTrue(ValidationUtil.checkForFileExtension("123.css", extensions));
+
+ assertFalse(ValidationUtil.checkForFileExtension("file.html1", extensions));
+ assertFalse(ValidationUtil.checkForFileExtension("123.html!", extensions));
+ assertFalse(ValidationUtil.checkForFileExtension("file.jshtml", extensions));
+ assertFalse(ValidationUtil.checkForFileExtension("123.js2", extensions));
+ assertFalse(ValidationUtil.checkForFileExtension("file.aaacss", extensions));
+ assertFalse(ValidationUtil.checkForFileExtension("123.111css", extensions));
+ }
+
+}
diff --git a/org.tizen.common/test/src/org/tizen/common/util/io/BufferPoolTest.java b/org.tizen.common/test/src/org/tizen/common/util/io/BufferPoolTest.java
new file mode 100644
index 000000000..ea93b06f7
--- /dev/null
+++ b/org.tizen.common/test/src/org/tizen/common/util/io/BufferPoolTest.java
@@ -0,0 +1,90 @@
+/*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common.util.io;
+
+import static org.junit.Assert.assertEquals;
+import static org.tizen.common.util.IOUtil.tryClose;
+
+import java.nio.ByteBuffer;
+import java.util.ArrayList;
+
+import org.junit.Test;
+
+
+/**
+ * BufferPoolTest
+ *
+ * Test case for {@link BufferPool}
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ *
+ * @see BufferPool
+ */
+public class
+BufferPoolTest
+{
+ /**
+ * Test {@link BufferPool#setSizeOfFragment(int)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see {@link BufferPool#setSizeOfFragment(int)}
+ */
+ @Test
+ public
+ void
+ test_setSizeOfFragment()
+ throws Exception
+ {
+ final ArrayList<ByteBuffer> tempPool = new ArrayList<ByteBuffer>();
+
+ final BufferPool pool = new BufferPool();
+
+ pool.setSizeOfFragment( 10 );
+ pool.setNumberOfFragments( 10 );
+
+ try {
+ for ( int i = 0 ; i < 9 ; ++i )
+ {
+ tempPool.add( pool.borrow() );
+ }
+ pool.setSizeOfFragment( 20 );
+ ByteBuffer buffer = pool.borrow();
+ assertEquals( 10, buffer.limit() );
+ tempPool.add( buffer );
+ }
+ finally
+ {
+ for ( ByteBuffer buffer : tempPool )
+ {
+ pool.release( buffer );
+ }
+
+ tryClose( pool );
+
+ }
+ }
+
+}
diff --git a/org.tizen.common/test/src/org/tizen/common/util/io/BufferTest.java b/org.tizen.common/test/src/org/tizen/common/util/io/BufferTest.java
new file mode 100644
index 000000000..c5c2c31b8
--- /dev/null
+++ b/org.tizen.common/test/src/org/tizen/common/util/io/BufferTest.java
@@ -0,0 +1,274 @@
+/*
+ * Common
+ *
+ * Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Contact:
+ * BonYong Lee <bonyong.lee@samsung.com>
+ *
+ * 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.
+ *
+ * Contributors:
+ * - S-Core Co., Ltd
+ *
+ */
+package org.tizen.common.util.io;
+
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.tizen.common.util.IOUtil.tryClose;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+/**
+ * BufferTest
+ *
+ * Test case for {@link Buffer}
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ *
+ * @see Buffer
+ */
+public class BufferTest
+{
+
+ /**
+ * {@link BufferPool} to use
+ */
+ protected BufferPool bufferPool;
+
+ /**
+ * Set up test unit
+ *
+ * @throws Exception If test unit can't be set up
+ */
+ @Before
+ public
+ void
+ setUp()
+ throws Exception
+ {
+ bufferPool = new BufferPool();
+
+ bufferPool.setSizeOfFragment( 10 );
+ }
+
+ /**
+ * Tear down test unit
+ *
+ * @throws Exception If test unit can't be tear down
+ */
+ @After
+ public
+ void
+ tearDown()
+ throws Exception
+ {
+ bufferPool.close();
+ }
+
+ /**
+ * Test {@link Buffer#readInt()}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see {@link Buffer#readInt()}
+ */
+ @Test
+ public
+ void
+ test_readInt()
+ throws Exception
+ {
+ final Object[][] TEST_CASES = new Object[][] {
+ new Object[] { 135, new byte[] { 0, 0, 0, -121 } }
+ };
+
+ for ( final Object[] TEST_CASE : TEST_CASES )
+ {
+ final int expected = (Integer) TEST_CASE[0];
+ final byte[] input = (byte[]) TEST_CASE[1];
+ final Buffer buffer = new Buffer( bufferPool );
+ try
+ {
+ for ( int i = 0, n = input.length ; i < n ; ++i )
+ {
+ buffer.write( input[i] );
+ }
+
+ assertEquals( expected, buffer.readInt() );
+ }
+ finally
+ {
+ tryClose( buffer );
+ }
+ }
+ }
+
+
+ /**
+ * Test {@link Buffer#writeInt(int)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see {@link Buffer#writeInt(int)}
+ */
+ @Test
+ public
+ void
+ test_writeInt()
+ throws Exception
+ {
+ final Object[][] TEST_CASES = new Object[][] {
+ new Object[] { 135, new int[] { 0, 0, 0, 135 } }
+ };
+
+ for ( final Object[] TEST_CASE : TEST_CASES )
+ {
+ final int input = (Integer) TEST_CASE[0];
+ final int[] expected = (int[]) TEST_CASE[1];
+
+ final Buffer buffer = new Buffer( bufferPool );
+ try
+ {
+ buffer.writeInt( input );
+ for ( int i = 0, n = expected.length ; i < n ; ++i )
+ {
+ assertEquals( expected[i], buffer.read() );
+ }
+ }
+ finally
+ {
+ tryClose( buffer );
+ }
+ }
+ }
+
+ /**
+ * Test {@link Buffer#getBufferSize()}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see {@link Buffer#getBufferSize()}
+ */
+ @Test
+ public
+ void
+ test_getBufferSize()
+ throws Exception
+ {
+ final Buffer buffer = new Buffer( bufferPool );
+ try
+ {
+ final BufferOutputStream bufferOut = new BufferOutputStream( buffer );
+ bufferOut.write( "12345678901234567890123456789012345678901234567890".getBytes() );
+
+ assertEquals( 5, buffer.getBufferSize() );
+
+ buffer.read();
+
+ assertEquals( 5, buffer.getBufferSize() );
+
+ }
+ finally
+ {
+ tryClose( buffer );
+ }
+
+ }
+
+ /**
+ * Test {@link Buffer#reset()}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see {@link Buffer#reset()}
+ */
+ @Test
+ public
+ void
+ test_reset()
+ throws Exception
+ {
+ final byte[] TEST = "12345678901234567890123456789012345678901234567890".getBytes();
+ final Buffer buffer = new Buffer( bufferPool );
+
+ try
+ {
+ final BufferOutputStream bufferOut = new BufferOutputStream( buffer );
+ bufferOut.write( TEST );
+
+ final BufferInputStream bufferIn = new BufferInputStream( buffer );
+ final byte[] result = new byte[TEST.length];
+
+ assertEquals( TEST.length, bufferIn.read( result ) );
+ assertArrayEquals( TEST, result );
+
+ buffer.reset();
+
+ assertEquals( TEST.length, bufferIn.read( result ) );
+ assertArrayEquals( TEST, result );
+ }
+ finally
+ {
+ tryClose( buffer );
+ }
+
+ }
+
+ /**
+ * Test {@link Buffer#concatenate(Buffer...)}
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see {@link Buffer#concatenate(Buffer...)}
+ */
+ @Test
+ public
+ void
+ test_concatenate()
+ throws Exception
+ {
+ final Buffer buffer1 = new Buffer( bufferPool );
+ final Buffer buffer2 = new Buffer( bufferPool );
+
+ final byte[] EXPECTED = "123456789012123456789012".getBytes();
+ final byte[] TEST = "123456789012".getBytes();
+
+ try
+ {
+ final BufferOutputStream bufferOut1 = new BufferOutputStream( buffer1 );
+ bufferOut1.write( TEST );
+
+ final BufferOutputStream bufferOut2 = new BufferOutputStream( buffer1 );
+ bufferOut2.write( TEST );
+
+ Buffer ret = Buffer.concatenate( buffer1, buffer2 );
+ BufferInputStream bufferIn = new BufferInputStream( ret );
+
+ final byte[] result = new byte[2 * TEST.length];
+
+ assertEquals( result.length, ret.size() );
+ assertEquals( result.length, bufferIn.read( result ) );
+ assertArrayEquals( EXPECTED, result );
+
+ }
+ finally
+ {
+ tryClose( buffer1 );
+ }
+ }
+
+}
diff --git a/org.tizen.common/test/src/org/tizen/common/util/test b/org.tizen.common/test/src/org/tizen/common/util/test
new file mode 100644
index 000000000..9daeafb98
--- /dev/null
+++ b/org.tizen.common/test/src/org/tizen/common/util/test
@@ -0,0 +1 @@
+test
diff --git a/org.tizen.common/test/src/org/tizen/common/util/url/classpath/ConnectionTest.java b/org.tizen.common/test/src/org/tizen/common/util/url/classpath/ConnectionTest.java
new file mode 100644
index 000000000..38e27011f
--- /dev/null
+++ b/org.tizen.common/test/src/org/tizen/common/util/url/classpath/ConnectionTest.java
@@ -0,0 +1,92 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* BonYong Lee <bonyong.lee@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+package org.tizen.common.util.url.classpath;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
+
+import java.io.IOException;
+import java.net.URL;
+import java.net.URLClassLoader;
+
+import org.junit.Test;
+
+/**
+ * ConnectionTest
+ *
+ * Test case for {@link Connection}
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ *
+ * @see Connection
+ */
+public class ConnectionTest
+{
+ /**
+ * Test {@link Connection#getClassLoaders()
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see {@link Connection#getClassLoaders()
+ */
+ @Test
+ public
+ void
+ test_getClassLoaders()
+ throws Exception
+ {
+ final Object[] classLoaders = Connection.getClassLoaders().toArray();
+ assertEquals( 1, classLoaders.length );
+
+ URLClassLoader classLoader = new URLClassLoader( new URL[] {} );
+ Thread.currentThread().setContextClassLoader( classLoader );
+
+ final Object[] classLoaders2 = Connection.getClassLoaders().toArray();
+ assertEquals( classLoader, classLoaders2[0] );
+ assertEquals( ClassLoader.getSystemClassLoader(), classLoaders2[1] );
+ }
+
+ /**
+ * Test {@link Connection#getInputStream()
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see Connection#getInputStream()
+ */
+ @Test
+ public void test_getInputStream() throws Exception
+ {
+ final Connection con = new Connection( new URL( "file:///virtualrul" ), null );
+ try
+ {
+ con.getInputStream();
+ fail( "Connection must throw IOException" );
+ }
+ catch ( final IOException e )
+ {
+ }
+ }
+
+}
diff --git a/org.tizen.common/test/src/org/tizen/common/util/url/classpath/HandlerTest.java b/org.tizen.common/test/src/org/tizen/common/util/url/classpath/HandlerTest.java
new file mode 100644
index 000000000..ba24cb3dc
--- /dev/null
+++ b/org.tizen.common/test/src/org/tizen/common/util/url/classpath/HandlerTest.java
@@ -0,0 +1,126 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* BonYong Lee <bonyong.lee@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+package org.tizen.common.util.url.classpath;
+
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import static org.tizen.common.util.IOUtil.getBytes;
+import static org.tizen.common.util.IOUtil.tryClose;
+
+import java.io.InputStream;
+import java.net.URL;
+import java.net.URLConnection;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+
+/**
+ * HandlerTest
+ *
+ * Test case for {@link Handler}
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ *
+ * @see Handler
+ */
+public class
+HandlerTest
+{
+ protected String oldConfig;
+
+ /**
+ * install url handler for classpath
+ */
+ @Before
+ public void setUp()
+ {
+ oldConfig = System.getProperty( "java.protocol.handler.pkgs" );
+ System.setProperty( "java.protocol.handler.pkgs", "org.tizen.common.util.url" );
+ }
+
+ /**
+ * uninstall url handler for classpath
+ */
+ @After
+ public void tearDown()
+ {
+ if ( null == oldConfig )
+ {
+ return ;
+ }
+ System.setProperty( "java.protocol.handler.pkgs", oldConfig );
+ }
+
+ /**
+ * Test {@link Handler#openConnection(URL)
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see {@link Handler#openConnection(URL)
+ */
+ @Test
+ public void test_openConnection() throws Exception
+ {
+
+ final Handler handler = new Handler();
+ final URL url = new URL( "classpath:///" + getClass().getName().replace( '.', '/' ) + ".class" );
+
+ final URLConnection connection = handler.openConnection( url );
+
+ connection.connect();
+ InputStream in = connection.getInputStream();
+ try
+ {
+ assertTrue( 0 < in.read() );
+ }
+ finally
+ {
+ tryClose( in );
+ }
+
+
+ }
+
+ /**
+ * Test {@link Handler#pickupCaller()
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see {@link Handler#pickupCaller()
+ */
+ @Test
+ public void test_pickupCaller() throws Exception {
+ final Handler handler = new Handler();
+ assertNull( handler.pickupCaller() );
+
+ final URL u = new URL( "classpath:///a.txt" );
+ final InputStream in = u.openStream();
+ assertArrayEquals( "Hello, World".getBytes(), getBytes( in, true ) );
+
+ }
+}
diff --git a/org.tizen.common/test/src/org/tizen/common/util/url/classpath/a.txt b/org.tizen.common/test/src/org/tizen/common/util/url/classpath/a.txt
new file mode 100644
index 000000000..1856e9be0
--- /dev/null
+++ b/org.tizen.common/test/src/org/tizen/common/util/url/classpath/a.txt
@@ -0,0 +1 @@
+Hello, World \ No newline at end of file
diff --git a/org.tizen.common/test/src/org/tizen/common/util/url/cp/HandlerTest.java b/org.tizen.common/test/src/org/tizen/common/util/url/cp/HandlerTest.java
new file mode 100644
index 000000000..34d0a33f6
--- /dev/null
+++ b/org.tizen.common/test/src/org/tizen/common/util/url/cp/HandlerTest.java
@@ -0,0 +1,115 @@
+/*
+* Common
+*
+* Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+*
+* Contact:
+* BonYong Lee <bonyong.lee@samsung.com>
+*
+* 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.
+*
+* Contributors:
+* - S-Core Co., Ltd
+*
+*/
+package org.tizen.common.util.url.cp;
+
+import static org.junit.Assert.assertTrue;
+import static org.tizen.common.util.IOUtil.tryClose;
+
+import java.io.InputStream;
+import java.net.URL;
+import java.net.URLConnection;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+
+/**
+ * HandlerTest
+ *
+ * Test case for {@link Handler}
+ *
+ * @author BonYong Lee{@literal <bonyong.lee@samsung.com>} (S-Core)
+ *
+ * @see Handler
+ */
+public class
+HandlerTest
+{
+ /**
+ * Property key for URL handler
+ */
+ protected static final String PROP_PKG = "java.protocol.handler.pkgs";
+
+ /**
+ * Old property value for URL handler
+ */
+ protected String oldConfig;
+
+ /**
+ * Set up URL handler before test
+ */
+ @Before
+ public void setUp()
+ {
+ oldConfig = System.getProperty( PROP_PKG );
+ System.setProperty( PROP_PKG, "org.tizen.common.util.url" );
+ }
+
+ /**
+ * Restore URL handler after test
+ */
+ @After
+ public void tearDown()
+ {
+ if ( null == oldConfig )
+ {
+ System.getProperties().remove( PROP_PKG );
+ return ;
+ }
+ System.setProperty( PROP_PKG, oldConfig );
+ }
+
+ /**
+ * Test {@link Handler#openConnection(URL)
+ *
+ * @throws Exception in case of failure in test
+ *
+ * @see {@link Handler#openConnection(URL)
+ */
+ @Test
+ public void test_openConnection() throws Exception
+ {
+
+ final Handler handler = new Handler();
+ final URL url = new URL( "cp:///" + getClass().getName().replace( '.', '/' ) + ".class" );
+
+ final URLConnection connection = handler.openConnection( url );
+
+ connection.connect();
+ InputStream in = connection.getInputStream();
+ try
+ {
+ assertTrue( 0 < in.read() );
+ }
+ finally
+ {
+ tryClose( in );
+ }
+
+
+ }
+
+}
diff --git a/package/build.linux b/package/build.linux
index 07c4de454..06e3deeb1 100755
--- a/package/build.linux
+++ b/package/build.linux
@@ -1,291 +1,89 @@
-#!/bin/bash -x
-
-build_path=${SRCDIR}/build_result
-
-__set_parameter()
-{
- build_id=${package_name}
- build_type=N
- build_result_directory=${build_type}.${build_id}
- build_result_path="$build_path/$build_result_directory"
- architecture=x86
- ide_root_path_name=IDE
-
- case ${platform} in
- linux)
- archive_platform_name=linux
- windowing=gtk
- ;;
- windows)
- archive_platform_name=win32
- windowing=win32
- ;;
- *)
- echo "${platform} is not support yet."
- ;;
- esac
-
- result_archive_file=${build_id}-${archive_platform_name}.${windowing}.${architecture}.zip
-}
-
-__set_build_parameter()
-{
- case ${platform} in
- linux)
- reference_ide_path=${ROOTDIR}/indigo-pde/eclipse
- ;;
- windows)
- reference_ide_path=${ROOTDIR}/indigo-winpde/eclipse
- ;;
- *)
- echo "${platform} is not support yet."
- ;;
- esac
-}
-
-__set_install_parameter()
-{
- INSTALL_DIR=${SRCDIR}/package/${package_name}.package.${platform}/data
-}
-
-__clean_build_environment()
-{
- if [ -d $build_path ]
- then
- echo "Build result directory : [$build_path]"
- else
- echo "Make build result directory [$build_path]"
- mkdir -p $build_path
- fi
-
- echo "Remove legacy build files..."
- if [ -d ${build_result_path}/${archive_platform_name}.${windowing}.${architecture} ]
- then
- rm -rf ${build_result_path}/${archive_platform_name}.${windowing}.${architecture}
- fi
- if [ -e ${build_result_path}/${result_archive_file} ]
- then
- rm -rf ${build_result_path}/${result_archive_file}
- fi
- if [ -d ${build_path}/tmp ]
- then
- rm -rf ${build_path}/tmp
- fi
-
- if [ -d ${build_path}/buildRepo ]
- then
- rm -rf ${build_path}/buildRepo
- fi
-
- rm -r ${build_path}/*.xml
- rm -r ${build_path}/*.properties
- rm -r ${build_path}/*.clean
-
-
- if [ -d $build_path/plugins ]
- then
- echo "plugins directory recreate..."
- rm -rf $build_path/plugins
- mkdir $build_path/plugins
- else
- echo "Make plugins directory..."
- mkdir $build_path/plugins
- fi
- if [ -d $build_path/features/ ]
- then
- echo "features directory recreate..."
- rm -rf $build_path/features
- mkdir $build_path/features
- else
- echo "Make features directory..."
- mkdir $build_path/features
- fi
-
-}
-
-__copy_build_sources()
-{
- echo "Copy features from $SRCDIR to $build_path/features"
- cp -r $SRCDIR/* $build_path/features
-
- echo "Copy plugins from $SRCDIR to $build_path/plugins"
- cp -r $SRCDIR/* $build_path/plugins
-}
-
-__copy_dependency_plugins()
-{
- dependency_plugin_path=${ROOTDIR}/${ide_root_path_name}
- if [ -d ${dependency_plugin_path} ]
- then
- cp -rf ${dependency_plugin_path}/features/* ${build_path}/features/
- cp -rf ${dependency_plugin_path}/plugins/* ${build_path}/plugins/
- fi
-}
-
-__make_ant_build_properties_file()
-{
- builder_path="${SRCDIR}/builder"
- parent_path_of_based_eclipse=${reference_ide_path}/..
-
- echo "Make build.properties file..."
- if [ ! -e $builder_path/build.properties.clean ] ; then
- echo "ERROR : \"build.properties.clean\" file does not exist..."
- exit 1
- fi
- cp $builder_path/build.properties.clean $build_path
- cp $builder_path/customTargets.xml $build_path
-
- if [ -d $reference_ide_path ]
- then
- sed -e "s;\(^buildDirectory=\).*;\1${build_path};g" \
- -e "s;\(^base=\).*;\1${parent_path_of_based_eclipse};g" \
- -e "s;\(^baseLocation=\).*;\1${reference_ide_path};g" \
- -e "s;\(^configs=\).*;\1${archive_platform_name},${windowing},${architecture};g" \
- -e "s;\(^buildType=\).*;\1${build_type};g" \
- -e "s;\(^buildId=\).*;\1${build_id};g" \
- -e "s;\(^archivePrefix=\).*;\1${build_id};g" \
- < $build_path/build.properties.clean > $build_path/build.properties
-
- else
- echo "ERROR : target eclipse is not exist."
- exit 1
- fi
-}
-
-__execute_pde_build()
-{
- echo "Execute Product Ant Builder..."
- equinox_launcher=`echo org.eclipse.equinox.launcher_*.jar`
- pde_build=`echo org.eclipse.pde.build_*`
-
- java -jar ${reference_ide_path}/plugins/$equinox_launcher -application org.eclipse.ant.core.antRunner -buildfile ${reference_ide_path}/plugins/$pde_build/scripts/productBuild/productBuild.xml -Dbuilder=$build_path -Dosgi.locking=none 2>&1
-
- if [ $? != 0 ];
- then
- echo "Build failed..."
- exit 1
- fi
-}
-
-__unzip_plugin_pack()
-{
- echo "unzip to $build_result_path"
- unzip -a $build_result_path/${result_archive_file} -d $build_result_path/${archive_platform_name}.${windowing}.${architecture}
-}
-
-build_plugins()
-{
- case ${platform} in
- linux)
- echo "build plugin for ${platform}"
- ;;
- windows)
- echo "build plugin for ${platform}"
- ;;
- *)
- echo "${platform} is not support yet."
- exit 1
- ;;
- esac
-
- __set_parameter
- __set_build_parameter
- __clean_build_environment
- __copy_build_sources
- __copy_dependency_plugins
- __make_ant_build_properties_file
- __execute_pde_build
- __unzip_plugin_pack
-
- echo "Build SUCCESS. You will find SDK IDE in \"${build_result_path}\"."
-}
-
-__clean_packaging_environment()
-{
-
- if [ -d ${INSTALL_DIR} ]
- then
- rm -rf ${INSTALL_DIR}
- else
- mkdir -p ${INSTALL_DIR}
- fi
-}
+#!/bin/bash -xe
__copy_necessary_binaries()
{
- echo "add necessary files."
- ## ex) cp -rf ~~~~/file.file ${INSTALL_DIR}/${ide_root_path_name}/
+ echo "add necessary files."
+ ## ex)
+ ## ide_root_path_name=IDE
+ ## cp -rf ~~~~/file.file ${INSTALL_DIR}/${ide_root_path_name}/
+ ## cp -rf ${SRCDIR}/packager/common/data/* ${INSTALL_DIR}/
}
-packaging_plugins()
+__set_parameter()
{
- __set_parameter
- __set_install_parameter
-
- __clean_packaging_environment
- __copy_necessary_binaries
-
- install_ide_path=${INSTALL_DIR}/${ide_root_path_name}
-
- if [ ! -d ${install_ide_path} ]
- then
- mkdir -p ${install_ide_path}
- fi
-
- cp -rf ${build_result_path}/${archive_platform_name}.${windowing}.${architecture}/${package_name}/* ${install_ide_path}/
+ echo "TARGET_OS : ${TARGET_OS}"
+ case ${TARGET_OS} in
+ ubuntu-32|ubuntu-64)
+ pde_path=${ROOTDIR}/indigo-pde
+ ;;
+ windows-32|windows-64)
+ pde_path=${ROOTDIR}/indigo-winpde
+ ;;
+ macos-64)
+ pde_path=${ROOTDIR}/indigo-macpde
+ ;;
+ *)
+ echo "${TARGET_OS} is not support yet."
+ exit 1
+ ;;
+ esac
+
+ build_script_path=${pde_path}/pde_build
}
# clean
clean()
{
- echo "=========================================CLEAN============================================"
- make clean
- rm -rf ${SRCDIR}/*.zip
- rm -rf ${SRCDIR}/*.tar.gz
- rm -rf ${build_path}
+ echo "=========================================CLEAN============================================"
+ __set_parameter
+ ${build_script_path}/clean.sh ${package_name}
}
# build
build()
{
- echo "=========================================BUILD============================================"
- pkgname_and_platform_list=`awk 'BEGIN{RS="\n\n"; FS="\n"} /Package:/{for(i=1;i<NF;i++){if($i ~ /^OS:/){print $1,$i}}}' ${SRCDIR}/package/pkginfo.manifest | tr ' ' '@'`
- for pkgname_and_platform in ${pkgname_and_platform_list}
- do
- pkgname_and_platform=`echo $pkgname_and_platform | tr '@' ' '`
- package_name=`echo ${pkgname_and_platform} | cut -f1 -d " " | cut -f2 -d ":"`
- platform=`echo ${pkgname_and_platform} | cut -f2 -d " " | cut -f2 -d ":"`
-
- if [ "x${BUILD_TARGET_OS}" = "x${platform}" ]
- then
- build_plugins
- else
- echo ""
- fi
- done
+ echo "=========================================BUILD============================================"
+ pkgname_and_platform_list=`awk 'BEGIN{RS="\n\n"; FS="\n"} /Package:/{for(i=1;i<NF;i++){if($i ~ /^OS:/){print $1,$i}}}' ${SRCDIR}/package/pkginfo.manifest | tr ' ' '@'`
+ for pkgname_and_platform in ${pkgname_and_platform_list}
+ do
+ pkgname_and_platform=`echo $pkgname_and_platform | tr '@' ' '`
+ package_name=`echo ${pkgname_and_platform} | cut -f1 -d " " | cut -f2 -d ":"`
+ platform=`echo ${pkgname_and_platform} | cut -f2 -d " " | cut -f2 -d ":"`
+
+ if [ "x${TARGET_OS}" = "x${platform}" ]
+ then
+ __set_parameter
+ ${build_script_path}/build.sh ${package_name}
+ else
+ echo ""
+ fi
+ done
}
# install
install()
{
- pkgname_and_platform_list=`awk 'BEGIN{RS="\n\n"; FS="\n"} /Package:/{for(i=1;i<NF;i++){if($i ~ /^OS:/){print $1,$i}}}' ${SRCDIR}/package/pkginfo.manifest | tr ' ' '@'`
- for pkgname_and_platform in ${pkgname_and_platform_list}
- do
- echo "=========================================INSTALL============================================"
- pkgname_and_platform=`echo $pkgname_and_platform | tr '@' ' '`
- package_name=`echo ${pkgname_and_platform} | cut -f1 -d " " | cut -f2 -d ":"`
- platform=`echo ${pkgname_and_platform} | cut -f2 -d " " | cut -f2 -d ":"`
-
- if [ "x${BUILD_TARGET_OS}" = "x${platform}" ]
- then
- packaging_plugins
- else
- echo ""
- fi
- done
+ pkgname_and_platform_list=`awk 'BEGIN{RS="\n\n"; FS="\n"} /Package:/{for(i=1;i<NF;i++){if($i ~ /^OS:/){print $1,$i}}}' ${SRCDIR}/package/pkginfo.manifest | tr ' ' '@'`
+ for pkgname_and_platform in ${pkgname_and_platform_list}
+ do
+ echo "=========================================INSTALL============================================"
+ pkgname_and_platform=`echo $pkgname_and_platform | tr '@' ' '`
+ package_name=`echo ${pkgname_and_platform} | cut -f1 -d " " | cut -f2 -d ":"`
+ platform=`echo ${pkgname_and_platform} | cut -f2 -d " " | cut -f2 -d ":"`
+
+ if [ "x${TARGET_OS}" = "x${platform}" ]
+ then
+ __set_parameter
+ INSTALL_DIR=${SRCDIR}/package/${package_name}.package.${TARGET_OS}/data
+ mkdir -p ${INSTALL_DIR}
+ __copy_necessary_binaries
+ ${build_script_path}/install.sh ${package_name}
+ else
+ echo ""
+ fi
+ done
}
[ "$1" = "clean" ] && clean
[ "$1" = "build" ] && build
[ "$1" = "install" ] && install
-exit 0
diff --git a/package/pkginfo.manifest b/package/pkginfo.manifest
index 7f09c0fb0..9cbbcfe6f 100644
--- a/package/pkginfo.manifest
+++ b/package/pkginfo.manifest
@@ -1,19 +1,39 @@
-Package:common-eplugin
-Version:1.0.14
-OS:linux
-Build-host-os:linux
-Build-dependency:indigo-pde [linux], base-ide-product [linux]
-Install-dependency:base-ide-product [linux]
+Version:1.0.64
Source:common-eplugin
-Maintainer:kangho kim <kh5325.kim@samsung.com>, yoonki park <yoonki.park@samsung.com>, hyunsik non <hyunsik.noh@samsung.com>, taeyoung son <taeyoung2.son@samsung.com>, gune Kim <gune.kim@samsung.com>, ho namkoong <ho.namkoong@samsung.com>, hyeongseok heo <hyeong-seok.heo@samsung.com>, gyeongseok seo <gyeongseok.seo@samsung.com>, jihoon song<jihoon80.song@samsung.com>, changhyun lee <changhyun1.lee@samsung.com>, bonyong lee <bonyong.lee@samsung.com>
+Maintainer:kangho kim <kh5325.kim@samsung.com>, yoonki park <yoonki.park@samsung.com>, hyunsik non <hyunsik.noh@samsung.com>, taeyoung son <taeyoung2.son@samsung.com>, gune Kim <gune.kim@samsung.com>, ho namkoong <ho.namkoong@samsung.com>, hyeongseok heo <hyeong-seok.heo@samsung.com>, gyeongseok seo <gyeongseok.seo@samsung.com>, jihoon song <jihoon80.song@samsung.com>, changhyun lee <changhyun1.lee@samsung.com>, bonyong lee <bonyong.lee@samsung.com>
+
+Package:common-eplugin
+OS:ubuntu-32
+Build-host-os:ubuntu-32
+Build-dependency:indigo-pde [ubuntu-32], base-ide-product [ubuntu-32]
+Install-dependency:base-ide-product [ubuntu-32]
Description:Common plugin
Package:common-eplugin
-Version:1.0.14
-OS:windows
-Build-host-os:linux
-Build-dependency:indigo-winpde [windows], base-ide-product [windows]
-Install-dependency:base-ide-product [windows]
-Source:common-eplugin
-Maintainer:kangho kim <kh5325.kim@samsung.com>, yoonki park <yoonki.park@samsung.com>, hyunsik non <hyunsik.noh@samsung.com>, taeyoung son <taeyoung2.son@samsung.com>, gune Kim <gune.kim@samsung.com>, ho namkoong <ho.namkoong@samsung.com>, hyeongseok heo <hyeong-seok.heo@samsung.com>, gyeongseok seo <gyeongseok.seo@samsung.com>, jihoon song<jihoon80.song@samsung.com>, changhyun lee <changhyun1.lee@samsung.com>, bonyong lee <bonyong.lee@samsung.com>
+OS:windows-32
+Build-host-os:ubuntu-32
+Build-dependency:indigo-winpde [windows-32], base-ide-product [windows-32]
+Install-dependency:base-ide-product [windows-32]
+Description:Common plugin
+
+Package:common-eplugin
+OS:ubuntu-64
+Build-host-os:ubuntu-64
+Build-dependency:indigo-pde [ubuntu-64], base-ide-product [ubuntu-64]
+Install-dependency:base-ide-product [ubuntu-64]
Description:Common plugin
+
+Package:common-eplugin
+OS:windows-64
+Build-host-os:ubuntu-64
+Build-dependency:indigo-winpde [windows-64], base-ide-product [windows-64]
+Install-dependency:base-ide-product [windows-64]
+Description:Common plugin
+
+Package:common-eplugin
+OS:macos-64
+Build-host-os:ubuntu-64
+Build-dependency:indigo-macpde [macos-64], base-ide-product [macos-64]
+Install-dependency:base-ide-product [macos-64]
+Description:Common plugin
+