How to handle first tab size on formatting? - visual-studio-extensions

I create an extension, that format vs editor tabs in custom ways, using ITextParagraphPropertiesFactoryService class. Everything works just fine, expect the fact, that when user enter new line, ITextParagraphPropertiesFactoryService doesnt affect to the new line
For simplifying the problem, I create a new MEF project, add a format provider like this
[Export(typeof(ITextParagraphPropertiesFactoryService))]
[ContentType("text")]
[TextViewRole(PredefinedTextViewRoles.Document)]
internal class ElasticTabstopsProvider : ITextParagraphPropertiesFactoryService
{
/// <summary>
/// Creates an ElasticTabstopsFormatters for
/// the provided configuration.
/// </summary>
public TextParagraphProperties Create(IFormattedLineSource formattedLineSource, TextFormattingRunProperties textProperties,
IMappingSpan line, IMappingPoint lineStart, int lineSegment)
{
return new TextFormattingParagraphProperties(textProperties, 1);
}
}
And it changes all tabs width from my editor to 1. Great! This is what I want. But now when I press Enter(new line) new cursor is set under Main, however I expect tab widths to be 1.
After I start typing it goes to expected position.
The question is, how can I set new line empty line tab size?
I try to override ISmartIndentProvider, but seems vs ignore that value.
Debuger stops on breakpoint in method
int? GetDesiredIndentation(ITextSnapshotLine currentLine)
of ISmartIndent, but indent stays the same no matter what value I return...

There are at least two reasons why your ISmartIndentProvider's indent is being ignored:
First, there are lots of places with the current C# and VB language services where we explicitly set the caret position in response to certain keypresses. Enter is one of them. It's quite possible that in your scenario, we're explicitly setting the position. Short of disabling smart indenting in Tools > Options, there's nothing you can do to override that. Since you said you're getting a debugger hit in your ISmartIndentProvider, that's probably the issue here.
Second, if you're trying to define a ISmartIndentProvider for content type "text", yours won't get called if there is a language-specific provider. There's also another provider for "text" already (which calls the shimmed old language services) which might win over yours anyways.
To be honest, if you're trying to do something fancy where you don't want automatic indenting, then you really should just turn it off to ensure it's not getting in your way.

Related

JavaFX TableView multiline tooltip with cell factory and bindings

I have using this code snippet to create tooltips for every tableView cell I propagate via cell factories:
private <T> void addFileTooltipToCells(TableColumn<FileTableBean,T> column) {
Callback<TableColumn<FileTableBean, T>, TableCell<FileTableBean,T>> existingCellFactory = column.getCellFactory();
column.setCellFactory(c -> {
TableCell<FileTableBean, T> cell = existingCellFactory.call(c);
Tooltip tooltip = new Tooltip();
tooltip.textProperty().bind(cell.itemProperty().asString());
tooltip.setShowDuration(Duration.seconds(30));
tooltip.setStyle("-fx-font-size: 12");
cell.setTooltip(tooltip);
return cell;
});
}
Problem is that the tooltips can sometimes have lots of data and should be multilined. From here I found that one should simply wrap the tooltips with and possibly set where necessary. However, the above carefully somewhere copied and trial-error tested code snippet doesn't like the idea. I have tried:
tooltip.textProperty().bind("<html>"+cell.itemProperty().asString()+"</html>");
tooltip.setText("<html>"+cell.itemProperty().asString()+"</html>");
First says in IDE: Incompatible String cannot be converted to ObservableValue
Second one generater following tooltips: " String binding [invalid] " :)
And before somebody starts with the usual "the error message says it all, read it" stuff, I know that there are probably a simple answer for this, but having these lambdas combined with the binding concept and cellfactories, I just have to give up and try to get some guidance from here.
Answer to those who face the same problem. You can use the "normal" binding but just apply the tooltip preferences to every tooltip the cellfactory creates simply by defining:
tooltip.setMaxWidth(750);
tooltip.setWrapText(true);
Setting preferable width will create tooltips with lots of extra blanks if the data is shorter than the width. Max width works like a charm. Next step is probably to make width parameter dynamic so that it calculates the max width based on stage resolution.

How to get return value in this case? (Java FX)

