Sort SWT table on cell text - swt

I have an SWT Table which I use with a JFace TableViewer.
I want to have the table sorted with a comparator that works with the text in the table cells, not with the model elements in the viewer.
Is that any good way to do this?
Motivation
I'm trying to do this because sorting a table on the cell text works in almost all cases, and it saves me from having to create separate comparators for each model object property that I want to be able to sort on.
Details
The problem is tables are normally sorted using a ViewerComparator set on the viewer. Its compare method does not have access to the position in the table of its argument elements:
new ViewerComparator() {
#Override
public int compare(Viewer viewer, Object elem1, Object elem2) {
// There seems to be no good way to get the
// text of the table cells here
}
}
Bad solutions I have considered
Looking up the cell widget in ViewerComparator#compare using StructuredViewer#findItem. This probably works, but I have to sub-class all viewers to make that method public.
Translating the compared elements into strings using the label provider in ViewerComparator#compare. This does not work, since most label providers I use are CellLabelProvider, and I don't find a way to call update on them to get the table text.

You could make your cell label provider implement ILabelProvider so that it has a getText method.
You could look at the getTextFromLabelProvider method of org.eclipse.e4.ui.dialogs.filteredtree.PatternFilter which has a similar problem:
private String getTextFromLabelProvider(IBaseLabelProvider baseLabelProvider, Object element) {
if (baseLabelProvider == null) {
return null;
}
String labelText = null;
if (baseLabelProvider instanceof ILabelProvider) {
labelText = ((ILabelProvider) baseLabelProvider).getText(element);
} else if (baseLabelProvider instanceof IStyledLabelProvider) {
labelText = ((IStyledLabelProvider) baseLabelProvider).getStyledText(element).getString();
} else if (baseLabelProvider instanceof DelegatingStyledCellLabelProvider) {
IStyledLabelProvider styledStringProvider = ((DelegatingStyledCellLabelProvider) baseLabelProvider)
.getStyledStringProvider();
StyledString styledText = styledStringProvider.getStyledText(element);
if (styledText != null) {
labelText = styledText.getString();
}
}
return labelText;
}

Related

TextCellEditor with autocomplete in Eclipse SWT/JFace?

