Skip to content

Instantly share code, notes, and snippets.

@rtomazini42
Created September 21, 2023 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rtomazini42/e770e3a679e37625b7ddfe8419eeeecb to your computer and use it in GitHub Desktop.
Save rtomazini42/e770e3a679e37625b7ddfe8419eeeecb to your computer and use it in GitHub Desktop.
{ -------------------------------------------------------------------------------
Procedure: TfmxJabberClient.OnMessageReceivedProc
Arguments: AFrom, AMessage: string
Result: None
------------------------------------------------------------------------------- }
procedure TfmxJabberClient.OnMessageReceivedProc(AFrom, AMessage: string);
begin
if assigned(fOnMessageReceived) then
fOnMessageReceived(AFrom, AMessage);
end;
unit frameChat;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls,
FMX.ListView.Types, FMX.ListView.Appearances, FMX.ListView.Adapters.Base,
System.ImageList, FMX.ImgList, FMX.Layouts, FMX.ListBox, FMX.ListView,
FMX.Controls.Presentation, FMX.Objects, Alcinoe.FMX.Memo, FMX.TextLayout,
Alcinoe.FMX.Objects, Alcinoe.FMX.Edit,ConversationListComponent, CommonHeader, FmxJabberTools, fmxJabberClient;
type
TFrameChatFrm = class(TFrame)
Rodape: TLayout;
ALEdit1: TALEdit;
ALRecAnexo: TALRectangle;
IconClip: TPath;
AlRecBtnEnvio: TALRectangle;
IconSent: TPath;
ALMemoMensagens: TALMemo;
Topo: TALRectangle;
ImgContato: TImage;
NomeUser: TLabel;
ALRecCallCam: TALRectangle;
IconCam: TPath;
ALRectangleMenu: TALRectangle;
IconDesativo: TPath;
IconAtivo: TPath;
StyleBook1: TStyleBook;
lvChat: TListView;
RectExt: TALRectangle;
ALRecColor: TALRectangle;
IconCores: TPath;
lbl: TLabel;
ALRecLoja: TALRectangle;
IconLoja: TPath;
lbl2: TLabel;
ALMidia: TALRectangle;
IconTopSeller: TPath;
Label1: TLabel;
ALClose: TALRectangle;
IconClose: TPath;
Label2: TLabel;
ALRecFechaOpcoes: TALRectangle;
IconFechar: TPath;
Label3: TLabel;
LayAnexosOpt: TLayout;
ALRectAnexarImagem: TALRectangle;
Label4: TLabel;
IconImage: TPath;
ALRectAnexarDocumento: TALRectangle;
Label5: TLabel;
IconDocument: TPath;
RectAvisos: TALRectangle;
OkAvisos: TALRectangle;
Label6: TLabel;
TextoAviso: TLabel;
ViewPhotos: TALRectangle;
Layout1: TLayout;
CloseTheImg: TPath;
Label7: TLabel;
ListImagesBox: TListBox;
JanelaErro: TRectangle;
ErroTexto: TLabel;
RecBtnJanelaErro: TRectangle;
Label8: TLabel;
StyleBook2: TStyleBook;
StyleBook3: TStyleBook;
imgFundo: TImage;
OpenDialog1: TOpenDialog;
BookImages: TStyleBook;
ListaFundos: TImageList;
procedure ALRectangleMenuClick(Sender: TObject);
procedure AlRecBtnEnvioClick(Sender: TObject);
procedure ALRecAnexoClick(Sender: TObject);
procedure OkAvisosClick(Sender: TObject);
procedure FramePaint(Sender: TObject; Canvas: TCanvas;
const ARect: TRectF);
procedure LayoutLvProprio(item: TListViewItem);
procedure LayoutLv(item: TListViewItem);
procedure AddMessage(id_msg: integer; texto, dt: string;
ind_proprio: boolean);
private
procedure lvChatUpdateObjects(const Sender: TObject;
const AItem: TListViewItem);
function GetTextHeight(const D: TListItemText; const Width: single;
const Text: string): Integer;
{ Private declarations }
public
CurrentBackgroundIndex: Integer;
TalkComp : TConversationList;
MessageTo : string;
nomeCliente: string;
OnSendMessage : TOnMessageReceived;
procedure Initialize( ATo : String);
end;
implementation
{$R *.fmx}
procedure TFrameChatFrm.ALRecAnexoClick(Sender: TObject);
begin
if LayAnexosOpt.Visible then
LayAnexosOpt.Visible := False
else
LayAnexosOpt.Visible := True;
end;
procedure TFrameChatFrm.AlRecBtnEnvioClick(Sender: TObject);
var
Mensagem: string;
begin
//IdTCPClient1.IOHandler.WriteLn(FormatChatMessage(lbEdtMsg.Text,lbEdtNick.Text,GetUserList,cboxReservado.IsChecked));
if (Assigned(OnSendMessage)) and (Trim(ALEdit1.Text) <> '') then
begin
Mensagem := ALEdit1.Text;
OnSendMessage(NomeCliente {+ '@192.168.1.10' }, Mensagem);
AddMessage(1, Mensagem, FormatDateTime(' dd/mm/yyyy hh:nn:ss', Now), True);
//Mensagem := '[' + NomeCliente + '] diz: ' + Mensagem + '||@|| ' + FormatDateTime(' dd/mm/yyyy hh:nn:ss', Now);
ALEdit1.Text := '';
//ShowMessage(self.Name);
end;
end;
procedure TFrameChatFrm.ALRectangleMenuClick(Sender: TObject);
begin
if RectExt.Visible = False then
begin
RectExt.Visible := True;
IconAtivo.Visible := True;
IconDesativo.Visible := False;
end
else
begin
RectExt.Visible := False;
IconAtivo.Visible := False;
IconDesativo.Visible := True;
end;
end;
procedure TFrameChatFrm.FramePaint(Sender: TObject; Canvas: TCanvas;
const ARect: TRectF);
begin
CurrentBackgroundIndex := 0;
end;
function TFrameChatFrm.GetTextHeight(const D: TListItemText;
const Width: single; const Text: string): Integer;
var
Layout: TTextLayout;
begin
Layout := TTextLayoutManager.DefaultTextLayout.Create;
try
Layout.BeginUpdate;
try
Layout.Font.Assign(D.Font);
Layout.VerticalAlign := D.TextVertAlign;
Layout.HorizontalAlign := D.TextAlign;
Layout.WordWrap := D.WordWrap;
Layout.Trimming := D.Trimming;
Layout.MaxSize := TPointF.Create(Width, TTextLayout.MaxLayoutSize.Y);
Layout.Text := Text;
finally
Layout.EndUpdate;
end;
Result := Round(Layout.Height);
Layout.Text := 'm';
Result := Result + Round(Layout.Height);
finally
Layout.Free;
end;
end;
procedure TFrameChatFrm.Initialize(ATo: String);
begin
NomeCliente:= ATo;
//TalkComp := TConversationList.Create(Self,'Me', ATo);
//TalkComp.Parent := Panel1;
{ TalkComp.Align := TAlignLayout.Client;
TalkComp.Position.X := 5;
TalkComp.Position.Y := 40;
TalkComp.width := width - 10;
TalkComp.Height := 380; }
//panel1.Anchors := [TAnchorKind.akleft, TAnchorKind.aktop, TAnchorKind.akright, TAnchorKind.akbottom];
end;
procedure TFrameChatFrm.LayoutLv(item: TListViewItem);
var
img: TListItemImage;
txt: TListItemText;
rect: TALRectangle;
begin
//ShowMessage('1');
// Posiciona o texto...
txt := TListItemText(item.Objects.FindDrawable('txtMsg'));
txt.Width := lvChat.Width / 2 - 40; // Ajuste a largura conforme necessário
txt.PlaceOffset.X := 20;
txt.PlaceOffset.Y := 10;
txt.Height := GetTextHeight(txt, txt.Width, txt.Text);
txt.TextColor := $FF000000;
// Balao msg...
img := TListItemImage(item.Objects.FindDrawable('imgFundo'));
img.Width := txt.Width + 20; // Ajuste a largura conforme necessário
img.PlaceOffset.X := 10;
img.PlaceOffset.Y := 10;
img.Height := txt.Height;
img.Opacity := 0.1;
// Data...
txt := TListItemText(item.Objects.FindDrawable('txtData'));
txt.PlaceOffset.X := img.PlaceOffset.X + img.Width - 100;
txt.PlaceOffset.Y := img.PlaceOffset.Y + img.Height + 2;
// Altura do item da Lv...
item.Height := Trunc(img.PlaceOffset.Y + img.Height + 30);
end;
procedure TFrameChatFrm.LayoutLvProprio(item: TListViewItem);
var
img: TListItemImage;
txt: TListItemText;
begin
// Posiciona o texto...
txt := TListItemText(item.Objects.FindDrawable('txtMsg'));
txt.Width := lvChat.Width / 2 - 40; // Ajuste a largura conforme necessário
txt.PlaceOffset.Y := 10;
txt.Height := GetTextHeight(txt, txt.Width, txt.Text);
txt.TextColor := $FFFFFFFF;
// Balao msg...
img := TListItemImage(item.Objects.FindDrawable('imgFundo'));
img.Width := txt.Width + 20; // Ajuste a largura conforme necessário
img.PlaceOffset.X := lvChat.Width - img.Width - 10;
img.PlaceOffset.Y := 10;
img.Height := txt.Height;
img.Opacity := 1;
txt.PlaceOffset.X := img.PlaceOffset.X + 10;
// Data...
txt := TListItemText(item.Objects.FindDrawable('txtData'));
txt.PlaceOffset.X := img.PlaceOffset.X + img.Width - 100;
txt.PlaceOffset.Y := img.PlaceOffset.Y + img.Height + 2;
// Altura do item da Lv...
item.Height := Trunc(img.PlaceOffset.Y + img.Height + 30);
end;
procedure TFrameChatFrm.lvChatUpdateObjects(const Sender: TObject;
const AItem: TListViewItem);
begin
if AItem.TagString = 'S' then
LayoutLvProprio(AItem)
else
LayoutLv(AItem);
end;
procedure TFrameChatFrm.AddMessage(id_msg: integer;
texto, dt: string;
ind_proprio: boolean);
var
item: TListViewItem;
Size: TSizeF;
wMessage: TText;
begin
// ShowMessage(texto);
Size := TSizeF.Create(60,60);
item := lvChat.Items.Add;
with item do
begin
Height := 100;
Tag := id_msg;
if ind_proprio then
TagString := 'S'
else
TagString := 'N';
// Fundo...
TListItemImage(Objects.FindDrawable('imgFundo')).Bitmap := ListaFundos.Bitmap(Size,CurrentBackgroundIndex);
// Texto...
TListItemText(Objects.FindDrawable('txtMsg')).Text := texto;
// Data...
TListItemText(Objects.FindDrawable('txtData')).Text := dt;
end;
if ind_proprio then
LayoutLvProprio(item)
else
LayoutLv(item);
end;
procedure TFrameChatFrm.OkAvisosClick(Sender: TObject);
begin
RectAvisos.Visible := False;
end;
end.
unit frmContacts;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs,
FMX.ListView.Types, FMX.ListView.Appearances, FMX.ListView.Adapters.Base,
Alcinoe.FMX.Objects, FMX.ListView, FMX.TabControl, FMX.Objects,
FMX.ListBox, FMX.Controls.Presentation, FMX.StdCtrls, FMX.Layouts, fmxJabberClient, CommonHeader, FmxJabberTools,
Alcinoe.FMX.Edit, System.StrUtils, FMX.Memo;
type
TFormContacts = class(TForm)
Layout1: TLayout;
Layout2: TLayout;
Fundo: TALRectangle;
lbDisplayName: TLabel;
btnADD: TALRectangle;
AlCirStatus: TALCircle;
Layout3: TLayout;
TabControl1: TTabControl;
TabItem1: TTabItem;
ListViewContacts: TListView;
ALText1: TALText;
Path1: TPath;
JanelaAdd: TALRectangle;
Label1: TLabel;
EdtNomeAdd: TALEdit;
BtnAddContato: TALRectangle;
Label2: TLabel;
ALRectangle1: TALRectangle;
Label3: TLabel;
Label4: TLabel;
LblEstado: TLabel;
Layout4: TLayout;
StyleBook1: TStyleBook;
ListView1: TListView;
TabItem2: TTabItem;
TabControl2: TTabControl;
procedure FormCreate(Sender: TObject);
procedure btnADDClick(Sender: TObject);
procedure BtnAddContatoClick(Sender: TObject);
procedure ALRectangle1Click(Sender: TObject);
procedure Layout4Click(Sender: TObject);
procedure LisvartViewContactsClick(Sender: TObject);
function jaAberto(procura: string): boolean;
procedure FormShow(Sender: TObject);
private
{ Private declarations }
procedure OnMessageReceivedProc(AFrom, AMessage : string);
procedure OnNewContactProc(AJID : string);
procedure OnAskTosendMessageProc(ATo, AMessage : string);
function GetTabIndex(ATagString : string ) : integer;
procedure CreateConversation(AContact : PContact); overload;
procedure OnPResenceCallBack(AJid : String);
procedure UpdateContactDisplay(AIdx : integer);
procedure ContactAskToAddProc(Jid : string; var AAccept : Boolean);
procedure OnAddContactStatusProc(AJid : string; AAccepted : Boolean);
procedure btnAddcontactClick(Sender: TObject);
public
procedure Showcontacts;
end;
var
FormContacts: TFormContacts;
gerenciadorVisivel : boolean;
servidor: string ;
implementation
{$R *.fmx}
uses UnitPrincipal, frameChat;
procedure TFormContacts.ALRectangle1Click(Sender: TObject);
begin
JanelaAdd.Visible := false;
end;
procedure TFormContacts.btnADDClick(Sender: TObject);
var
wID : string;
begin
JanelaAdd.Visible := True;
end;
procedure TFormContacts.btnAddcontactClick(Sender: TObject);
begin
JanelaAdd.Visible := True;
end;
procedure TFormContacts.BtnAddContatoClick(Sender: TObject);
var
wID : string;
begin
if EdtNomeAdd.Text <> '' then
begin
wID := EdtNomeAdd.Text + '@192.168.1.10'; // descobri que tem que sempre colocar o servidor e arroba no final
GJabberClient.AddContact(wID,wID,'');
JanelaAdd.Visible := False;
ShowMessage('contato adicionado')
end
else
ShowMessage('algo deu errado');
ShowContacts;
end;
function TFormContacts.GetTabIndex(ATagString: string): integer;
var i : integer;
begin
Result := -1;
for i := 0 to TabControl2.TabCount -1 do
if Pos(uppercase(TabControl2.Tabs[i].TagString) , UpperCase(ATagString)) > 0 then
begin
Result := i;
Break;
end;
end;
function TFormContacts.jaAberto(procura: string): boolean;
var
i: Integer;
TabName: string;
begin
// Percorre todas as abas na TabControl1
for i := 0 to TabControl1.TabCount - 1 do
begin
TabName := TabControl1.Tabs[i].Text;
// Faça a verificação (if) com o nome da aba
if TabName = procura then
begin
TabControl1.TabIndex := i;
result := True;
end
else
result := False;
end;
end;
procedure TFormContacts.Layout4Click(Sender: TObject);
begin
if LblEstado.Text = 'Online' then
begin
GJabberClient.SetPresence(usAway, '');
LblEstado.Text := 'Ausente';
AlCirStatus.Fill.Color := TAlphaColors.Lightcoral;
end
else
begin
GJabberClient.SetPresence(usOnline, '');
LblEstado.Text := 'Online';
AlCirStatus.Fill.Color := TAlphaColors.Lightgreen;
end;
end;
procedure TFormContacts.OnAskTosendMessageProc(ATo, AMessage: string);
begin
GJabberClient.SendMessage(ATo, AMessage);
end;
procedure TFormContacts.LisvartViewContactsClick(Sender: TObject);
var
wTabID: Integer;
wContact: PContact;
//NewTab: TTabItem;
//NewFrame: TFrameChatFrm;
begin
if ListViewContacts.ItemIndex <> -1 then
begin
wContact := GJabberClient.Contacts[ListViewContacts.ItemIndex];
wTabID := GetTabIndex( wContact.Jid );
if wTabID = -1 then
begin
CreateConversation(wContact);
wTabID := TabControl2.TabCount -1;
end;
TabControl1.ActiveTab := TabItem2;
TabControl2.TabIndex := wTabID;
end;
end;
{if ListViewContacts.ItemIndex <> -1 then
begin
wContact := GJabberClient.Contacts[ListViewContacts.ItemIndex];
if Assigned(wContact) then
begin
if jaAberto(wContact.Jid) then
begin
ShowMessage('Conversa já aberta');
end
else
begin
try
NewTab := TTabItem.Create(TabControl1);
NewTab.Text := wContact.Jid;
NewFrame := TFrameChatFrm.Create(NewTab);
NewFrame.Initialize(wContact.Jid);
NewFrame.OnSendMessage := OnAskTosendMessageProc;
NewFrame.Name := 'Frame_' + inttostr(TabControl1.TabCount);
NewFrame.Parent := NewTab;
NewFrame.Align := TAlignLayout.Client;
NewFrame.NomeUser.Text := wContact.Jid + servidor;
except
on E: Exception do
Raise Exception.Create('[TFormContacts.LisvartViewContactsClick]: ' + E.Message);
end;
TabControl1.AddObject(NewTab);
end;
end;
end;
end;}
procedure TFormContacts.CreateConversation(AContact: PContact);
var
wNewTab : TTabItem;
wFrame : TFrameChatFrm;
begin
try
wNewTab := TTabItem.Create(TabControl2);
wNewTab.Text := AContact.Jid;
wNewTab.TagString := AContact.Jid;
wFrame := TFrameChatFrm.Create(Self);
wFrame.Name := 'Frame_' + inttostr(TabControl2.TabCount);
wFrame.Parent := wNewTab;
//wFrame.nomeCliente :=AContact.Jid;
wFrame.MessageTo :=AContact.Jid;
wFrame.NomeUser.Text:=AContact.Jid;
wFrame.OnSendMessage := OnAskTosendMessageProc;
wFrame.Initialize(AContact.Jid + servidor);
TabControl2.AddObject(wNewTab);
wFrame.Align := TAlignLayout.Client;
except
On E:Exception do
Raise Exception.create('[TFormContacts.CreateConversation] : '+E.message);
end;
end;
procedure TFormContacts.ContactAskToAddProc(Jid: string;
var AAccept: Boolean);
var wContactName : String;
begin
AAccept := False;
wContactName := jid;
if MessageDlg(wContactName + ' want to add you to it''s contacts list, ok ?',TMsgDlgType.mtConfirmation,mbYesNo,0) = mrYes then
AAccept := True;
end;
procedure TFormContacts.FormCreate(Sender: TObject);
begin
servidor := '@192.168.1.10';
gerenciadorVisivel := False;
GJabberClient.OnNewContact := OnNewContactProc;
GJabberClient.OnMessageReceived := OnMessageReceivedProc;
GJabberClient.OnUpdatePresence := OnPResenceCallBack;
GJabberClient.OnContactAskToAdd := ContactAskToAddProc;
GJabberClient.OnAddContactStatus := OnAddContactStatusProc;
end;
procedure TFormContacts.FormShow(Sender: TObject);
begin
Caption := GJabberClient.Login;
GJabberClient.SetPresence(usOnline, '');
//abberClient.OnMessageReceived := OnMessageReceivedProc;
end;
procedure TFormContacts.OnAddContactStatusProc(AJid: string;
AAccepted: Boolean);
begin
end;
procedure TFormContacts.OnMessageReceivedProc(AFrom, AMessage: string);
begin
TThread.Queue(nil,
procedure
var
i, wTabID: Integer;
wFrame: TFrameChatFrm;
wContact: PContact;
begin
try
Caption := AMessage;
ListViewContacts.BeginUpdate;
try
wTabID := GetTabIndex(AFrom);
if wTabID <> -1 then
begin
wFrame := TFrameChatFrm(FindComponent('Frame_' + inttostr(wTabID)));
if wFrame <> nil then
begin
wFrame.AddMessage(0, AMessage, '', false);
end;
end
else
begin
for i := 0 to GJabberClient.ContactsCount - 1 do
begin
wContact := GJabberClient.Contacts[i];
if Pos(uppercase(wContact.Jid), uppercase(AFrom)) > 0 then
begin
CreateConversation(GJabberClient.Contacts[i]);
wTabID := GetTabIndex(AFrom);
if wTabID <> -1 then
begin
wFrame := TFrameChatFrm(FindComponent('Frame_' + inttostr(wTabID)));
if wFrame <> nil then
begin
wFrame.AddMessage(0, AMessage, '', false);
//wFrame.MemText2Send.SetFocus;
end;
end;
ListViewContacts.Items[i].Detail := '! New message !';
ListViewContacts.Repaint;
Break;
end;
end;
end;
finally
ListViewContacts.EndUpdate;
end;
except
on E: Exception do
begin
// Tratar a exceção aqui, por exemplo, mostrar uma mensagem de erro
ShowMessage('Ocorreu uma exceção: ' + E.Message);
end;
end;
end
);
end;
procedure TFormContacts.OnNewContactProc(AJID: string);
begin
ShowContacts;
end;
procedure TFormContacts.OnPResenceCallBack(AJid: String);
var i : integer;
begin
if AJid = '-2' then
begin
case GJabberClient.UserStatus of
usOnline : begin
AlCirStatus.Fill.Color := TAlphaColors.Green;
GJabberClient.SetPresence(usOnline, '');
//ImgUserstatus.Bitmap.Assign(FormConnect.OnlineImage.Bitmap); //LoadFromFile(GetImageFilename('online.png'));
end;
usAway : begin
AlCirStatus.Fill.Color := TAlphaColors.Red;
GJabberClient.SetPresence(usAway, '');
//ImgUserstatus.Bitmap.Assign(FormConnect.BusyImage.Bitmap); //LoadFromFile(GetImageFilename('busy.png'));
end;
usInVisible : begin
AlCirStatus.Fill.Color := TAlphaColors.Alpha;
GJabberClient.SetPresence(usInVisible, '');
//ImgUserstatus.Bitmap.Assign(FormConnect.OfflineImage.Bitmap); //LoadFromFile(GetImageFilename('offline.png'));
end;
end;
end
{else begin
for i := 0 to GJabberClient.ContactsCount -1 do
begin
if CompareText(AJid,GJabberClient.Contacts[i].Jid) = 0 then
UpdateContactDisplay(i);
end;
end; }
end;
procedure TFormContacts.Showcontacts;
var i : integer;
wContact : PContact;
wTListViewItem : TListViewItem;
begin
ListViewContacts.Items.Clear;
FormContacts.ListViewContacts.BeginUpdate;
try
for i := 0 to GJabberClient.ContactsCount -1 do
begin
wTListViewItem := ListViewContacts.Items.Add;
wContact := GJabberClient.Contacts[i];
wTListViewItem.Text := IFTHEN(wContact.Name = '', wContact.Jid, wContact.Name);
wTListViewItem.Detail := wContact.ADisplayMessage;
//wTListViewItem.Bitmap.Assign(FormConnect.OfflineImage.Bitmap); //LoadFromFile(GetImageFilename('offline.png'));
end;
finally
FormContacts.ListViewContacts.EndUpdate;
end;
end;
procedure TFormContacts.UpdateContactDisplay(AIdx: integer);
var
icon: TBitmap;
begin
icon.CreateFromFile('C:\Users\viacr\OneDrive\Área de Trabalho\Chat 1009\Chat 1009\Chat 2808\ChatProject\Img\UserBlue.png');
ListViewContacts.Items[Aidx].Detail := GJabberClient.Contacts[AIdx].ADisplayMessage;
case GJabberClient.Contacts[AIdx].AStatus of
usOnline : ListViewContacts.Items[Aidx].Bitmap.Assign(icon); //LoadFromFile(GetImageFilename('online.png'));
usAway : ListViewContacts.Items[Aidx].Bitmap.Assign(icon); //LoadFromFile(GetImageFilename('busy.png'));
usInVisible : ListViewContacts.Items[Aidx].Bitmap.Assign(icon); //LoadFromFile(GetImageFilename('offline.png'));
end;
end;
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment