unit UnitFrmEditHistory;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, UnitClipQueue, ComCtrls, ExtCtrls, {xpman,} Menus, Buttons,
  ImgList, UnitFrameClipDisplay;

type
  TfrmEditHistory = class(TForm)
    {$REGION 'default'}
    pcPages: TPageControl;
    tsPopup: TTabSheet;
    tsRemoved: TTabSheet;
    pmRemovedMore: TPopupMenu;
    RemovedCreatePlainText: TMenuItem;
    RemovedCreateClip: TMenuItem;
    pmRemovedCopyAs: TPopupMenu;
    RemovedCopytoClipboard1: TMenuItem;
    CopyasFormat1: TMenuItem;
    RemovedFindDialog1: TFindDialog;
    Panel1: TPanel;
    lbRemovedList: TListBox;
    btnRemovedFind: TButton;
    btnRemovedPermanent: TSpeedButton;
    btnRemovedCopy: TButton;
    btnRemovedCopyAs: TSpeedButton;
    btnRemovedEdit: TButton;
    btnRemovedFlushItems: TButton;
    Label1: TLabel;
    Panel2: TPanel;
    btnPermanent: TSpeedButton;
    btnDelete: TButton;
    btnDeleteMore: TSpeedButton;
    bCopyToClipboard: TButton;
    btnCopyAs: TSpeedButton;
    btnEdit: TButton;
    lbPopupQueue: TListBox;
    Preview: TLabel;
    Panel3: TPanel;
    btnTop: TSpeedButton;
    btnUp: TSpeedButton;
    btnDown: TSpeedButton;
    btnBottom: TSpeedButton;
    pmCopyAs: TPopupMenu;
    asText1: TMenuItem;
    asFormat: TMenuItem;
    pmDelete: TPopupMenu;
    DeleteClip1: TMenuItem;
    DestroyClip1: TMenuItem;
    pmMore: TPopupMenu;
    CreatePlainText: TMenuItem;
    CreateClip: TMenuItem;
    btnRemovedConfig: TSpeedButton;
    TabSheet1: TTabSheet;
    Label2: TLabel;
    Panel4: TPanel;
    lblhelp: TLabel;
    Label3: TLabel;
    btnPopupFlush: TButton;
    btnExport: TSpeedButton;
    pmExport: TPopupMenu;
    SaveallSelected1: TMenuItem;
    N1: TMenuItem;
    SaveallTXT1: TMenuItem;
    SaveallBMP1: TMenuItem;
    SaveallRichText1: TMenuItem;
    sdExport: TSaveDialog;
    odExport: TOpenDialog;
    btnExportRemoved: TSpeedButton;
    FrameClipDisplay1: TFrameClipDisplay;
    FrameClipDisplay2: TFrameClipDisplay;
    btnRemovedDelete: TButton;
    tsPermanent: TTabSheet;
    cpgGroups: TCategoryPanelGroup;
    pmPermMenu: TPopupMenu;
    MIMoveTo1: TMenuItem;
    MIDelete1: TMenuItem;
    FramePermClip: TFrameClipDisplay;
    cpNewGroup: TCategoryPanel;
    Label4: TLabel;
    txtPermGroup: TEdit;
    btnPermCreate: TButton;
    pnlHotkey: TPanel;
    btnSetHotkey: TSpeedButton;
    btnClearHotkey: TSpeedButton;
    pnl1: TPanel;
    Label5: TLabel;
    lblHotkey: TLabel;
    MIEdit1: TMenuItem;
    N2: TMenuItem;
    procedure FormShow(Sender: TObject);

    procedure btnRemovedEditClick(Sender: TObject);
    procedure btnRemovedCopyClick(Sender: TObject);
    procedure btnRemovedCopyAsClick(Sender: TObject);
    procedure btnRemovedPermanentClick(Sender: TObject);
    procedure btnRemovedFindClick(Sender: TObject);
    procedure btnRemovedFlushItemsClick(Sender: TObject);
    procedure btnRemovedConfigClick(Sender: TObject);
    procedure lbRemovedListDrawItem(Control: TWinControl; Index: Integer; Rect: TRect;
      State: TOwnerDrawState);
    procedure lbRemovedListClick(Sender: TObject);
    procedure lbRemovedListMeasureItem(Control: TWinControl; Index: Integer;
      var Height: Integer);
    procedure RemovedFindDialog1Show(Sender: TObject);
    procedure RemovedFindDialog1Find(Sender: TObject);
    procedure RemovedCopytoClipboard1Click(Sender: TObject);
    procedure CopyasFormat1Click(Sender: TObject);
    procedure RemovedCreatePlainTextClick(Sender: TObject);
    procedure RemovedCreateClipClick(Sender: TObject);
    procedure btnEditClick(Sender: TObject);
    procedure lbPopupQueueClick(Sender: TObject);
    procedure bCopyToClipboardClick(Sender: TObject);
    procedure btnCopyAsClick(Sender: TObject);
    procedure btnDeleteClick(Sender: TObject);
    procedure btnDeleteMoreClick(Sender: TObject);
    procedure btnPermanentClick(Sender: TObject);
    procedure btnTopClick(Sender: TObject);
    procedure btnUpClick(Sender: TObject);
    procedure btnDownClick(Sender: TObject);
    procedure btnBottomClick(Sender: TObject);
    procedure lbPopupQueueDrawItem(Control: TWinControl; Index: Integer; Rect: TRect;
      State: TOwnerDrawState);
    procedure lbPopupQueueKeyDown(Sender: TObject; var Key: Word;
      Shift: TShiftState);
    procedure lbPopupQueueMeasureItem(Control: TWinControl; Index: Integer;
      var Height: Integer);
    procedure asText1Click(Sender: TObject);
    procedure asFormatClick(Sender: TObject);
    procedure DeleteClip1Click(Sender: TObject);
    procedure DestroyClip1Click(Sender: TObject);
    procedure CreatePlainTextClick(Sender: TObject);
    procedure CreateClipClick(Sender: TObject);
    procedure FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
    procedure pcPagesChange(Sender: TObject);
    procedure btnPopupFlushClick(Sender: TObject);
    procedure btnExportClick(Sender: TObject);
    procedure odExportCanClose(Sender: TObject; var CanClose: Boolean);
    procedure btnExportRemovedClick(Sender: TObject);
    procedure FormCreate(Sender: TObject);
    procedure cpgGroupsMouseWheel(Sender: TObject; Shift: TShiftState;
      WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean);
    procedure pmPermMenuPopup(Sender: TObject);
    procedure txtPermGroupChange(Sender: TObject);
    procedure btnPermCreateClick(Sender: TObject);
    procedure btnSetHotkeyClick(Sender: TObject);
    procedure btnClearHotkeyClick(Sender: TObject);
    procedure MIEdit1Click(Sender: TObject);
    procedure MINewClip1Click(Sender: TObject);
    {$ENDREGION}
  private
    { Private declarations }
        fskipconfirmationonce : boolean;
    	maxpopupheader, maxremovedheader : integer;
        ci : TClipItem;
        slGroups : TStringList;
        lastGroup, lastHotkey : string;
        lastClip : integer;
        procedure FreeRemoved(ci : TClipItem);
        procedure RemovedResetButtons;
        function RemovedClickedClip : TClipItem;
        procedure PopupResetButtons;
        function IsSafeToMove : boolean;
        procedure SaveTextItemsOrder;

        procedure resetView;
        procedure btnPermEdit(Sender : TObject);
        procedure btnPermNew(Sender : TObject);
        procedure ShowPermGroup(group : string; clipIndex : integer=-1);
        procedure NewRemovedClipEvent(Sender : TObject);
        procedure loadPermanent;
        procedure groupExpand(Sender : TObject);
        procedure permanentMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
        procedure permMenuItemClick(Sender : TObject);
        procedure btnPermDelete(Sender : TObject);
  protected
        procedure CreateParams(var Params: TCreateParams); override;
  public
    { Public declarations }
        procedure ShowRemoved;
        procedure ShowPopup;
        procedure ShowPopupModal;
        procedure SkipConfirmationOnce;
  end;