I'd like a TextCellEditor with the standard auto-complete behaviour, that that any user nowadays expects when typing inside an input cell with a list of suggested strings. For a good working example of what I'm after, in Javascript, see this jQuery autocomplete widget.
I couldn't find a good example.
I only found (aside from some tiny variations) this TextCellEditorWithContentProposal snippet. But that leaves a lot to be desired:
It lists all the words, irrespective of the "partial word" typed in the cell (no partial matching)
When the desired word is selected, it is appended to the partial word, instead of replacing it
The interaction is ugly and non-intuitive. For example, one would expect the
Escape key to tear off the list of suggestions; again, see the Javascript example; here, it also removes the typed letters.
It looks strange to me that such an standard and useful component is not available. Or perhaps it is available? Can someone point to me to a more apt snippet or example?
The example you are linking to is a code snippet intended to showcase the API and guide you toward customizing the control to your preference.
Some of your complaints are either invalid or can easily be fixed using public API.
Let's go through them in detail.
All proposals are listed, irrespective of typed text
Note that in the snippet an org.eclipse.jface.fieldassist.SimpleContentProposalProvider is used:
IContentProposalProvider contentProposalProvider = new SimpleContentProposalProvider(new String[] { "red",
"green", "blue" });
cellEditor = new TextCellEditorWithContentProposal(viewer.getTable(), contentProposalProvider, null, null);
As suggested in its javadoc it is:
designed to map a static list of Strings to content proposals
To enable a simple filtering of the contents for the snippet, you could call: contentProposalProvider.setFiltering(true);
For anything more complex you will have to replace this with your own implementation of org.eclipse.jface.fieldassist.IContentProposalProvider.
Selection is appended to cell contents, instead of replacing it
The content proposal behavior is defined in the org.eclipse.jface.fieldassist.ContentProposalAdapter. Again a simple method call to org.eclipse.jface.fieldassist.ContentProposalAdapter.setProposalAcceptanceStyle(int) will achieve your target behavior:
contentProposalAdapter = new ContentProposalAdapter(text, new TextContentAdapter(), contentProposalProvider, keyStroke, autoActivationCharacters);
contentProposalAdapter.setProposalAcceptanceStyle(ContentProposalAdapter.PROPOSAL_REPLACE);
Cancelling the proposal should not remove typed content
This is hard to do using just the API, since the ContentProposalAdapter does only propagate the key strokes to the opened ContentProposalPopup without storing them.
You would have to subclass ContentProposalAdapter, in order to have access to ContentProposalAdapter.ContentProposalPopup.filterText.
Most of the functionality in this snippet with sensible defaults can also be obtained in a more simple way by using an org.eclipse.jface.fieldassist.AutoCompleteField.
Here is a snippet showing you a simple implementation. You have to customize it but it give you the way.
Note, this is not a generic copy/paste of the documentation or an explanation about the doc.
String[] contentProposals = {"text", "test", "generated"};
// simple content provider based on string array
SimpleContentProposalProvider provider = new SimpleContentProposalProvider(contentProposals);
// enable filtering or disabled it if you are using your own implementation
provider.setFiltering(false);
// content adapter with no keywords and caracters filtering
ContentProposalAdapter adapter = new ContentProposalAdapter(yourcontrolswt, new TextContentAdapter(), provider, null, null);
// you should not replace text content, you will to it bellow
adapter.setProposalAcceptanceStyle(ContentProposalAdapter.PROPOSAL_IGNORE);
// now just put your implementation
adapter.addContentProposalListener(new IContentProposalListener() {
#Override
public void proposalAccepted(IContentProposal proposal) {
if(proposal != null && StringUtils.isNotBlank(proposal.getContent())){
// you need filter with blank spaces
String contentTextField = getFilterControl().getText();
String[] currentWords = getFilterControl().getText().split(" ");
StringBuilder textToDisplay = new StringBuilder();
if(currentWords.length > 1) {
// delete and replace last word
String lastWord = currentWords[currentWords.length-1];
textToDisplay.append(contentTextField.substring(0, contentTextField.length()-1-lastWord.length()));
textToDisplay.append(" ");
}
// add current proposal to control text content
textToDisplay.append(proposal.getContent());
yourcontrolswt.setText(textToDisplay.toString());
}
}
});
If you want more you can also have your own content proposal provider If you need a particular object instead of string or something like.
public class SubstringMatchContentProposalProvider implements IContentProposalProvider {
private List<String> proposals = Collections.emptyList();
#Override
public IContentProposal[] getProposals(String contents, int position) {
if (position == 0) {
return null;
}
String[] allWords = contents.split(" ");
// no words available
if(allWords.length == 0 || StringUtils.isBlank(allWords[allWords.length-1]))
return null;
// auto completion on last word found
String lastWordFound = allWords[allWords.length-1];
Pattern pattern = Pattern.compile(lastWordFound,
Pattern.LITERAL | Pattern.CASE_INSENSITIVE /*| Pattern.UNICODE_CASE*/); // this should be not used for better performances
IContentProposal[] filteredProposals = proposals.stream()
.filter(proposal -> proposal.length() >= lastWordFound.length() && pattern.matcher(proposal).find())
.map(ContentProposal::new).toArray(IContentProposal[]::new);
// no result
return filteredProposals.length == 0 ? null : filteredProposals;
}
public void setProposals(List<String> proposals) {
this.proposals = proposals;
}
}

GWT-Charts ColumnFunction not working?

