TTreeView Drag and Drop, with ghost image lazarus / 21-General ---------------------------------------------------------------------- geraldholdsworth · 2021-02-03 13:27 Hi all, I have a TTreeView acting as a file tree viewer. I wish to be able to drag and drop files from one folder to another. OK, this seems pretty easy thing to do - and indeed it is, and I've managed to write the code and it works. But, the aesthetics are not good - there is no indication that anything has been picked up and is being moved. The '+' symbol, in green, flashes on occasionally, but doesn't stay on - this is not a huge issue because I highlight the folder which it can be dropped onto. What I'd ideally like to do is have a 'ghost' image of the file/node being dragged. Previously, in Delphi, I've managed this using the attached unit (which I didn't write, btw). OK, this was for dragging TImages from one panel to another. It worked, and worked well. But, it doesn't work here - I create an image for it to display instead of picking up the one being dragged (as there isn't one to be dragged, if you know what I mean). The drag/drop code is: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i procedure TMainForm.DirListDragDrop(Sender, Source: TObject; X, Y: Integer);var Dst: TTreeNode;begin  Dst := DirList.GetNodeAt(X,Y);  if(DraggedItem<>nil)AND(Dst<>nil) then  begin   if not TMyTreeNode(Dst).IsDir then Dst:=Dst.Parent;   ShowMessage('Copy '+DraggedItem.Text+' to '+Dst.Text);  end; DraggedItem:=nil;end; procedure TMainForm.DirListDragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean);var Dst: TTreeNode;begin Accept:=False;  Dst:=DirList.GetNodeAt(X,Y);  if(DraggedItem<>nil)AND(Dst<>nil)AND(DraggedItem<>Dst) then  begin   if not TMyTreeNode(Dst).IsDir then    Dst:=Dst.Parent;   DirList.ClearSelection;   DraggedItem.Selected:=True;   Dst.Selected:=True;   Accept:=True;  end;end; procedure TMainForm.DirListStartDrag(Sender: TObject;var DragObject: TDragObject);var p: TPoint; G: TImage; B: TBitmap;begin  DraggedItem:=DirList.Selected;  if DraggedItem<>nil then  begin   p:=TImage(Sender).ScreenToClient(mouse.cursorpos);   if Assigned(FDragObject) then FDragObject.Free;   FDragObject:=TMyDragObject.Create(Sender as TControl);   G:=TImage.Create(MainForm);   B:=TBitmap.Create;   FileImages.GetBitmap(DraggedItem.ImageIndex,B);   G.Canvas.Draw(0,0,B);   FDragObject.StartDrag(G.Picture.Graphic,p,Sender as TControl);   G.Free;   B.Free;   DragObject:=FDragObject;  end;end;(Incidentally, I've expanded the TTreeNode to add some extra information, like if it is a folder or a file, hence the TMyTreeNode). First the image doesn't appear with the cursor, and when I drop it, I get: Project raised exception class 'Debugger stopped with reason: EXC_BAD_ACCESS (code=1, address=0xb0)'. In file 'dragimagelist.inc' at line 268 (line 268 is about hiding the image). Any ideas? Of course, I'll probably solve this now I've posted it! Cheers, Gerald. ---------------------------------------------------------------------- geraldholdsworth · 2021-02-03 14:38 BTW, probably makes no odds - I'm using Lazarus 2.0.11 on macOS. I also found I think I needed to add this to the FormCreate: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i  ControlSty le:=ControlStyle+[csDisplayDragImage]; ImageContentsPanel.ControlStyle :=ImageContentsPanel.ControlStyle+[csDisplayDragImage]; DirList.Contro lStyle:=DirList.ControlStyle+[csDisplayDragImage];Still makes no difference. ---------------------------------------------------------------------- geraldholdsworth · 2021-02-03 17:47 I've been doing some investigating. I put that unit into a new, blank, project, added some images and tested it out. The cursor still did not change to the image, but it was dropped successfully with no errors. But I then found out that there is an example project doing this exact thing for non-image controls supplied with Lazarus (dragimagelist). So, I found it, loaded and compiled it. Still no image following the cursor. Oh, and the PaintTo method does not work - if I do Button4.PaintTo(bitmap.Canvas.Handle,0,0) this just produces a black bitmap. So, I transplanted this code for what I have in my main project. Of course, no image following the cursor and STILL an exception being thrown when it is dropped. I've found this code, which I have yet to try: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i   TErrForm = class(TForm)......  protected    ResetDragged: Boolean;    CursorPos: TPoint;    ObjectPos: TPoint;.... procedure TErrForm.ResetBtnMouseDown(Sender: TObject; Button: TMouseButton;  Shift: TShiftState; X: LongInt; Y: LongInt);begin  ResetDragged := True;  CursorPos.X := Mouse.CursorPos.X;  CursorPos.Y := Mouse.CursorPos.Y;  with ResetBtn do begin;    ObjectPos.X := Left;  ObjectPos.Y := Top;    end;end; procedure TErrForm.ResetBtnMouseMove(Sender: TObject; Shift: TShiftState;  X: LongInt; Y: LongInt);begin  if ResetDragged then begin    with ResetBtn do begin      Left := ObjectPos.X + (Mouse.CursorPos.X - CursorPos.X);      Top := ObjectPos.Y +  (Mouse.CursorPos.Y - CursorPos.Y);      ResetPos.X := (Left * NormalGeometry.ClientWidth div CurrImage.Width) + HorzScrollBar.Position;      ResetPos.Y := (Top * NormalGeometry.ClientHeight div CurrImage.Height) + VertScrollBar.Position;      end;    end;end; procedure TErrForm.ResetBtnMouseUp(Sender: TObject; Button: TMouseButton;  Shift: TShiftState; X: LongInt; Y: LongInt);begin  if ResetDragged then begin    ResetDragged := False;    Paint;    end;  if (abs(Mouse.CursorPos.X - CursorPos.X) < 10) and (abs(Mouse.CursorPos.Y - CursorPos.Y)< 10) then Close;end;But it looks promising. ---------------------------------------------------------------------- geraldholdsworth · 2021-02-03 19:33 I've found something...doesn't help, but it's an answer - here. Half way down it says: QuoteThe current LCL implementation has removed input processing from the drag object, so that the application can no more customize the UI. And the LCL implementation is far from being okay :-( Also the drag object is bypassed in the presentation of the visual feedback. OK, so that's why no image will appear. Why my application crashes though when I do try it is beyond me (while another with the exact same code works)...but it appears to be academic now. ---------------------------------------------------------------------- geraldholdsworth · 2021-02-09 13:02 I thought I'd post up my solution to this little problem. Using the idea (posted above) I wrote my own. By mistake, I'd left the DragMode on dmAutomatic, and it worked just fine. But I decided to turn this back to dmManual (because I'm sure the system was trying to get in on the action), and it all fell over. You see, as the cursor moved over the image I'd created and placed next to it, the TTreeView no longer got the OnMouseMove event firing (obviously), so I had to add an OnMouseMove event to the created image and pass this through to the control underneath, compensating for the X and Y values passed. So, enough blurb, here is my code, removed direct from my project (so you'll see lines that are not necessary for other projects): Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i {---------- --------------------------------------------------------------------}/ /User has initiated a drag operation on the directory list{----------- -------------------------------------------------------------------}pr ocedure TMainForm.DirListMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);begin //ADFS, double sided DFS, or AmigaDOS if((Image.FormatNumber shr 4=0) AND (Image.DoubleSided)) or (Image.FormatNumber shr 4=1) or (Image.FormatNumber shr 4=4) then begin  //Remember the node being dragged  DraggedItem:=DirList.GetNodeAt(X,Y);  //If it is valid  if DraggedItem<>nil then  begin   //Set the mouse down flag   MouseIsDown :=True;   //Remember the mouse position   CursorPos.X:=X;   CursorPos.Y:=Y;  end; end;end; {------------------------------------- -----------------------------------------}//Mouse Move event handler for the 'ghost' image{------------------------------------------------ ------------------------------}procedure TMainForm.DraggedItemMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);begin //Adjust the X and Y and pass through to the DirList event handler DirListMouseMove(Sender,Shift,X+ObjectDrag.Left, Y+ObjectDrag.Top);end; {---------------------------------------------- --------------------------------}//Mouse Up event handler for the 'ghost' image{-------------------------------------------------------- ----------------------}procedure TMainForm.DraggedItemMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);begin //Adjust the X and Y and pass through to the DirList event handler DirListMouseUp(Sender,Button,Shift,X+ObjectDrag.Left,Y+O bjectDrag.Top);end; {------------------------------------------------- -----------------------------}//User has dragged an item around the directory list{------------------------------------------------------- -----------------------}procedure TMainForm.DirListMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);var Xmovement, Ymovement, H         : Integer; R         : TRect; B         : TBitmap; Dst       : TTreeNode; copymode  : Boolean;begin copymode:=GetCopyMode(Shift); //Is the mouse button down? if MouseIsDown then begin  //Work out how far the mouse has moved  Xmovement:=Abs(X-CursorPos.X);  Ymovement:=Abs(Y-CursorPos.Y);  //If it has moved more than 10 pixels then user is dragging  if(Xmovement>10)or(Ymovement>10)then  begin   //We are dragging the control   IsDragging:=True;   //Are we over another node?   Dst:=DirList.GetNodeAt(X,Y);   if(DraggedItem<>nil)AND(Dst<>nil)AND(DraggedItem<>Dst) then   begin  //If it is not a directory, then get the parent    if not TMyTreeNode(Dst).IsDir then     Dst:=Dst.Parent;    //Only allow copying if it is a different parent and not within itself    if(DraggedItem<>Dst)AND(DraggedItem.Parent<>Dst)then    begin     //Highlight it, keeping the original highlighted     DirList.ClearSelection;     DraggedItem.Selected:=True;     Dst.Selected:=True;     //Expand the folder tree     Dst.Expand(False);    end;   end;   //See if we have created an image to move, if not then do so   if ObjectDrag=nil then   begin    //Get the bounding box of the dragged item    R:=DraggedItem.DisplayRect(False);    //Now create a bitmap copy of this    B:=TBitmap.Create;    B.Width:=R.Width;    B.Height:=R.Height;    //We need it transparent    B.Transparent:=True;    B.TransparentColor:=clFuchsia;    B.Canvas.Brush.Color:=clFuchsia;    B.Canvas.FillRect(Rect(0,0,R.Width,R.Height));    //Put the file icon in    FileImages.Draw(B.Canvas,1,0,DraggedItem.ImageIndex);    //Set up the font    B.Canvas.Font:=DirList.Font;    B.Canvas.Font.Quality:=fqNonAntialiased; //Otherwise we get a purple 'shadow'    B.Canvas.Font.Style:=[fsBold];    //Centralise the text  H:=B.Canvas.TextHeight(DraggedItem.Text);    B.Canvas.TextOut(Fileimages.Width+8,                    (Fileimages.Height-H)div 2,                     DraggedItem.Text);    //Now create the new image    ObjectDrag:=TImage.Create(DirList);    ObjectDrag.Parent:=DirList;    //Assign the mouse move event handler  ObjectDrag.OnMouseMove:=@DraggedItemMouseMove;    ObjectDrag.OnMouseUp:=@DraggedItemMouseUp;    //Set the size    ObjectDrag.Width:=B.Width;    ObjectDrag.Height:=B.Height;    //Put our bitmap in    ObjectDrag.Picture.Assign(B);    ObjectDrag.Transparent:=True;    //Make sure we can see it    ObjectDrag.Visible:=True;    //And free up the bitmap    B.Free;   end;   //Position our copied control above the mouse   ObjectDrag.Top:=Y-(ObjectDrag.Height div 2);   ObjectDrag.Left:=X-(Fileimages.Width+4);   //Show and position the 'copy' plus icon   imgCopy.Visible:=copymode;   imgCopy.Top:=Y+8;   imgCopy.Left:=X+8;   //Scroll the control, if near the edge - looks like can't be done easily  end; end;end; {---------------------------- --------------------------------------------------}//Determine whether to copy or move{------------------------------------------------------ ------------------------}function TMainForm.GetCopyMode(Shift: TShiftState): Boolean;begin //Default result Result:=True; //Look at the key modifiers {$IFDEF Darwin}   //For the Mac if ssMeta in Shift then Result:=False; //Move if ssAlt in Shift  then Result:=True;  //Copy {$ELSE}           //For Windows or Linux if ssShift in Shift then Result:=False; //Move if ssCtrl in Shift  then Result:=True;  //C opy {$ENDIF}end; {---------------------------------------------------- --------------------------}//User has dropped an item over the directory list{------------------------------------------------------- -----------------------}procedure TMainForm.DirListMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);var Xmovement, Ymovement, index      : Integer; Dst        : TTreeNode; copymode   : Boolean;begin copymode:=GetCopyMode(Shift); //Remove the copied control if ObjectDrag<>nil then ObjectDrag.Free; ObjectDrag:=nil; //And hide the 'copy' plus icon imgCopy.Visible:=False; //If we are in dragging mode, and the mouse is down if(MouseIsDown)and(IsDragging)then begin  //Work out how far the mouse has moved  Xmovement:=Abs(X-CursorPos.X);  Ymovement:=Abs(Y-CursorPos.Y);  //If it has moved more than 10 pixels then user is dragging  if(Xmovement>10)or(Ymovement>10)then  begin   //Are we over another node?   Dst:=DirList.GetNodeAt(X,Y);   if(DraggedItem<>nil)AND(Dst<>nil)AND(DraggedItem<>Dst) then   begin  //If it is not a directory, then get the parent    if not TMyTreeNode(Dst).IsDir then     Dst:=Dst.Parent;    //Only allow copying if it is a different parent and not within itself    if(DraggedItem<>Dst)AND(DraggedItem.Parent<>Dst)then    begin     //Currently only files - this needs to be written.     if TMyTreeNode(DraggedItem).IsDir then      ReportError('The functionality to copy/move directories has not yet been written.')     else      begin       //Do the copy/move       if copymode then      index:=Image.CopyFile(GetFilePath(DraggedItem),GetFilePath(Dst))     else        index:=Image.MoveFile(GetFilePath(DraggedItem),GetFilePath(Dst));     //Update the display       if index>=0 then AddFileToTree(Dst,DraggedItem.Text,index,False);       if index<0 then       begin        //For some reason the operation failed to write the data these are the error        //codes returned when writing a file, as it uses the same function)        if index=-1 then ReportError('Could not load "'+DraggedItem.Text+'"');        if index=-2 then ReportError('Could not add file - image full');        if index=-3 then ReportError('File already exists in directory');      if index=-4 then ReportError('Catalogue full');        if index=-5 then ReportError('Could not write file - error unknown');        if index=-6 then ReportError('Destination directory does not exist');      If index=-7 then ReportError('Could not write file - map full');      if index=-8 then ReportError('Could not write file - nothing to write');        if index=-9 then ReportError('Cannot move or copy to the same directory');       end;      end;    end;   end;  end;  //Clear any selections  if DraggedItem<>nil then  begin   DirList.ClearSelection;   //But make sure ours is still selected   DraggedItem.Selected:=True;   //Flush the memory of what is being dragged   DraggedItem:=nil;  end;               end;  //Reset the flags  MouseIsDown:=False;  IsDragging:=False;end;DirList is the TTreeView component. Also required is a small (16x16px) Timage of a suitable 'plus' icon (to indicate whether copying or moving), called imgCopy here.