var
  frmEditHistory: TfrmEditHistory;

implementation

{$R *.dfm}

uses StrUtils, Clipbrd, UnitFrmHotKey, UnitFrmConfig,
  UnitFrmClipboardManager, UnitPaste, Math, UnitMisc, UnitFrmEditItem,
  UnitFrmEditTextExternal, UnitToken, UnitFrmPermanentNew, INIFiles, UnitKeyboardQuery, UnitListBoxMover,
  {$WARN UNIT_PLATFORM OFF} VCL.FileCtrl, {$WARN UNIT_PLATFORM ON}
  UnitSpecialPaths, UnitFrmMainPopup, UnitPopupGenerate, UnitFrmDebug,
  UnitClipDatabase, UnitFrmPermanentEdit;

{ TfrmNewEditHistory }
procedure TfrmEditHistory.SkipConfirmationOnce;
begin
    self.fskipconfirmationonce := true;
end;


procedure TfrmEditHistory.CreateParams(var Params: TCreateParams);
begin
    inherited CreateParams(Params);
    // allow context taskbar context menu and
    // show me on the taskbar - independant of main form
    with Params do begin
        ExStyle := ExStyle or WS_EX_APPWINDOW;
        WndParent := GetDesktopwindow;
    end;
end;

procedure TfrmEditHistory.FormClose(Sender: TObject; var Action: TCloseAction);
begin
    RemovedQueue.ClearClipCache;
    lbPopupQueue.Clear;
    RemovedFindDialog1.CloseDialog;
end;
procedure TfrmEditHistory.FormCreate(Sender: TObject);
begin
    FrameClipDisplay1.color := clWhite;
    FrameClipDisplay1.SetScrollbars(ssVertical);
    FrameClipDisplay1.Enabled := true;

    FrameClipDisplay2.Color := clWhite;
    FrameClipDisplay2.SetScrollbars(ssVertical);
    FrameClipDisplay2.Enabled := true;

    RemovedQueue.addNewClipListener(NewRemovedClipEvent);

    slGroups := TStringList.Create;
end;
procedure TfrmEditHistory.NewRemovedClipEvent(Sender : TObject);
begin
    if (self.Showing) then begin
        self.FormShow(nil);
        lbRemovedList.Invalidate;
    end;
end;
procedure TfrmEditHistory.FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
    if (KEY = VK_ESCAPE) then begin
        self.ModalResult := mrok;
        self.close;
    end;
end;
procedure TfrmEditHistory.FormShow(Sender: TObject);
var i : longint;
    procedure AddItems(clips : TClipQueue; listbox : TListBox);
    var i : integer;
        s : string;
        ci : TClipItem;
    begin
        for i := 0 to (clips.GetQueueCount - 1) do begin
            ci := clips.GetClipItem(i);
            s := ci.GetAsPlaintext;
            if ci.GetFormatType = FT_PICTURE then begin
            	s := ci.GetFormatName; 
            end;

            listbox.Items.AddObject(LeftStr(s,300), TObject(ci) );
        end;
    end;

begin

    if pcPages.ActivePageIndex = tsRemoved.PageIndex then begin
        FrameClipDisplay1.ShowClip('');

        RemovedQueue.PreloadCache;

        lbRemovedList.Items.Clear;
        lbRemovedList.Items.BeginUpdate;

        if (TClipDatabase.exists) then begin
            TClipDatabase.StartBatch;
        end;

        for i := (RemovedQueue.GetQueueCount - 1) downto 0 do begin
            lbRemovedList.Items.Add('TEST TEXT HERE');
        end;
        lbRemovedList.Items.EndUpdate;

        if (TClipDatabase.exists) then begin
            TClipDatabase.EndBatch;
        end;


        self.RemovedResetButtons;
    end;
    //
    // popup clips
    //



    if pcPages.ActivePageIndex = tsPopup.PageIndex then begin
        FrameClipDisplay2.ShowClip('');
        bCopyToClipboard.Enabled := false;
        btnEdit.enabled := false;

        PopupResetButtons;
        lbPopupQueue.Items.Clear;
        lbPopupQueue.Items.BeginUpdate;
        AddItems(ClipQueue, lbPopupQueue);
        lbPopupQueue.Items.EndUpdate;
    end;

    if pcPages.ActivePageIndex = tsPermanent.PageIndex then begin
        self.loadPermanent;
    end;

end;
procedure TfrmEditHistory.pcPagesChange(Sender: TObject);
begin
    maxpopupheader := 0;
    maxremovedheader := 0;

    self.FormShow(sender);
end;


procedure TfrmEditHistory.SaveTextItemsOrder;
var i, index : longint;
    ci : TClipItem;
begin
    for i := (lbPopupQueue.Items.count - 1) downto 0 do begin
        ci := TClipItem(lbPopupQueue.items.Objects[i]);
        index := ClipQueue.IndexOf(ci);
        if (i <> index) then begin
            ClipQueue.Move(index, i);
        end;
    end;
end;

procedure TfrmEditHistory.ShowPopup;
begin
	pcPages.ActivePageIndex := tsPopup.PageIndex;
    self.show;

end;
procedure TfrmEditHistory.ShowPopupModal;
begin
    pcPages.ActivePageIndex := tsPopup.PageIndex;
    self.ShowModal;
end;
procedure TfrmEditHistory.ShowRemoved;
begin
	pcPages.ActivePageIndex := tsRemoved.PageIndex;
    self.Show;
end;


//
// Permanent Clips/Macros
//

type TListUsed = class(TListBox);
type
  TCategoryPanelGroupHelper = class helper for TCustomCategoryPanelGroup
  public
    procedure RemovePanel_(Panel: TCustomCategoryPanel);
  end;
procedure TCategoryPanelGroupHelper.RemovePanel_(Panel: TCustomCategoryPanel);
begin
  Self.RemovePanel(Panel);
end;
type TCategoryPanelHelper = class helper for TControl
    public
        procedure setHeight_(height : integer);
end;
procedure TCategoryPanelHelper.setHeight_(height : integer);
begin
    self.fheight := height;
end;
const NEW_GROUP_LABEL = '[New Group]';
procedure TfrmEditHistory.loadPermanent;
var
    i : integer;
    s, key : string;
    mi : TMenuItem;
    procedure showGroup(group : string);
    var
        sl, keys : TStringList;
        s : string;
        pnl : TCategoryPanel;
        lb : TListUsed;
        li : TListItem;
        pnl2 : TPanel;
        btn, btn2 : TButton;
    begin
        pnl := TCategoryPanel.Create(cpgGroups);
        pnl.PanelGroup := cpgGroups;
        pnl.Caption := group;
        pnl.Hint := group;
        pnl.OnExpand := self.groupExpand;
        pnl.Padding.Top := 5;


        lb := TListUsed.Create(pnl);
        lb.Parent := pnl;
        lb.OnMouseUp := self.permanentMouseUp;
        lb.ParentFont := false;
        lb.Font := cpgGroups.Font;
        lb.font.size := 9;
        lb.BorderStyle := bsNone;

        sl := TStringList.Create;
        TClipDatabase.LoadPermanentNames(sl, group);
        keys := TStringList.Create;
        TClipDatabase.LoadPermanentHotkeys(keys, group);
        for s in sl do begin
            key := '';
            if keys.Count > lb.Items.count then
                key := keys[lb.Items.Count];
            if (length(key) > 6) then begin
                delete(key,1,6);
                lb.Items.Add(s + '  ['+key+']');
            end else begin
                lb.Items.Add(s);
            end;
        end;
        i := trunc(lb.Canvas.TextHeight('ASDF') * 1.15);
        lb.height := i * (lb.Items.Count) + 8;


        pnl2 := TPanel.Create(pnl);
        pnl2.Parent := pnl;
        pnl2.BevelOuter := bvNone;
        btn := TButton.Create(pnl2);
        btn.Parent := pnl2;
        btn.Caption := 'New';
        btn.Align := alRight;
        btn.OnClick := self.btnPermNew;

        pnl2.Height := 37;
        pnl2.Padding.Right := 20;
        pnl2.Padding.Top := 10;
        pnl2.Padding.Bottom := 3;

        pnl2.Align := alTop;
        lb.Align := alTop;

        pnl.setHeight_(lb.height + (i*3) + pnl2.height );
        pnl.Collapsed := true;
    end;

var
    pnl : TCategoryPanel;
begin
    MIDelete1.OnClick := btnPermDelete;
    cpNewGroup.OnExpand := self.groupExpand;
    cpNewGroup.Collapsed := true;
    for i:= cpgGroups.Panels.Count-1 downto 0 do begin
        pnl := cpgGroups.Panels[i];
        if (pnl.Caption <> NEW_GROUP_LABEL) then
            cpgGroups.RemovePanel_(pnl);
    end;

    slGroups.Clear;


    TClipDatabase.StartBatch;
    TClipDatabase.LoadPermanentGroups(slGroups);

    for s in slGroups do begin
        showGroup(s);
    end;



    TClipDatabase.EndBatch;
end;
procedure TFrmEditHistory.ShowPermGroup(group : string; clipIndex : integer=-1);
var
    i : integer;
    cp : TCategoryPanel;
    lb : TListUsed;
begin
    resetView;
    for i := 0 to cpgGroups.Panels.Count-1 do begin
        cp := cpgGroups.Panels[i];
        if (cp.hint = group) then begin
            cp.Collapsed := false;

            if (clipIndex <> -1) then begin
                lb := TListUsed(cp.Controls[0]);
                lb.ItemIndex := clipIndex;
            end;
            EXIT;
        end;
    end;
end;
procedure TfrmEditHistory.resetView;
begin
    lblHotkey.Caption := '';
    lastClip := -1;
    FramePermClip.ShowClip('');
    FramePermClip.PicStretched := true;
end;

procedure TfrmEditHistory.btnPermEdit(Sender : TObject);
var s : string;
begin
    s := lastGroup;
    FrmPermanentEdit.Top := self.Top;
    FrmPermanentEdit.Left := self.Left;
    if FrmPermanentEdit.ShowForm(lastGroup, lastClip) = mrOK then begin
        self.loadPermanent;
        self.ShowPermGroup(s);
    end;
end;
procedure TfrmEditHistory.btnPermNew(Sender : TObject);
var s : string;
begin
    s := lastGroup;
    FrmPermanentEdit.Top := self.Top;
    FrmPermanentEdit.Left := self.Left;
    if FrmPermanentEdit.ShowFormNew(lastGroup, -1) = mrOK then begin
        self.loadPermanent;
        self.ShowPermGroup(s);
    end;
end;
procedure TfrmEditHistory.groupExpand(Sender : TObject);
var i,j : integer;
    cp : TCategoryPanel;
    ci : TClipItem;
    lb : TListUsed;
begin
    resetView;
    for i := 0 to cpgGroups.Panels.Count-1 do begin
        cp := cpgGroups.Panels[i];
        if (sender <> cp) then begin
            if (not cp.Collapsed) then begin
                cp.Collapse;
            end;
        end else begin
            if (cp.Caption = NEW_GROUP_LABEL) then begin
                txtPermGroup.Text := '';
                txtPermGroup.SetFocus;
                CONTINUE;
            end;

            lb := TListUsed(TWinControl(cp.Controls[0]).Controls[0]);
            lb.ItemIndex := -1;
            lastGroup := cp.hint;
            lastClip := -1;
            CONTINUE;

            ci := TClipItem.Create;
            TClipDatabase.LoadPermanent(ci, lastClip, lastGroup);
            FramePermClip.ShowClip(ci);
            myfree(ci);
        end;
    end;
end;
procedure TfrmEditHistory.permanentMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
    lb : TListUsed;
    cp : TCategoryPanel;
    cpg : TCategoryPanelGroup;
    i : integer;
    pt : TPoint;
    ci : TClipITem;
    li : TListItem;
    procedure setButtons;
    begin

    end;