I just want to make sure I'm not doing something wrong before I file a bug/start digging in GWT-Charts code...
Trying to style a LineChart:
DataViewColumn ret = DataViewColumn.create(new ColumnFunction() {
#Override
public Object calc(DataTable dataTable, int row) {
if (dataTable.isValueNull(i, dataColumn)
|| dataTable.getValueNumber(i, dataColumn) < value) {
return "color: red";
}
return "color: green";
}
}, ColumnType.STRING);
ret.setRole(RoleType.STYLE);
(I had to add RoleType.STYLE myself, custom-built 0.9.11-SNAPSHOT off Master)
But adding that column results in (using new JSONObject(columns)):
{
"0":{"sourceColumn":0},
"1":{"sourceColumn":1, "label":"Data"},
"2":{"calc":{}, "type":"string", "role":"style"}
}
Note the empty set for "calc"?
I tried just doing a ColumnFunction for Data (returning a flat value) in case the "style" Role required more than just adding to the RoleType Enum, and that also doesn't seem to be getting passed through.
The JSNI in DataViewColumn.setCalc(ColumnFunction) seems to be right to me, so I'm not sure where the issue lies...
UPDATE:
Putting debugging statements in the ColumnFunction showed it to be running, but the output didn't seem to be getting used.
Turns out that DataViewColumn.setCalc was missing the return statement in its JSNI wrapper.
DataViewColumn.setCalc:
/**
* Sets a function that will be called for each row in the column to calculate a value for that cell.
*
* #param columnFunction a function for calculating each row value
*/
public final native void setCalc(ColumnFunction columnFunction) /*-{
this.calc = function(dataTable, row) {
columnFunction.#com.googlecode.gwt.charts.client.ColumnFunction::calc(Lcom/googlecode/gwt/charts/client/DataTable;I) (dataTable, row);
};
}-*/;
Was not returning the value calculated by the function, just calculating it.
Adding "return" to the line in the innermost block fixes the issue.

MVC how do i populate dropdownlist without using a model