I'm writing part of a cross-platform application, where we mostly use REST (jersey) and Hibernate to communicate between systems. I'm new to JavaFX, but my side of the program should use it to get input values from users. Here is how the code flow would look:
public class startingClass{
...
public void startingMethod(Payload payload){
//send REST requests to different places with different payloads, like:
Response response = Utility.sendPostRequest(URI, payload2);
something = response.readEntity(something.class)
//more processing with the returned values
...
}}
In one of the places where I sent a request:
#Path("something")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON + ";charset=UTF-8")
public class Resource{
...
#POST
#Path(something)
public Response doSomething(Payload payload) {
//show JavaFX window with text fields and an okay button
JavaFXClass.launch(JavaFXClass.class);
/* THIS IS WHERE I would need to get back the input values somehow */
//payload3 has the input values I need to send back
return Response.entity(payload3).build();
}}
The JavaFX class extends application and and overrides the (void) start method where I put together the window I want to show and after the button click (if inputs are okay) I close the window.
So the idea is that the startingMethod would have to wait, until the response comes back (maybe return with some default values, if the user doesnt type in anything for a minute - what would be the elegant solution for that?) with the input values. This would guarantee the sync.
If I use more REST or database saves inside the JavaFX class then I can't be sure the values are there by the time I wanna use them in the startingMethod (probably not) and it's probably a really bad looking solution anyway.
What could I do? I dont know much about callback methods in javafx, can those help me here? Thanks!
In the end I moved the JavaFXClass into the Resource class. Meaning Resource class extends Application, overrides start, etc. In the doSomethingMethod I call launch in a try-catch block, catch the IllegalStateException if needed and call start() instead (also in a try-catch block). The textfield input values are stored in a global variable after.
Also in the start() method I havePlatform.setImplicitExit(false);
so the doSomethingMethod() can be called multiple times without a problem, starting the javaFX window. It's not a pretty solution.

Visual Studio SDK - How to add a margin glyph on command invoked?

How can I modify this sample: https://msdn.microsoft.com/en-us/library/ee361745.aspx to have glyphs added to the margin when a button I added is clicked?
I have a button which creates a special kind of breakpoint. I would like this kind to be recognized by my own margin glyph. So I wrote the GetTags method in my Tagger class as follows:
IEnumerable<ITagSpan<MyBreakpointTag>> ITagger<MyBreakpointTag>.GetTags(NormalizedSnapshotSpanCollection spans)
{
if (BreakpointManager != null)
{
DTE2 ide = ServiceProvider.GlobalProvider.GetService(typeof(DTE)) as DTE2;
Document document = ide.ActiveDocument;
foreach (SnapshotSpan span in spans)
{
ITextSnapshot textSnapshot = span.Snapshot;
foreach (ITextSnapshotLine textSnapshotLine in textSnapshot.Lines)
{
if (BreakpointManager.IsMyBreakpointAt(document.FullName, textSnapshotLine.LineNumber + 1))
{
yield return new TagSpan<MyBreakpointTag>(new SnapshotSpan(textSnapshotLine.Start, 1),
new MyBreakpointTag());
}
}
}
}
}
However, glyphs are added after moving the cursor to a different line of code or making changes to the code. What do I have to do to have glyphs added right after the button is clicked?
GetTags is called by the editor whenever a layout happens, but the editor won't call it for any random reason. (Think: how would it know when to call you?) You need to raise the TagsChanged event from your tagger to say the tags for a given span changed, and then it'll call GetTags again to refresh.
As an unrelated piece of advice: you shouldn't be using DTE.ActiveDocument in your GetTags for a few reasons:
GetTags should be as fast as possible...calling DTE methods are rarely fast.
Imagine you have two files open, and GetTags is called for the non-active file. That would have both files looking at the same filename which is probably bad. There's code here that shows how to fetch the file name from an ITextBuffer.
This is copied from my answer here. Basically, changing from using ITaggerProvider to IViewTaggerProvider allowed me to redraw the glyphs. I used the Implementing a Brace Matching Tagger Provider section in Walkthrough: Displaying Matching Braces example to make these changes.
Using the IViewTaggerProvider, you can then call
TagsChanged?.Invoke(this, new SnapshotSpanEventArgs(
new SnapshotSpan(
SourceBuffer.CurrentSnapshot,
0,
SourceBuffer.CurrentSnapshot.Length)));
in your functions to explicitly call GetTags and go over the spans in the current snapshot.

How to listen to visible changes to the JavaFX SceneGraph for specific node