begin
    if (sender is TListUsed) then begin

        lb := TListUsed(Sender);
        resetView;
        FramePermClip.PicStretched := true;
        case Button of
        mbLeft: begin
            lastClip := lb.ItemIndex;
            setButtons;
            if lastClip = -1 then EXIT;

            ci := TClipItem.Create;
            TClipDatabase.LoadPermanent(ci, lastClip, lastGroup);
            lastHotkey := TClipDatabase.LoadPermanentHotkey(lastClip, lastGroup);
            lblHotkey.Caption := unitmisc.hotkeyName(lastHotkey);

            FramePermClip.ShowClip(ci);
            myfree(ci);
        end;
        mbRight: begin
            pt := lb.ScreenToClient(mouse.CursorPos);
            lastClip := lb.ItemAtPos(pt, true);
            lb.ItemIndex := lastClip;
            setButtons;
            if lastClip=-1 then EXIT;

            ci := TClipItem.Create;
            TClipDatabase.LoadPermanent(ci, lastClip, lastGroup);
            lastHotkey := TClipDatabase.LoadPermanentHotkey(lastClip, lastGroup);
            lblHotkey.Caption := unitmisc.hotkeyName(lastHotkey);

            FramePermClip.ShowClip(ci);
            myfree(ci);
            pmPermMenu.Popup(mouse.CursorPos.X + 10, mouse.CursorPos.y + 5);
        end;
        end;
    end;
end;
procedure TfrmEditHistory.txtPermGroupChange(Sender: TObject);
begin
    btnPermCreate.Enabled := txtPermGroup.Text <> '';
end;
procedure TfrmEditHistory.pmPermMenuPopup(Sender: TObject);
var
    s : string;
    mi : TMenuItem;
begin
    MIMoveTo1.Clear;
    for s in slGroups do begin
        if (s <> lastGroup) then begin
            mi := TMenuItem.Create(MIMoveTo1);
            mi.Caption := s;
            mi.hint := s;
            mi.OnClick := self.permMenuItemClick;
            MIMoveTo1.Add(mi);
        end;
    end;
end;
procedure TfrmEditHistory.btnPermCreateClick(Sender: TObject);
var
    group : string;
begin
    group := txtPermGroup.text;
    if slGroups.IndexOf(group) = -1 then begin
        TClipDatabase.SavePermanentGroup(group, 0);
        self.loadPermanent;
        self.ShowPermGroup(group);
    end;
end;
procedure TFrmEditHistory.permMenuItemClick(Sender : TObject);
var
    group : string;
begin
    group := TMenuItem(Sender).hint;

    TClipDatabase.MovePermanentClip(lastClip, lastGroup, group);
    self.loadPermanent;
    self.ShowPermGroup(group);
end;
procedure TfrmEditHistory.btnSetHotkeyClick(Sender: TObject);
var
    hkd : THotkeyData;
    s : string;
begin
    if FrmHotkey.GetHotkey(hkd) then begin
        s := FrmHotkey.ToHKString(hkd);
        TClipDatabase.SavePermanentHotkey(s,lastClip,lastGroup );
        lblHotkey.Caption := unitmisc.hotkeyName(s);
        FrmPermanent.RefreshHotkeys;
    end;
end;
procedure TfrmEditHistory.btnClearHotkeyClick(Sender: TObject);
begin
    TClipDatabase.SavePermanentHotkey('',lastClip,lastGroup);
    lblHotkey.Caption := '';
    FrmPermanent.RefreshHotkeys;
end;
procedure TFrmEditHistory.btnPermDelete(Sender : TObject);
var s : string;
begin
    if MessageDlg('Delete the selected item ?', mtConfirmation,[mbYes, mbNo],0,mbNo) <> mrYes  then
        EXIT;
    s := lastGroup;
    TClipDatabase.DeletePermanentClip(lastClip, lastGroup);
    self.loadPermanent;
    self.ShowPermGroup(s);
end;
procedure TfrmEditHistory.MIEdit1Click(Sender: TObject);
begin
    btnPermEdit(Sender);
end;
procedure TfrmEditHistory.MINewClip1Click(Sender: TObject);
begin
    btnPermNew(Sender);
end;


//
//  Removed Clips Functions
//

procedure TfrmEditHistory.btnRemovedCopyClick(Sender: TObject);
var i : integer;
	ci : TClipItem;
begin
    Paste.SetClipboardOnlyOnce;
    i := (lbRemovedList.Count - 1) - lbRemovedList.ItemIndex;

    // to be more inuitive, let any copied removed item back onto the popup

    //if frmconfig.cbMoveFirst.checked then begin
        frmClipboardManager.DisablePasteProtectionOnce;
    //end;

    ci := nil;
    ci := RemovedQueue.GetItemClip(i);
    if (ci <> nil) and (ci.GetFormatType = ft_picture) then begin
    	Paste.SendText('', ci);
    end else begin
    	Paste.SendText(RemovedQueue.GetItemText(i), nil);
    end;
    if ci <> nil then myfree(ci);
    

    self.hide;
end;
procedure TfrmEditHistory.btnRemovedFlushItemsClick(Sender: TObject);
begin
    if (fskipconfirmationonce) or (MessageDlg('Delete all Removed Clips?', mtConfirmation, [mbyes, mbno],0) = mrYes) then begin
        fskipconfirmationonce := false;
        RemovedQueue.ClearQueue;
        //TempClipQueue.ClearQueue;

        lbRemovedList.Items.Clear;
        FrameClipDisplay1.ShowClip('');

        self.FormShow(self);
    end;
end;

procedure TfrmEditHistory.asFormatClick(Sender: TObject);
var ci : TClipItem;
begin
    ci := TClipItem(lbPopupQueue.items.Objects[lbPopupQueue.ItemIndex]);
    FrmDebug.AppendLog('Copy As ' + ci.GetAsPlaintext + ' ' + ci.GetFormatName );
    Paste.SetClipboardOnlyOnce;
    Paste.SendText('', ci);
end;
procedure TfrmEditHistory.asText1Click(Sender: TObject);
begin
 	bCopyToClipboard.click;
end;
procedure TfrmEditHistory.bCopyToClipboardClick(Sender: TObject);
var i : longint;
    s : string;
    ci : TClipItem;
begin
    ci := nil;
    for i := 0 to (lbPopupQueue.Items.count - 1) do begin
        if lbPopupQueue.Selected[i] then begin
            ci := TClipItem(lbPopupQueue.items.Objects[i]);
            s := s + ci.GetAsPlaintext;
        end;
    end;

    if (lbPopupQueue.SelCount = 1) and (ci.GetFormat = CF_DIB) then begin
        Paste.SetClipboardOnlyOnce;
        Paste.SendText('', ci);
    end else if (s <> '') then begin
        Paste.SetClipboardOnlyOnce;
        Paste.SendText(s);
    end;
end;
procedure TfrmEditHistory.btnBottomClick(Sender: TObject);
begin
    if (IsSafeToMove) then begin
        UnitListBoxMover.MoveSelectedBottom(lbPopupQueue);
        self.SaveTextItemsOrder;  lbPopupQueue.Repaint;
    end;
end;


procedure TfrmEditHistory.btnCopyAsClick(Sender: TObject);
var p : TPoint;
begin
    p := btnCOpyas.ClientToScreen(point(btnCopyAs.Width,0) );
    pmCopyas.Popup(p.X, p.y);
end;
procedure TfrmEditHistory.btnDeleteClick(Sender: TObject);
var i, j : integer;
    ci : TClipItem;
