Determine size of popup hint message (THintInfo::HintStr) at runtime - windows

We have a TListView with ShowHint enabled. In the OnInfoTip handler, a hint message is constructed that is specific to the item over which the mouse is hovering. The message may include newline (#13#10) characters.
An override has been created to process CM_HINTSHOW messages and the hint message about to be displayed can be seen in msg.HintInfo.HintStr. It may be possible to calculate the size at runtime but this seems risky because the implementation details may be complex or platform-dependent.
Can the THintInfo be queried for its' bounding rectangle or is there another way to determine exactly how big the popup hint message will be when it is displayed?
This is required so an exact position of the hint (msg.HintInfo.HintPos) can be set.

THintWindow has the function CalcHintRect that can be used for this case. The VCL will use this function when showing a HintWindow:
with HintInfo do
HintWinRect := FHintWindow.CalcHintRect(HintMaxWidth, HintStr, HintData);
As FHintWindow is inaccessible outside of TApplication a temporary instance would need to be created.
procedure TMyListView.CMHintShow(var Message: TCMHintShow);
var
AHintWindow: THintWindow;
AHintWinRect: TRect;
...
begin
AHintWindow := Message.HintInfo.HintWindowClass.Create(nil);
try
AHintWinRect := AHintWindow.CalcHintRect(...);
...
finally
AHintWindow.Free;
end;
end;
How correct this is depends on the THintWindowClass's implementation. But the HintWindow would show incorrectly if one could not rely on it.
A potential pitfall could be in middle-eastern locale when BidiMode is right-to-left. Then following is done additionally:
if FHintWindow.UseRightToLeftAlignment then
with HintWinRect do
begin
Delta := MultiLineWidth(HintInfo.HintStr) + 5;
Dec(Left, Delta);
Dec(Right, Delta);
end;

Related

How to use Image1.Bitmap.BitmapChanged;

Bitmap.BitmapChanged; is protected in FMX.Graphics so I cannot use the procedure.
Useing a TImage or TImageControler I am drawing a line but the line does not show.
I am using this snippet:
imgc1.Bitmap.Canvas.BeginScene;
imgc1.Bitmap.Canvas.DrawLine(FStartPoint,FEndPoint, 100);
imgc1.Bitmap.Canvas.EndScene;
imgc1.Bitmap.BitmapChanged; // the original example said that this would redraw the image. In my CE Rio IDE the BitmapChanged is undefind. How can I use it?
Draw the line. IDE cannot find BitmapChanged.
BitmapChanged is a protected member. I need to write some code to handle the OnBitmapChanged event.
I understand now. Almost 30 years of developing in Delphi and this is the first time I have run into protected members. The examples I was using must not have been compiled else the writer would have had the same error that I had.
TBitmap.BitmapChanged() is a virtual method that simply fires the public TBitmap.OnChange event. Since it is protected, you can use an accessor class to reach it:
type
TBitmapAccess = class(TBitmap)
end;
TBitmapAccess(imgc1.Bitmap).BitmapChanged;
However, this is not really needed. TImage assigns its own internal OnChange event handler to its Bitmap. So it should react to changes to the Bitmap automatically. But, if for some reason it does not, the correct way to refresh the TImage is to call its Repaint() method:
imgc1.Repaint;
Which is exactly what TImage's internal OnChange handler does:
constructor TImage.Create(AOwner: TComponent);
begin
inherited;
FBitmap := TBitmap.Create(0, 0);
FBitmap.OnChange := DoBitmapChanged;
...
end;
procedure TImage.DoBitmapChanged(Sender: TObject);
begin
Repaint;
UpdateEffects;
end;

How do I pass a message from an object to another object in Free Pascal

I have a form and then I have a 'TPageControl' object (named 'MyPages') and a 'TButton' object (named 'MyButton') placed on it at design time.
Then I have a new class called 'TTab' which extends 'TTabSheet'. 'TTab' class has a 'TButton' object as one of its member variables like below.
class TTab = class(TTabSheet)
private
m_btnCloseTab: TButton;
end;
When I click on the 'MyButton', it would create a new 'TTab' object, init the tab (like instantiating the 'm_btnCloseTab') and add it to 'MyPages' at run time.
Procedure TForm1.MyButtonClick(Sender:TObject);
var
newTab: TTab;
newCaption: AnsiString;
begin
newCaption:= 'Tab' + IntToStr(count); //count is a global var
inc(count);
newTab:= TTab.Create(nil);
newTab.Init(newCaption);
newTab.Parent(MyPages);
end;
This is what the TTab.Init(newCaption: AnsiString) Procedure looks like.
Procedure TTab.Init(newCaption: AnsiString);
begin
Self.Caption:= newCaption;
m_btnCloseTab:= TButton.Create(nil);
with m_btnCloseTab do begin
Parent:= Self;
Left:= 10;
Top:= 10;
Caption:= 'Close Tab';
Visible:= True;
OnClick:= #closeTab;
end;
end;
That adds a new tab alright. The close button is also shown on each tab.
How do I click on the 'm_btnCloseTab' on each tab to close that particular tab?
If I define a destructor (by overriding the destructor of the TTabSheet) for TTab like below, I can call it from outside.
Destructor TTab.Destroy;
begin
if m_btnCloseTab <> nil then begin
m_btnCloseTab.Destroy;
m_btnCloseTab:= nil;
end;
inherited;
end;
But I cannot call the Destructor from inside the tab (well, you can). If I do it, I cannot free the m_btnCloseTab object as it would give an exception, because we are still its event handler. If I don't free it, the tab gets closed fine, but the memory gets leaked (because we did not free m_btnCloseTab).
I believe I have to trigger an event so that the destructor can be called from the outside of 'TTab'. I don't know how to do it.
Any help would be appreciated.
Thanks.
You can find Notification methods all over the LCL sources (and in Delphi as well, of course). A simple example is a TLabeledEdit: this is some kind of "TEdit" which contains a TLabel. If the Label is destroyed the LabeledEdit is notified of this because it must set the reference to the label to nil. Otherwise the destructor of TLabeledEdit would attempt to destroy the label again - BOOM. Here the method is like this (pasted from ExtCtrls):
procedure TCustomLabeledEdit.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if (AComponent = FEditLabel) and (Operation = opRemove) then
FEditLabel := nil;
end;
And here you can see what you have to do in your case:
procedure TTab.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if (AComponent = m_BtnCloseTab) and (Operation = opRemove) then
m_BtnCloseTab := nil;
end;
Please note that Notification is a virtual method and must be declared with the attribute "override" in the protected section of the component.
I would use a single button for this task.
Take m_btnCloseTab declaration out of TTab and put it in private main form.
Then on your main form's FormCreate:
m_btnCloseTab := TButton.Create( MyPages );
(the above assumes MyPages is a component placed on the form, if not it must be created first.)
Give the button a top and left that makes sense for your TTab's.
Now m_btnCloseTab will be freed when MyPages is freed which is freed when the form is closed.
Now all you have to do is create your new tabs as you like and when one is focused simply make that tab the parent of your button. You could do this, for instance, in the MyPages OnChange method or whatever it has like that.
When the button is clicked it does something like TTab( Parent ).Free;
However, you may need to store Parent in a local variable in the button's OnClick, say:
TempTab: TTab
Then simply set TempTab := TTab( Parent ), set Button's Parent to nil, then call TempTab.Free;
I would also give your Tabs an owner. That way if the user closes the form with tabs still open (that is, your button hasn't been clicked) the owner will free them.
So declare your tabs like:
newTab:= TTab.Create( MyPages );
This should solve all your problems and, after a bit of fiddling, is quite easy to manage.
One final recommendation I would use the method .Free and/or FreeAndNil( ) rather than calling .destroy directly.

How to get dimensions of an Image which is in Clipboard?

I want to know width and height of Image while it is in Clipboard, because if dimensions are too small then message like "Image is too small" should appear.
How to get width and height?
Unless you are prepared to manually parse the various image formats that you want to support, you can have the VCL simply load the image for you (just make sure suitable TGraphic classes have been registered, such as TGIFImage, TJPEGImage, TPNGImage, etc), and then you can ask the image for its dimensions, eg:
uses
Graphics, Clipbrd, Jpeg, PngImage, ...;
procedure TForm1.BitBtn1Click(Sender: TObject);
var
p: TPicture;
begin
p := TPicture.Create;
try
try
p.Assign(Clipboard);
// use p.Graphic, p.Graphic.Width, p.Graphic.Height as needed...
except
// unable to access Clipboard, or Clipboard
// does not contain a supported image type
end;
finally
p.Free;
end;
end;
If this is about bitmap I think you may try this.
procedure TForm1.BitBtn1Click(Sender: TObject);
var b:TBitmap;
begin
if Clipboard.HasFormat(CF_BITMAP) then begin
b:=TBitmap.Create;
try
b.Assign(Clipboard);
ShowMessage(IntToStr(b.Width)+','+IntToStr(b.Height));
finally
b.Free;
end;
end;
end;
you can instead of showmessage put If-statement and do what ever you want.

How do I render text quickly when each character needs separate placement and formatting?

I try to display formatted text on the screen. At first the very simple HTML text is parsed (there are tags like b,u,i) and then each character is rendered using Canvas.TextOut function in appropriate position and font.
The first thing I noticed is, that rendering of every separate character on the canvas is rather slow. The rendering of whole sentence is much faster. It is obvious, when the canvas is forced to repaint, when form is moved around the screen.
One solution would be to cluster the characters with even fonts and render them at once. But it won't help too much, when the formatting is rich. In addition I need the characters to be the discrete entities, which could be rendered in any way. For example, there is no WinAPI to support text alignment taJustify or in block writing...
Another approach is to render on bitmap, or to use wisely ClipRect property of TCanvas (I haven't tried yet).
Anyway, when the same formatted text is displayed in TRichEdit, there is no time penalty by repaint operation. Another quick example are all major browsers, which has no problem to display tons of formated text... do they render each character like I do, but they do it more efficiently ??? I do not know.
So do you know some recipe to speeding up the application (formatted text rendering?).
Thanx for your ideas...
Sample code: (make TForm as big as possible, grab it with mouse and drag it down under screen. When you move it up, you will see "jumpy" movement)
procedure TForm1.FormPaint(Sender: TObject);
var i, w, h, j:integer;
s:string;
switch:Boolean;
begin
w:=0;
h:=0;
s:='';
for j:=0 to 5 do
for i:=65 to 90 do s:=s + Char(i);
switch:=False; // set true to see the difference
if switch then
begin
for j:=0 to 70 do begin
for i := 1 to Length(s) do
begin
Form1.Canvas.TextOut(50+ w,h +70 , s[i]);
w:=w + Form1.Canvas.TextWidth(s[i]);
end;
w:=0;
h:=h+15;
end;
end
else
begin
for j:=0 to 70 do begin
Form1.Canvas.TextOut(50+ w,h +70 , s);
w:=w + Form1.Canvas.TextWidth(s); // not optimalized just for comparison
w:=0; // not optimalized just for comparison
h:=h+15;
end;
end;
end;
Use a profiler, such as AQTime, to find where your code is actually spending its time. Chances are that it will not be TextOut() itself that is taking the most time. You are indexing through a String one character at a time, passing each character to TextOut() and TextWidth(). Neither of those methods accept Char parameters as input, they only take String input instead, so the RTL is spending effort allocating and freeing a lot of temporary Strings in memory, depending on how long your source String is. I've seen things like that kill loop performance.
To avoid flicker, have best performance and still have all advanced text rendering features (like kerning), the answer is using a temporary bitmap.
Drawing text is very fast in Windows, but displaying a pre-computed bitmap will be much faster.
You can divide your layout to render only the shown part of the text. Or try to split your text into "boxes" of text (just like the great TeX engine does), using a cache for the width of each box. But Windows itself does such caching, so only use such technique if you find a real bottleneck, via proper profiling of the whole code.
Do not reinvent the wheel. On real content, you will find out that text rendering is much more complex than imagined, e.g. if you mix languages and layouts (Arabic and English for instance). You should better rely on Windows, e.g. its UniScribe API, for such complex work. When we made our open source pdf engine, we re-used it as much as possible.
For instance, FireMonkey suffers from reinventing the wheel, and fails when rendering complex text content. So using existing APIs is IMHO the best path...
On my pc, it's about twice as fast when you render to a bitmap, and then draw that to the canvas. Well, the slow version becomes twice as fast. The fast version stays the same.
Another optimization that might work.
You can also pre-calculate character widths into an array, so you don't have to call canvas.TextWidth() often.
Keep a variable like this
widths:array[char] of byte;
Fill it like this:
for c := low(widths) to high(widths) do
widths[c] := Canvas.TextWidth(char(c));
Filling this 65536 element array is slow, so perhaps it's better to just create a 65..90 element-array, and drop unicode-support.
Another thing..
Calling Winapi.Windows.TextOut() is faster than canvas.TextOut().
You can actually win a lot with that.
Winapi.Windows.TextOut(bmp.Canvas.Handle, w, h, #s[i], 1);
Modified version of your code:
// set up of off-screen bitmap.. needs to be resized when the form resizes.
procedure TForm1.FormCreate(Sender: TObject);
begin
bmp := TBitmap.Create;
bmp.SetSize(width,height);
end;
This is
procedure TForm36.PaintIt2;
var h,i,j,w: Integer; s: string;
begin
w := 0; h := 0; s := '';
for j := 0 to 5 do
for i := 65 to 90 do
s := s + Char(i);
bmp.Canvas.Brush.Color := Color;
bmp.Canvas.FillRect(bmp.Canvas.ClipRect);
if Checkbox1.Checked then
begin
for j := 0 to 70 do
begin
for i := 1 to Length(s) do
begin
Winapi.Windows.TextOut(bmp.Canvas.Handle, w, h, #s[i], 1);
w := w + widths[s[i]];
end;
w := 0; h := h + 15;
end;
end
else
for j := 0 to 70 do
begin
bmp.Canvas.TextOut(w, h, s);
w := 0; h := h + 15;
end;
canvas.Draw(0,0,bmp);
end;
I timed the performance with this procedure:
procedure TForm1.Button2Click(Sender: TObject);
var i : Integer; const iterations=300;
begin
with TStopwatch.StartNew do
begin
for I := 1 to iterations do
PaintIt2;
Caption := IntToStr(Elapsed.Ticks div iterations);
end;
end;
Last note:
I've tried disabling cleartype/anti-aliasing, but strangely enough that makes rendering twice as slow! This is how I turned anti-aliasing off:
tagLOGFONT: TLogFont;
GetObject(
bmp.Canvas.Font.Handle,
SizeOf(TLogFont),
#tagLOGFONT);
tagLOGFONT.lfQuality := NONANTIALIASED_QUALITY;
bmp.Canvas.Font.Handle := CreateFontIndirect(tagLOGFONT);

How do I add dock-icon badge and popupmenu support for lazarus apps in OSX?

I've tried googling around abit but I cannot find any help in using the badge feature of dock-icons on OSX aswell as getting access to the dock icon menu? I guess I could change the dock icon during run to indicate something is up but it isn't as sleek ;)
This feature isn't implemented in LCL, so if you want to use it, you will have to use the relevant Cocoa framework directly. You can use ObjPas for that. Of course if you are up for writing an LCL implementation, that would be a better long term solution, as it could be made to work on Windows/Gnome later.
Ludicrous late ... but I bumped into this post, and found this post in the Lazarus Forum, which shows code how you can change the application icon in the dock while the application is running.
Hope it will be of use for someone looking for an answer to the same question, even though it's years after the post of the original question. (apologies if this is not appropriate)
uses
... MacOSAll ...
procedure TFrm_Main.FormCreate(Sender: TObject);
begin
...
FResPath := TrimFilename(ExtractFilePath(Application.ExeName) + PathDelim + 'Resource');
...
end;
procedure TFrm_Main.SomeEventWhenOverlay(SomeVar: Integer);
var
temp_ImagePath: String;
temp_CGDataProvider: CGDataProviderRef;
temp_Float32Ptr: Float32Ptr;
temp_CGImage: CGImageRef;
temp_CGContext: CGContextRef;
begin
temp_ImagePath := TrimFilename(FResPath + PathDelim + 'Image' + PathDelim + 'overlay_image.png'); // image must be same size as icon, if not, will be deformed
if (FileExists(temp_ImagePath)) then
begin
temp_CGDataProvider := CGDataProviderCreateWithFilename(PChar(temp_ImagePath));
temp_Float32Ptr := nil;
temp_CGImage := CGImageCreateWithPNGDataProvider(temp_CGDataProvider, temp_Float32Ptr, 1, kCGRenderingIntentDefault);
CGDataProviderRelease(temp_CGDataProvider);
// Draw image
temp_CGContext := BeginCGContextForApplicationDockTile;
//SetApplicationDockTileImage(temp_CGImage);
OverlayApplicationDockTileImage(temp_CGImage);
CGImageRelease(temp_CGImage);
EndCGContextForApplicationDockTile(temp_CGContext);
end;
end;
procedure TFrm_Main.SomeOtherEventWhenRestore();
begin
//This will not work if you use SetApplicationDockTileImage
RestoreApplicationDockTileImage;
end;

Resources