We created a small painting application in JavaFX. A new requirement arose, where we have to warn the user, that he made changes, which are not yet persisted and asking him, if the user might like to save first before closing.
Sample Snapshot:
Unfortunately there are a lot of different Nodes, and Nodes can be changed in many ways, like for example a Polygon point can move. The Node itself can be dragged. They can be rotated and many more. So before firing a zillion events for every possible change of a Node object to the canvas I`d like to ask, if anyone might have an idea on how to simplify this approach. I am curious, if there are any listeners, that I can listen to any changes of the canvas object within the scene graph of JavaFX.
Especially since I just want to know if anything has changed and not really need to know the specific change.
Moreover, I also do not want to get every single event, like a simple select, which causes a border to be shown around the selected node (like shown on the image), which does not necessary mean, that the user has to save his application before leaving.
Anyone have an idea? Or do I really need to fire Events for every single change within a Node?
I think you are approaching this problem in the wrong way. The nodes displayed on screen should just be a visual representation of an underlying model. All you really need to know is that the underlying model has changed.
If, for example, you were writing a text editor, the text displayed on the screen would be backed by some sort of model. Let's assume the model is a String. You wouldn't need to check if any of the text nodes displayed on screen had changed you would just need to compare the original string data with the current string data to determine if you need to prompt the user to save.
Benjamin's answer is probably the best one here: you should use an underlying model, and that model can easily check if relevant state has changed. At some point in the development of your application, you will come to the point where you realize this is the correct way to do things. It seems like you have reached that point.
However, if you want to delay the inevitable redesign of your application a little further (and make it a bit more painful when you do get to that point ;) ), here's another approach you might consider.
Obviously, you have some kind of Pane that is holding the objects that are being painted. The user must be creating those objects and you're adding them to the pane at some point. Just create a method that handles that addition, and registers an invalidation listener with the properties of interest when you do. The structure will look something like this:
private final ReadOnlyBooleanWrapper unsavedChanges =
new ReadOnlyBooleanWrapper(this, "unsavedChanged", false);
private final ChangeListener<Object> unsavedChangeListener =
(obs, oldValue, newValue) -> unsavedChanges.set(true);
private Pane drawingPane ;
// ...
Button saveButton = new Button("Save");
saveButton.disableProperty().bind(unsavedChanges.not());
// ...
#SafeVarArgs
private final <T extends Node> void addNodeToDrawingPane(
T node, Function<T, ObservableValue<?>>... properties) {
Stream.of(properties).forEach(
property -> property.apply(node).addListener(unsavedChangeListener));
drawingPane.getChildren().add(node);
}
Now you can do things like
Rectangle rect = new Rectangle();
addNodeToDrawingPane(rect,
Rectangle::xProperty, Rectangle::yProperty,
Rectangle::widthProperty, Rectangle::heightProperty);
and
Text text = new Text();
addNodeToDrawingPane(text,
Text::xProperty, Text::yProperty, Text::textProperty);
I.e. you just specify the properties to observe when you add the new node. You can create a remove method which removes the listener too. The amount of extra code on top of what you already have is pretty minimal, as (probably, I haven't seen your code) is the refactoring.
Again, you should really have a separate view model, etc. I wanted to post this to show that #kleopatra's first comment on the question ("Listen for invalidation of relevant state") doesn't necessarily involve a lot of work if you approach it in the right way. At first, I thought this approach was incompatible with #Tomas Mikula's mention of undo/redo functionality, but you may even be able to use this approach as a basis for that too.

Flex - Is there a way to specify what direction a ComboBox will open?

Maybe I should further qualify this - Is there a way to specify which direction a ComboBox will open without copying and pasting the entire ComboBox class and ripping out the code where it determines which direction it will open in...
I'm my specific case - I need it to open upwards - always.
UPDATE: You can't fix this by subclassing it because the function that handles the direction of the opening is:
private function displayDropdown(show:Boolean, trigger:Event = null):void
And that bad boy uses a fair amount of private variables which my subclass wouldn't have access to...
If you build up the Menu object yourself, you can place the menu anywhere you want by simply setting the x,y coordinates of the menu object. You'll need to calculate those coordinates, but you might be able to do this easily without subclassing ComboBox.
I am doing something similar with PopUpButton; you might find it easier to work with PopUpButton. This is based on real code from my current project:
private function initMenu(): void {
var m:Menu = new Menu();
m.dataProvider = theMenuData;
m.addEventListener(MenuEvent.ITEM_CLICK, menuClick);
m.showRoot = false;
// m.x = ... <-- probably don't need to tweak this.
// m.y = ... <-- this is really the interesting one :-)
theMenu.popUp = m;
}
<mx:PopUpButton id="theMenu" creationComplete="initMenu()" ... />
BTW, to get the PopUpButton to act more like I wanted it (always popup, no matter where the click), setting openAlways=true in the MXML works like a charm.
I doubt it - you'd need to subclass the control (which isn't that big a deal.)
Maybe you could mess with the real estate so it's placed in such a fashion (e.g. crowded into the lower right corner) that up is naturally coerced?
I would recommend checking out this post. Yes, you do have to grab the ComboBox code and modify it, but at least now you have an idea where the modifications need to go.
You could set the MaxDropDownHeight, if you set it big enough Windows will automatically set the direction upwards.
This irritated me no end. I have uploaded a solution, its a simple Class that extends the PopUpButton and removes the logic of stage bounds detection as it failed 50% of the time anyway. My code just allows you to simply specify whether you want to open the menu up or down:
http://gist.github.com/505255

Resources