begin
    if (MessageDlg('Delete the selected clips?', mtConfirmation, [mbyes, mbno],0) = mrYes) then begin
        if (TButton(sender).Name = 'btnRemovedDelete') then begin
            for i := (lbRemovedList.Items.count - 1) downto 0 do begin
                if (lbRemovedList.Selected[i]) then begin
                    TClipDatabase.DeleteRemoved(i);
                end;
            end;
            RemovedQueue.RefreshSize;
        end else begin
            for i := (lbPopupqueue.Items.count - 1) downto 0 do begin
                if (lbPopupqueue.Selected[i]) then begin
                    ci := TClipItem(lbPopupQueue.Items.Objects[i]);
                    j := ClipQueue.IndexOf(ci);
                    ClipQueue.DeleteItem(j);
                end;
            end;
        end;
        self.FormShow(self);
    end;
end;
procedure TfrmEditHistory.btnDeleteMoreClick(Sender: TObject);
var p : TPoint;
begin
    DeleteClip1.Enabled := false;
    if (TSpeedButton(sender).Name = 'btnDeleteMoreClick') then begin
        DeleteClip1.Enabled := true;
    end;
    p := btnDeleteMore.ClientToScreen(point(btnDeleteMore.Width,0) );
    pmDelete.Popup(p.X, p.y);

    PopupResetButtons;
end;
procedure TfrmEditHistory.btnDownClick(Sender: TObject);
begin
if (IsSafeToMove) then begin
            UnitListBoxMover.MoveSelectedDown(lbPopupQueue);
            self.SaveTextItemsOrder; lbPopupQueue.Repaint;
        end;
end;
procedure TfrmEditHistory.btnEditClick(Sender: TObject);
var
    ci : TClipItem;
begin
    ci := ClipQueue.GetClipItem(lbPopupQueue.itemindex);

//    frmEditTextExternal.EditClip(ci);
//    self.Show;

    if frmConfig.cbEditClipWindow.checked then begin
        FrmEditItem.SetText(ci.GetAsPlaintext, nil);
        FrmMainPopup.ShowPreviewEditForm;
    end else begin
        frmEditTextExternal.EditClip(ci);
        self.Show;
    end;

    Application.ProcessMessages;
    self.FormShow(self);
end;
procedure TfrmEditHistory.btnPermanentClick(Sender: TObject);
var p : TPoint;
var ci : TClipItem;
begin
    ci := ClipQueue.GetClipItem(lbPopupQueue.itemindex);

    CreateClip.Caption := 'Create ' + ci.GetFormatName(false) + ' Clip';

    p := btnPermanent.ClientToScreen(point(btnPermanent.Width,0) );
    pmMore.Popup(p.X, p.y);

    PopupResetButtons;
end;

procedure TfrmEditHistory.btnPopupFlushClick(Sender: TObject);
begin
    if (fskipconfirmationonce) or (MessageDlg('Delete all Popup Clips?', mtConfirmation, [mbyes, mbno],0) = mrYes) then begin
        fskipconfirmationonce := false;
        ClipQueue.ClearQueue;
        lbPopupQueue.Items.Clear;
        FrameClipDisplay2.ShowClip('');

        self.FormShow(self);
    end;
end;
procedure TfrmEditHistory.btnRemovedConfigClick(Sender: TObject);
begin
    frmconfig.pcPanels.ActivePageIndex := frmconfig.tsHistory.PageIndex;
    frmconfig.Show;
end;
procedure TfrmEditHistory.btnRemovedCopyAsClick(Sender: TObject);
var p : TPoint;
begin
    p := btnRemovedCopyAs.ClientToScreen(point(btnRemovedCopyAs.Width,0) );
    pmRemovedCopyAs.Popup(p.X, p.y);
end;
procedure TfrmEditHistory.btnRemovedEditClick(Sender: TObject);
var
    i : integer;
begin
    MyFree(ci);

//    i := (lbRemovedList.Count - 1) - lbRemovedList.ItemIndex;
    i := lbRemovedList.ItemIndex;
    ci := RemovedQueue.GetItemClip(i);


//    frmEditTextExternal.EditClip(ci);
//    self.Show;

    if frmConfig.cbEditClipWindow.checked then begin
        FrmEditItem.SetText(ci.GetAsPlaintext, nil);
        FrmMainPopup.ShowPreviewEditForm;
    end else begin
        frmEditTextExternal.EditClip(ci);
        self.Show;
    end;


    Application.ProcessMessages;
    self.FormShow(self);

end;
procedure TfrmEditHistory.btnRemovedFindClick(Sender: TObject);
begin
    RemovedFindDialog1.Execute;
end;
procedure TfrmEditHistory.btnRemovedPermanentClick(Sender: TObject);
var p : TPoint;
begin
    //self.FreeRemoved(ci);
    MyFree(ci);
    ci := self.RemovedClickedClip;
    if (ci <> nil) then begin
        RemovedCreateClip.Caption := 'Create ' + ci.GetFormatName(false) + ' Clip';

        p := btnRemovedPermanent.ClientToScreen(point(btnRemovedPermanent.Width,0) );
        pmRemovedMore.Popup(p.X, p.y);

        RemovedResetButtons;
    end;
end;


procedure TfrmEditHistory.btnTopClick(Sender: TObject);
begin
    if (IsSafeToMove) then begin
        UnitListBoxMover.MoveSelectedTop(lbPopupQueue);
        self.SaveTextItemsOrder;  lbPopupQueue.Repaint;
    end;
end;
procedure TfrmEditHistory.btnUpClick(Sender: TObject);
begin
        if (IsSafeToMove) then begin
            UnitListBoxMover.MoveSelectedUp(lbPopupQueue);
            self.SaveTextItemsOrder;
            lbPopupQueue.Repaint;
        end;
end;

function TfrmEditHistory.RemovedClickedClip: TClipItem;
var i : integer;
begin
    result := nil;
    if lbRemovedList.ItemIndex = -1 then EXIT;

//    i := (lbRemovedList.Count - 1) - lbRemovedList.ItemIndex;
    i := lbRemovedList.ItemIndex;
    result := RemovedQueue.GetItemClip(i);
end;



procedure TfrmEditHistory.RemovedCopytoClipboard1Click(Sender: TObject);
begin
    btnRemovedCopy.click;
end;
procedure TfrmEditHistory.RemovedCreateClipClick(Sender: TObject);
begin
    //self.FreeRemoved(ci);
    MyFree(ci);
    ci := self.RemovedClickedClip;
    FrmPermanent.ShowWithNewComplexItem(ci);
end;
procedure TfrmEditHistory.RemovedCreatePlainTextClick(Sender: TObject);
begin
    //self.FreeRemoved(ci);
    MyFree(ci);
    ci := self.RemovedClickedClip;
    FrmPermanent.ShowWithNewItem(ci.GetAsPlaintext);