I am using mvc 4, i have a form in a view (not binded to a model), its using standard html elements.
I want to populate a dropdownlist from a list value (i.e return from controller action)
also based on the selection of a value from the first dropdownlist i want to populate a second dropdownlist
can someone please guide
for the first dropdownlist you loop thru all the available options and add in <option> tags inside <select> for the second dropdownlist you need to either make bunch drop downs and hide/show them, or you create one big list and remove invalid entries base on the first list's selection. You would definitely need to do javascript for 2nd list.
If you don't want to use a Model (you should though), you will have to add the items to ViewData
I'll stub something out for you and you can complete the rest.
Inside your controller, create a list object of what you need. If you are using EntityFrameWork this will look familiar.
var list = context.Table.ToList();
List<System.Web.Mvc.SelectListItem> ddlItems = new List<System.Web.Mvc.SelectListItem>();
foreach (var item in list)
{
ddlItems.Add(new SelectListItem(){ Text = item.Text, Value = item.Value.ToString()});
}
ViewData["DDLItems"] = ddlItems;
#Html.DropDownListFor(x => x.LeagueId,
new SelectList((System.Collections.IEnumerable)ViewData["DDLItems"], "Value", "Text")
, "--Select League--", new { id = "league" })
You can define your second dropdownlist with just a placeholder until the cascade effect happens.
#Html.DropDownListFor(x => x.DivisionId, Enumerable.Empty<SelectListItem>(),
"--Select Division--", new { id = "ddlDivision" })
Your going to need to use JQuery and fire and event when the dropdown changes, and then use Ajax to make a call back to the controller. Theres 2348239 examples online about making Ajax calls, know how to do that because it's done all the time in MVC.
I'll let you figure that part out. One hint, inside the Ajax call you can pass data to the controller. something like this data: { leagueId: value } where value is the value of the dropdownlist you want to cascade off of. leagueId must match type and name of the parameter your controller will expect.
Return a Json object from your controller like so...
public JsonResult GetDivisions(int leagueId)
{
var division = //similar to before, fill a list.
return Json(divisions, JsonRequestBehavior.AllowGet);
}
And then in the success function of your Ajax call, you will populate the Second dropdownlist.
success: function (data) {
$.each(data, function (index, item)
$('#ddlDivision')
.append($('<option></option>')
.val(item.Value)
.html(item.Text))
item.Value and item.Text can be anything, just as long as the Json you return as the properties of Text and Value
IE...
var divisions = (from x in context.Division
select new
{
Text = league + " " + x.Region,
Value = x.DivisionId
}).ToList();

method based on variable type

I just have the following scenario
i want to return string from method but the method should be based on variable type which is (Type CType)
i need to make the render class like this
public string render(TextBox ctype){
return "its text box";
}
public string render(DropDown ctype){
return "its drop down";
}
you know TextBox is a Type thats why i can declare the Type variable like this
var CType = typeof(TextBox)
and i need to call the render method like this
render(Ctype);
so if the Ctype is type of TextBox it should call the render(TextBox ctype)
and so on
How can i make it ?
you should use a template function
public customRender<T>(T ctype)
{
if(ctype is TextBox){
//render textbox
}
else if(ctype is DropDown){
//render dropdown
}
}
hope it will help
First of all, even if you don't see an if or a switch, there will still be one somewhere hidden inside some functions. Distinguishing types at runtime that are not known at compile-time simply will not be possible without any such kind of branching of the control flow.
You can use one of the collection classes to build a map at runtime that maps Type instances to Func<T, TResult> methods. For example, you can use the Dictionary type to create such a map:
var rendererFuncs = new Dictionary<Type, Func<object, string>>();
You could then add some entries to that dictionary like this:
rendererFuncs[typeof(TextBox)] = ctype => "its text box";
rendererFuncs[typeof(DropDown)] = ctype => "its drop down";
Later on, you can call the appropriate function like this:
string renderedValue = rendererFuncs[Ctype.GetType()](Ctype);
Or, if you want to be on the safe side (in case there are Ctype values that have no appropriate renderer):
string renderedValue;
Func<object, string> renderer;
if (rendererFuncs.TryGetValue(Ctype.GetType(), out renderer)) {
renderedValue = renderer(Ctype);
} else {
renderedValue = "(no renderer found)";
}
Note that this will only work for as long as Ctype is of the exact type used as a key in the dictionary; if you want any subtypes to be correctly recognized as well, drop the dictionary and build your own map that traverses the inheritance hierarchy of the type being searched (by using the Type.BaseType property).

Zend Framework: is there a way to access the element name from within a custom validator?

I'm writing a custom validator that will validate against multiple other form element values. In my form, I call my custom validator like this:
$textFieldOne = new Zend_Form_Element_Text('textFieldOne');
$textFieldOne->setAllowEmpty(false)
->addValidator('OnlyOneHasValue', false, array(array('textFieldTwo', 'textFieldThree')));
My validator will check that only one of those three fields (textFieldOne, textFieldTwo, textFieldThree) has a value. I want to prevent a future developer from accidentally passing the same field twice.
$textFieldOne->addValidator('OnlyOneHasValue', false, array(array('textFieldOne', 'textFieldTwo', 'textFieldThree')));
So far, my validator works perfectly, except when I pass the same field name as the field that has the valiator set on it.
In my validator, you can see that I am checking that the value (of the element with the validator set on it). I'm also checking the values of the other fields that were passed to the validator.
public function isValid($value, $context = null) {
$this->_setValue($value);
$this->_context = $context;
if ($this->valueIsNotEmpty()) {
if ($this->numberOfFieldsWithAValue() == 0) {
return true;
}
$this->_error(self::MULTIPLE_VALUES);
return false;
}
if ($this->numberOfFieldsWithAValue() == 0) {
$this->_error(self::ALL_EMPTY);
return false;
}
if ($this->numberOfFieldsWithAValue() == 1) {
return true;
}
if ($this->numberOfFieldsWithAValue() > 1) {
$this->_error(self::MULTIPLE_VALUES);
return false;
}
}
private function valueIsNotEmpty() {
return Zend_Validate::is($this->_value, 'NotEmpty');
}
private function numberOfFieldsWithAValue() {
$fieldsWithValue = 0;
foreach ($this->_fieldsToMatch as $fieldName) {
if (isset($this->_context[$fieldName]) && Zend_Validate::is($this->_context[$fieldName], 'NotEmpty')) {
$fieldsWithValue++;
}
}
return $fieldsWithValue;
}
My solution is to either...
A. Let the developer figure out there is a certain way to do it.
B. Ignore $value, forcing you to pass all the elements (which isn't much different than the first option).
or C. (if possible) Find the name of the element that called my validator in the first place and ignore it from the list of $fieldsWithValue.
I don't think there is a way to apply a validator on a form without attaching it to an element, but that would be even better, if it were an option.
How can I solve this problem?
Normaly i'd advise against such things, but, in this case I believe a static member in your class would actually provide a good solution to this problem.
With a static member, you can set it to the value in the first time the isValid is called, and check against it in subsequent calls, thus giving you a mechanism for this.
You may want to set this up to use some array in the configuration options, so that you can namespace and allow multiple instances of the validator to exist happily alongside each other for different sets.
The only problem that you really have to decide how to overcome, is where you wish to display the error, as yes the form itself does not take validators. if you want all the duplicates after the first to display an error, it is not so much of a problem.