end;
procedure TfrmEditHistory.RemovedFindDialog1Find(Sender: TObject);
var i,j, a,b : integer;
    s : string;
    pc : PChar;
    op : TStringSearchOptions;
begin
    if lbRemovedList.Count = 0 then EXIT;

    // select the first item in the list by default
    // translate the index because RemovedCach is stored oldest first
    if lbRemovedList.itemindex = -1 then begin
        lbRemovedList.ItemIndex := 0;
        lbRemovedListClick(lbRemovedList);
    end;
    i := lbRemovedList.ItemIndex;
    i := (lbRemovedList.Count-1) - i;

    op := [soDown];
    if frMatchCase in RemovedFindDialog1.options then op := op + [soMatchCase];
    if frwholeword in RemovedFindDialog1.options then op := op + [soWholeWord];

    // in an oldest-first list, down and up searches are reversed
    if (frdown in RemovedFindDialog1.Options) then begin
        a := 0;
        b := i;
        for j := b-1 downto a do begin
            s := RemovedQueue.GetItemText(j);
            pc := SearchBuf(
                pchar(s), length(s),
                0,0, RemovedFindDialog1.FindText,
                op
            );
            if pc <> nil then begin
                lbRemovedList.ClearSelection;
                lbRemovedList.Selected[(lbRemovedList.count-1)-j] := true;
                lbRemovedList.ItemIndex := (lbRemovedList.count-1)-j;
                lbRemovedList.TopIndex := (lbRemovedList.count-1)-j;
                lbRemovedListClick(lbRemovedList);
                EXIT;
            end;
        end;
    end else begin
        a := i;
        b := lbRemovedList.Count - 1;

        for j := a+1 to b do begin
            s := RemovedQueue.GetItemText(j);
            pc := SearchBuf(
                pchar(s), length(s),
                0,0, RemovedFindDialog1.FindText,
                op
            );
            if pc <>nil then begin
                lbRemovedList.ClearSelection;
                lbRemovedList.Selected[(lbRemovedList.count-1)-j] := true;
                lbRemovedList.ItemIndex := (lbRemovedList.count-1)-j;
                lbRemovedList.TopIndex := (lbRemovedList.count-1)-j;
                lbRemovedListClick(lbRemovedList);
                EXIT;
            end;
        end;
    end;
end;
procedure TfrmEditHistory.RemovedFindDialog1Show(Sender: TObject);
begin
    SetForegroundWindow(RemovedFindDialog1.Handle)
end;



procedure TfrmEditHistory.FreeRemoved(ci: TClipItem);
begin
    //
    // Removed items are generated on the fly and resources must
    // be freed manually.
    //
    if (ci <> nil) then begin
        MyFree(ci);
    end;
end;

function TfrmEditHistory.IsSafeToMove: boolean;
var ci : TClipItem;
begin
    if (lbPopupQueue.Count = 0) then begin
        Result := true;
        EXIT;
    end;

    ci := TClipItem(self.lbPopupQueue.Items.Objects[0]);
    result := (ClipQueue.IndexOf(ci) = 0);
    if (not result) then begin
        ShowMessage('The clipboard contents have changed. Unable to move the items.'
            + #13#10 + 'Refreshing display');
        self.FormShow(self);
    end;
end;

procedure TfrmEditHistory.lbPopupQueueClick(Sender: TObject);
var ci : TClipItem;
begin
    PopupResetButtons;
    ci := ClipQueue.GetClipItem(lbPopupQueue.itemindex);
    if (ci <> nil) then begin
        asFormat.Caption := 'Copy as ' + leftstr(ci.GetFormatName,10);
        FrameClipDisplay2.ShowClip(ci);
    end;
end;
procedure TfrmEditHistory.lbPopupQueueDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState);
var ci : TClipItem;
    th, h, headerwd : integer;
    c, bc : TColor;
    header : string;
    s : string;
    bmp : TBitmap;
const HEADER_WIDTH = 80;
begin
    // height of rectangle & height of text on the listbox
    h := (rect.Bottom - rect.top) + 1;
    th := lbPopupQueue.Canvas.TextHeight('ALKJDFIOJ');
    headerwd  := lbRemovedList.Canvas.TextWidth(' ');

    bc := lbPopupQueue.Canvas.Brush.Color;
    lbPopupQueue.Canvas.Brush.Color := clWhite;
    lbPopupQueue.Canvas.FillRect(rect);
    lbPopupQueue.Canvas.Brush.Color := bc;

    //
    // draw the icon leaving enough pixels above and below
    // for the selection outline
    //


    ci := ClipQueue.GetClipItem(index);
    if (ci <> nil) then begin
    	//s := ci.GetAsText;
        s := lbPopupqueue.Items.Strings[index];
        DrawIconEX(
            lbPopupQueue.Canvas.Handle, rect.Left+2, rect.Top+1,ci.CData.GetHICON,
            h-2, h-2,
            0,0,DI_NORMAL);

		case ci.GetFormatType of
            FT_PICTURE:		bmp := FrmClipboardManager.iPic.Picture.Bitmap;
            FT_HTML: 		bmp  := FrmClipboardManager.iFormat.Picture.Bitmap;
            FT_RICHTEXT:	bmp := FrmClipboardManager.iFormat.Picture.Bitmap;
            FT_FILE: 		bmp := FrmClipboardManager.iFiles.Picture.Bitmap;
            else
            	bmp := FrmClipboardManager.iText.Picture.Bitmap;
        end;

        lbPopupQueue.Canvas.Draw(rect.Left+h, rect.Top+1, bmp);
        //s := UnitMisc.GetCliptypeSymbol(ci.GetFormat) + ' ' + s;
        //s := '['+ci.GetFormatName(false) + ']: ' + s;
        header := ' ';
    end else begin
        s := lbPopupqueue.Items.Strings[index];
    end;

    // leave a space for the icon
    // center the text if possible
    if (h  <=  th) then begin
        lbPopupqueue.Canvas.TextOut(
            rect.Left + h*2 , rect.Top, header);
        lbPopupqueue.Canvas.TextOut(
            rect.Left + h*2 + headerwd, rect.Top, s);
    end else begin
        lbPopupqueue.Canvas.TextOut(
            rect.Left + h*2 , floor((h-th)/2) + rect.Top, header);
        lbPopupqueue.Canvas.TextOut(
            rect.Left + h*2 + headerwd, floor((h-th)/2) + rect.Top, s);
    end;


    //
    // Draw/Clear the selection outline
    //
    c := lbPopupQueue.Canvas.Brush.color;
    if (odSelected in state) then begin
        lbPopupQueue.Canvas.Brush.Color := clHighlight;
        lbPopupQueue.Canvas.FrameRect(rect);
    end else begin
        lbPopupqueue.Canvas.Brush.color := clWindow;
        lbPopupQueue.Canvas.FrameRect(rect);
    end;
    lbPopupQueue.Canvas.Brush.color := c;
end;
procedure TfrmEditHistory.lbPopupQueueKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
if (key = Windows.VK_DELETE) then begin
        self.btnDelete.Click;
    end;
end;
procedure TfrmEditHistory.lbPopupQueueMeasureItem(Control: TWinControl; Index: Integer; var Height: Integer);
var ci : TClipItem;
    s : string;
begin
    height := math.max(18, lbPopupQueue.Canvas.TextHeight('ALKJDIOJ')+4);

    ci := ClipQueue.GetClipItem(index);
    if (ci <> nil) then begin
        s := '['+ci.GetFormatName(false) + ']: ';
        maxpopupheader := max(canvas.TextWidth(s), maxpopupheader);
    end;
end;

procedure TfrmEditHistory.lbRemovedListClick(Sender: TObject);
var i : integer;
begin
    self.RemovedResetButtons;

    myfree(ci);

//    i := (lbRemovedList.Count - 1) - lbRemovedList.ItemIndex;
    i := lbRemovedList.ItemIndex;
    ci := RemovedQueue.GetItemClip(i);
    if (ci <> nil) then begin
        FrameClipDisplay1.ShowClip(ci);
    end;
end;
procedure TfrmEditHistory.lbRemovedListDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState);
var ci : TClipItem;
    th, h, headerwd : integer;
    c, bc : TColor;
    header, s, s2 : string;

    bmp : TBitmap;
    pd : TPagedData;
    ti : integer;
const HEADER_WIDTH = 120;
begin
    // height of rectangle & height of text on the listbox
    h := (rect.Bottom - rect.top) + 1;
    th := lbRemovedList.Canvas.TextHeight('ALKJDFIOJ');
    headerwd  := lbRemovedList.Canvas.TextWidth('99-99-99: ');

    bc := lbRemovedList.Canvas.Brush.Color;
    lbRemovedList.Canvas.Brush.Color := clWhite;
    lbRemovedList.Canvas.FillRect(rect);
    lbRemovedList.Canvas.Brush.Color := bc;
    //
    // draw the icon leaving enough pixels above and below
    // for the selection outline
    //
//    ti  := (lbRemovedList.Count - 1) - index;
    ti := index;
    pd := RemovedQueue.GetPagedData(ti);

    if (true) then begin
        DrawIconEX(
            lbRemovedList.Canvas.Handle, rect.Left+2, rect.Top+1, pd.icon,
            h-2, h-2,
            0,0,DI_NORMAL);

		case pd.FormatType of
            FT_PICTURE:		bmp := FrmClipboardManager.iPic.Picture.Bitmap;
            FT_HTML: 		bmp  := FrmClipboardManager.iFormat.Picture.Bitmap;
            FT_RICHTEXT:	bmp := FrmClipboardManager.iFormat.Picture.Bitmap;
            FT_FILE: 		bmp := FrmClipboardManager.iFiles.Picture.Bitmap;
            else
            	bmp := FrmClipboardManager.iText.Picture.Bitmap;
        end;

        lbRemovedList.Canvas.Draw(rect.Left+h, rect.Top+1, bmp);

        try
            DateTimeToString(s2, 'mm-dd-yy', pd.FileDate);
        except
        end;

        header := s2 + '' ;
        s := pd.AsText;
    end;

    // leave a space for the icon
    // center the text if possible
    if (h  <=  th) then begin
        lbRemovedList.Canvas.TextOut(
            rect.Left + h*2+2, rect.Top, header);
        lbRemovedList.Canvas.TextOut(
            rect.Left + h*2 + 4 + headerwd, rect.Top, s);
    end else begin
        lbRemovedList.Canvas.TextOut(
            rect.Left + h*2+2, floor((h-th)/2) + rect.Top, header);
        lbRemovedList.Canvas.TextOut(
            rect.Left + h*2 + 4 +headerwd, floor((h-th)/2) + rect.Top, s);
    end;


    //
    // Draw/Clear the selection outline
    //
    c := lbRemovedList.Canvas.Brush.color;
    if (odSelected in state) then begin
        lbRemovedList.Canvas.Brush.Color := clHighlight;
        lbRemovedList.Canvas.FrameRect(rect);
    end else begin
        lbRemovedList.Canvas.Brush.color := clWindow;
        lbRemovedList.Canvas.FrameRect(rect);
    end;
    lbRemovedList.Canvas.Brush.color := c;

end;
procedure TfrmEditHistory.lbRemovedListMeasureItem(Control: TWinControl; Index: Integer; var Height: Integer);
begin
    height := math.max(16, lbRemovedList.Canvas.TextHeight('ALKJDIOJ')+4);
end;




procedure TfrmEditHistory.RemovedResetButtons;
var i : integer;
    pd : TPagedData;
    s : string;
begin

    btnRemovedEdit.Enabled := false;
    btnRemovedCopy.Enabled := false;
    btnRemovedCopyAs.Enabled := false;
    btnRemovedFind.Enabled := true;
    btnRemovedPermanent.Enabled := false;
    btnExportRemoved.Enabled := (lbRemovedList.SelCount>0);
    btnRemovedDelete.Enabled := btnExportRemoved.Enabled;
    if lbRemovedList.SelCount > 1 then begin
        EXIT;
    end;


    if lbRemovedList.itemindex <> -1 then begin
        btnRemovedEdit.Enabled := true;
        btnRemovedCopy.Enabled := true;
        btnRemovedCopyAs.Enabled := true;
        btnRemovedPermanent.Enabled := true;

        i := (lbRemovedList.Count - 1) - lbRemovedList.ItemIndex;
        pd := RemovedQUeue.GetPagedData(i);
        case pd.FormatType of
            FT_PICTURE:		s := 'Picture';
            FT_HTML: 		s := 'HTML Clip';
            FT_RICHTEXT:	s := 'RichText';
            FT_FILE: 		s := 'File(s)';
            FT_UNICODE:      s := 'Text';
            else
            	s := 'Unknown';
        end;
        CopyasFormat1.Caption := 'Copy as ' + s ;
        RemovedCreateClip.Caption := 'Create as ' + s + ' Clip';
    end;
end;
procedure TfrmEditHistory.PopupResetButtons;
var ci : TClipItem;
begin
    //bCopyAs.Enabled := false;
    btnCopyAs.Enabled := false;
    bCopyToClipboard.Enabled := false;
    btnDelete.Enabled := false;
    btnDeleteMore.enabled := false;
    btnPermanent.Enabled := false;
    btnEdit.Enabled := false;
    btnExport.Enabled := false;

    if lbPopupQueue.selcount = 0 then begin

    end else begin
        btnDelete.Enabled := true;
        btnDeleteMore.enabled := true;
        btnExport.Enabled := true;
        if lbPopupQueue.SelCount > 1 then begin
            EXIT;
        end;


        ci := ClipQueue.GetClipItem(lbPopupQueue.itemindex);
        if ci.GetFormat = CF_DIB then begin
            btnEdit.Enabled := true;
            bCopyToClipboard.Enabled := true;
            btnPermanent.Enabled := true;
            EXIT;
        end;

        btnEdit.Enabled := true;
       // bCopyAs.Enabled := true;
        btnCopyAs.Enabled := true;
        bCopyToClipboard.Enabled := true;
        btnPermanent.Enabled := true;
    end;
end;

procedure TfrmEditHistory.CreatePlainTextClick(Sender: TObject);
var ci : TClipItem;
begin
    ci := ClipQueue.GetClipItem(lbPopupQueue.itemindex);
    FrmPermanent.ShowWithNewItem(ci.GetAsPlaintext);
end;
procedure TfrmEditHistory.CopyasFormat1Click(Sender: TObject);
begin
    //self.FreeRemoved(ci);
    MyFree(ci);
    ci := self.RemovedClickedClip;
    if (ci = nil) then EXIT;

    Paste.SetClipboardOnlyOnce;
    frmClipboardManager.DisablePasteProtectionOnce;
    Paste.SendText('', ci);
end;
procedure TfrmEditHistory.cpgGroupsMouseWheel(Sender: TObject;
  Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint;
  var Handled: Boolean);
var
    direction : integer;
begin
    Handled := true;
    direction := -3;
    if wheelDelta < 0 then direction := 3;
    cpgGroups.VertScrollBar.Position :=
        cpgGroups.VertScrollBar.ScrollPos + cpgGroups.VertScrollBar.Increment * direction;
end;

procedure TfrmEditHistory.CreateClipClick(Sender: TObject);
var ci : TClipItem;
begin
    ci := ClipQueue.GetClipItem(lbPopupQueue.itemindex);
    FrmPermanent.ShowWithNewComplexItem(ci);
end;
procedure TfrmEditHistory.DeleteClip1Click(Sender: TObject);
begin
    btnDelete.Click;
    PopupResetButtons;
end;
procedure TfrmEditHistory.DestroyClip1Click(Sender: TObject);
var i,j : integer;
    ci : TClipItem;
begin
    if (MessageDlg('Destroy: Permanently delete the selected clips?', mtConfirmation, [mbyes, mbno],0) = mrYes) then begin

            for i := (lbPopupqueue.Items.count - 1) downto 0 do begin
                if (lbPopupqueue.Selected[i]) then begin
                    ci := TClipItem(lbPopupQueue.Items.Objects[i]);
                    j := ClipQueue.IndexOf(ci);

                    ClipQueue.DestroyItem(j);
                    lbPopupQueue.Items.Delete(i);
                end;
            end;

    end;
    PopupResetButtons;
end;



procedure TfrmEditHistory.btnExportClick(Sender: TObject);
var s, num : string;
    i,j : integer;
    ci : TClipItem;
begin
    s := SpecialPaths.GetMyDocs;
    if VCL.FileCtrl.SelectDirectory(
        'Save as Text,RichText,Pictures in a Single Folder',
        WideString(''),
        s,
        [sdNewFolder, sdShowEdit, sdShowShares, sdNewUI, sdValidateDir],
        self
    ) then begin

        for i := 0 to lbPopupQueue.count - 1 do begin
            if lbPopupQueue.Selected[i] then begin
                j := 0;
                repeat
                    inc(j);
                    num := Format('%.4d',[j]);
                until   not (
                    FileExists(IncludeTrailingPathDelimiter(s) + 'PopupClip'+num+'.txt') or
                    FileExists(IncludeTrailingPathDelimiter(s) + 'PopupClip'+num+'.rtf') or
                    FileExists(IncludeTrailingPathDelimiter(s) + 'PopupClip'+num+'.bmp')
                );

                ci := ClipQueue.GetClipItem(i);

                case ci.GetFormatType  of
                FT_RICHTEXT: begin
                    frmEditTextExternal.SaveClip(
                        IncludeTrailingPathDelimiter(s) + 'PopupClip'+num+'.rtf',
                        ci
                    );
                end;
                FT_PICTURE: begin
                    frmEditTextExternal.SaveClip(
                        IncludeTrailingPathDelimiter(s) + 'PopupClip'+num+'.bmp',
                        ci
                    );
                end;
                else begin
                    frmEditTextExternal.SaveClip(
                        IncludeTrailingPathDelimiter(s) + 'PopupClip'+num+'.txt',
                        ci
                    );
                end;
                end;
            end;
        end;

        if MessageDlg('Clips saved to folder: ' + s +#13#10#13#10 +
                    'Open this folder in Explorer?',
                    mtConfirmation, [mbYes, mbNo],0,mbYes
        ) = mrYes then begin
            Paste.SendTextWithKeystrokes('[KEYS][RUN]'+ s); 
        end;
    end;
end;
procedure TfrmEditHistory.btnExportRemovedClick(Sender: TObject);
var s, num : string;
    i,j : integer;
    ci : TClipItem;
begin
    s := SpecialPaths.GetMyDocs;
    if VCL.FileCtrl.SelectDirectory(
        'Save as Text,RichText,Pictures in a Single Folder',
        WideString(''),
        s,
        [sdNewFolder, sdShowEdit, sdShowShares, sdNewUI, sdValidateDir],
        self
    ) then begin

        for i := 0 to lbRemovedList.count - 1 do begin
            if lbRemovedList.Selected[i] then begin
                j := 0;
                repeat
                    inc(j);
                    num := Format('%.4d',[j]);
                until   not (
                    FileExists(IncludeTrailingPathDelimiter(s) + 'RemovedClip'+num+'.txt') or
                    FileExists(IncludeTrailingPathDelimiter(s) + 'RemovedClip'+num+'.rtf') or
                    FileExists(IncludeTrailingPathDelimiter(s) + 'RemovedClip'+num+'.bmp')
                );

                ci := RemovedQueue.GetItemClip(i);


				case ci.GetFormatType  of
                FT_RICHTEXT: begin
                    frmEditTextExternal.SaveClip(
                        IncludeTrailingPathDelimiter(s) + 'RemovedClip'+num+'.rtf',
                        ci
                    );
                end;
                FT_PICTURE: begin
                    frmEditTextExternal.SaveClip(
                        IncludeTrailingPathDelimiter(s) + 'RemovedClip'+num+'.bmp',
                        ci
                    );
                end;
                else begin
                    frmEditTextExternal.SaveClip(
                        IncludeTrailingPathDelimiter(s) + 'RemovedClip'+num+'.txt',
                        ci
                    );
                end;
                end;
                myfree(ci);
            end;
        end;

        if MessageDlg('Clips saved to folder: ' + s +#13#10#13#10 +
                    'Open this folder in Explorer?',
                    mtConfirmation, [mbYes, mbNo],0,mbYes
        ) = mrYes then begin
            Paste.SendTextWithKeystrokes('[KEYS][RUN]'+ s); 
        end;

    end;
end;

procedure TfrmEditHistory.odExportCanClose(Sender: TObject; var CanClose: Boolean);
begin
    CanClose := true;
end;

end.
