Source

oberchatten / MsgUnit.cpp

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
/*
Copyright (C) 2001-2006 Daybo Logic.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.
3. Neither the name of the project nor the names of its contributors
   may be used to endorse or promote products derived from this software
   without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
*/
//---------------------------------------------------------------------------
#include "overchat_config.h"
#include <vcl.h>
#include <limits.h>
#include <time.h>
#include <stdio.h>
#include <assert.h>
#include <dir.h> // For mkdir()
#include <deque>
#include <string>
#ifdef HDRSTOP
# pragma hdrstop
#endif //HDRSTOP

#include "dlstdinc.h"
#include "blake.h"
#include "Events.h"
#include "History.h"
#include "MsgUnit.h"
#include "NetBuffer.h"
#include "Options.h"
#include "StatusBarManagerUnit.h" // TStatusBarManager
#include "ChatFormUnit.h" // TChatForm
#include "MyUserUnit.h" // TMyUser
#include "MainFormUnit.h"
#include "Globals.h"
#include "General.h"
#include "ShadowUnit.h"
#include "Options.h"
#include "SoundsUnit.h"
#include "SetKeyUnit.h"
#include "AwayMessageUnit.h" // TAwayMessageDlg
#include "InfoBoxUnit.h" // InfoBox()
#include "daybocrypt.h" // Cryptography library
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TMsgForm *MsgForm;

using namespace Oberchatten;

#ifdef OVERCHAT_RCS_STAMPS
static const char *rcsid =
  "$Id: MsgUnit.cpp,v 0.7 2006/03/05 13:02:00 ddrp Exp $";
#endif /*OVERCHAT_RCS_STAMPS*/
//---------------------------------------------------------------------------
__fastcall TMsgForm::TMsgForm(TComponent* Owner)
        : TForm(Owner),
          pendingDelete(false),
          flashMode(false),
          flashCurrentState(false),
          keyphrase(""),
          printingAwayMsg(false),
          clipboardAllowed(false)
{
  #ifdef OVERCHAT_RCS_STAMPS
    blake_Unused(rcsid);
  #endif /*OVERCHAT_RCS_STAMPS*/

  // Up to fifty previous comments may be recalled
  history.SetBufferLimit(50);
}
//---------------------------------------------------------------------------
void TMsgForm::SetRemoteUserName(
  AnsiString& NewRemoteUserName
)
{
  remoteUserName = NewRemoteUserName;
  RefreshTitle();
}
//---------------------------------------------------------------------------
void TMsgForm::SetRemoteUserName(
  const char *NewRemoteUserName
)
{
  remoteUserName = NewRemoteUserName;
  RefreshTitle();
}
//---------------------------------------------------------------------------
AnsiString& TMsgForm::GetRemoteUserName()
{
  return remoteUserName;
}
//---------------------------------------------------------------------------
void TMsgForm::RefreshTitle()
{
  Caption = "Conversation with " + remoteUserName;
}
//---------------------------------------------------------------------------
void __fastcall TMsgForm::FormClose(
  TObject *Sender,
  TCloseAction &Action
)
{
  // Program will clean this form up later
  this->pendingDelete = true;
}
//---------------------------------------------------------------------------
void __fastcall TMsgForm::CloseBtnClick(TObject *Sender)
{
  pendingDelete = true;
}
//---------------------------------------------------------------------------
void __fastcall TMsgForm::MsgBtnClick(TObject *Sender)
{
  enum blakeCipherID bcid;
  AnsiString msg(MessageEdit->Text); // Copy message

  /*
    Limit to the recommended maximum bytes unless debugging programmer
    has set this safegaurd off to test the server can deal with it too
  */
  if ( msg.Length() > OVERCHAT_MSG_LIMIT_BYTES ) {
    MainForm->FoolishUser("The message is too long!");
  }
  else {
    time_t timeOfMsg;

    time(&timeOfMsg);
    // In case user wants to recall this message
    history.AddString(MessageEdit->Text.c_str());
    MessageEdit->Text = ""; // Get rid of message
    if ( MnuLeetSpeak->Checked )
      blake_13375p34k(msg.c_str());

    // Add your text to the conversation, all stuff here is plaintext
    AddToConversation(
      timeOfMsg,
      MainForm->MyUser.GetUserName(),
      msg,
      bcidPlain
    );
    bcid = Encipher(msg);
    blake_Msg(
      GlobalNetBuffer.GetSocket(),
      remoteUserName.c_str(),
      msg.c_str(),
      bcid,
      0
    );
    MessageEdit->Tag = 0; // No undoing stuff on the edit box now
    AwayMessageDlg->SetLastActionTime(&timeOfMsg); // Prevent auto-away
  }
}
//---------------------------------------------------------------------------
void __fastcall TMsgForm::FormResize(TObject *Sender)
{
  this->CommandPanel->Width = this->ClientWidth;

  this->CommandPanel->Top =
    this->ClientHeight - (this->CommandPanel->Height+1);

  this->MessageEdit->Top =
    this->CommandPanel->Top - this->MessageEdit->Height -1;

  this->MessageEdit->Left = 8;
  this->MessageEdit->Width = this->ClientWidth - 16;

  this->ConversationMemo->Height =
    this->ClientHeight -
      (this->CommandPanel->Height + this->MessageEdit->Height + 1);

  this->ConversationMemo->Width = this->ClientWidth;
}
//---------------------------------------------------------------------------
void __fastcall TMsgForm::FormKeyPress(
  TObject *Sender,
  char &Key
)
{
  if ( Key == '\r' ) { /* Pressing enter? */
    if ( MsgBtn->Enabled )
      MsgBtnClick(0); /* Shortcut to send message button */
  }
}
//---------------------------------------------------------------------------
void __fastcall TMsgForm::SaveBtnClick(TObject *Sender)
{
  if ( SaveDialog->Execute() )
    ConversationMemo->Lines->SaveToFile(SaveDialog->FileName);
}
//---------------------------------------------------------------------------
void __fastcall TMsgForm::WhoisBtnClick(TObject *Sender)
{
  MainForm->Whois(remoteUserName);
}
//---------------------------------------------------------------------------
void TMsgForm::AddToConversation(
  const time_t When,
  const char *UserName,
  const char *NewComment,
  const enum blakeCipherID CipherID,
  const blake_word8_t Flags1
)
{
  const AnsiString un(UserName);
  const AnsiString nc(NewComment);

  AddToConversation(
    When,
    un,
    nc,
    CipherID,
    Flags1
  );
}
//---------------------------------------------------------------------------
void TMsgForm::AddToConversation(
  const time_t When,
  const AnsiString &UserName,
  const AnsiString &NewComment,
  const enum blakeCipherID CipherID,
  const blake_word8_t Flags1
)
{
  const char* me = "/me ";
  const char* unofficialkill = "/unofficialkill";
  const char* wobblewindow = "/wobblewindow";
  const char* version = "/version";
  const char* slap = "/slap";
  AnsiString newcomment(NewComment);

  if ( UserName == remoteUserName ) // Strings coming from other users are ciphered
    Decipher(newcomment); // Decipher

  // Both strings must contain _something_
  if ( !(UserName.IsEmpty() || newcomment.IsEmpty()) ) {
    // Add to conversation, handling /me command
    if ( strnicmp(newcomment.c_str(), me, sizeof(me)-1) == 0 ) {
      // Miss the /me string out
      AnsiString newComment(NewComment.c_str() + (sizeof(me)-1));
      AddWithTime(When, "*** " + UserName + " " + newComment);
    }
    else if (
      UserName == remoteUserName &&
      stricmp(newcomment.c_str(), unofficialkill) == 0
    ) {
      MessageEdit->Text = "[NOTICE] This method of killing is no longer supported by OberChatten";
      MsgBtn->OnClick(0);
    }
    else if ( stricmp(newcomment.c_str(), wobblewindow) == 0 ) {
      WobbleWindow();
    }
    else if ( stricmp(newcomment.c_str(), version) == 0 ) {
      if ( UserName == remoteUserName ) { // It was the other person who said "/version"
        // Print status
        AddToConversation(
          When,
          "OverChat", "Remote user has requested version information"
        );
        Version(); // Send version stuff as message
      }
      else { // You have said "/version"
        // Print a status
        AddToConversation(When, "OverChat", "Requesting version information");
      }
    }
    else if ( stricmp(newcomment.c_str(), slap) == 0 ) {
      if ( UserName == remoteUserName ) // It was the other person who said /slap?
        AddToConversation(When, "OverChat", "You have been slapped!");
      else // It is you who is slapping
        AddToConversation(When, "OverChat", "You have slapped this user");
    }
    else
      AddWithTime(When, UserName + ": " + newcomment);
  }

  // Do a beep
  if ( BeepBtn->Down )
    MessageBeep(0xFFFFFFFF);

  // Hmm, if this message has been received from the remote user
  // _and_ we're away, _and_ it's not a notice send them an away notice
  if ( remoteUserName == UserName && AwayMessageDlg->IsAway() && !(Flags1 & BLAKEMESSAGE_FLAGS1_NOTICE) )
    AwayMessage();

  // If the message is in the background, make it flash
  if ( !Active )
    Flash(true);
}
//---------------------------------------------------------------------------
void TMsgForm::AddWithTime(
  const time_t When,
  const AnsiString &Message
)
{
  AnsiString newStr("");

  if ( Options.GetOptionBool(Oberchatten::oMsgWinTimestamps) ) {
    char buff[3];
    struct tm* local_time;
    local_time = localtime(&When);
    newStr = "[";
    newStr = newStr + PaddedNumber(buff, local_time->tm_hour) + ":" + PaddedNumber(buff, local_time->tm_min) + ":" + PaddedNumber(buff, local_time->tm_sec);
    newStr = newStr + "] ";
  }

  newStr = newStr + Message;
  ConversationMemo->Lines->Add(newStr);
  Log(newStr);
}
//---------------------------------------------------------------------------
void TMsgForm::AddWithTime(
  const time_t When,
  const char *Message
)
{
  AnsiString msg(Message);
  this->AddWithTime(When, msg);
  return;
}
//---------------------------------------------------------------------------
void TMsgForm::Add(
  const char *Message
)
{
  time_t t;

  time(&t);
  this->AddWithTime(t, Message);
  return;
}
//---------------------------------------------------------------------------
void __fastcall TMsgForm::MessageEditChange(TObject *Sender)
{
  MsgBtn->Enabled = !MessageEdit->Lines->Text.IsEmpty(); // Determine if user may send messages
  SetTag(Sender); // Mark memo as changed
}
//---------------------------------------------------------------------------
void __fastcall TMsgForm::KillBtnClick(TObject *Sender)
{
  blake_Kill(
    GlobalNetBuffer.GetSocket(),
    remoteUserName.c_str(),
    NULL /* Don't send a sneer */
  );
}
//---------------------------------------------------------------------------
bool TMsgForm::BeepOnMessage(const bool* NewSetting)
{
  bool oldSetting = BeepBtn->Down;
  if ( NewSetting )
    BeepBtn->Down = *NewSetting;
  return oldSetting;
}
//---------------------------------------------------------------------------
void __fastcall TMsgForm::FormCreate(TObject *Sender)
{
  this->BeepBtn->Down = Options.GetOptionBool(Oberchatten::oMsgWinBeep);
  this->GrabColors();
}
//---------------------------------------------------------------------------
void TMsgForm::WobbleWindow()
{
  if ( !Options.GetOptionBool(Oberchatten::oMsgWinIgnoreWobbles) ) { // Not ignoring wobbles?
    Sounds.Play(bell);
    for ( int i = 0; i < 5; i++ ) {
      int j;
      for ( j = 0; j < 6; j++ ) {
        Left -= 2;
        Application->ProcessMessages();
      }
      for ( j = 0; j < 12; j++ ) {
        Left += 2;
        Application->ProcessMessages();
      }
      for ( j = 0; j < 6; j++ ) {
        Left -= 2;
        Application->ProcessMessages();
      }
    }
  }
}
//---------------------------------------------------------------------------
void __fastcall TMsgForm::FormActivate(TObject *Sender)
{
  Flash(false);
}
//---------------------------------------------------------------------------
void TMsgForm::Flash(bool NewFlashMode)
{
  if ( NewFlashMode != flashMode ) {
    flashMode = NewFlashMode;
    if ( flashMode ) {
      FlashWindow(Handle, true);
      FlashTimer->Enabled = true;
    }
    else {
      FlashTimer->Enabled = false;
      FlashWindow(Handle, false);
    }
  }
  return;
}
//---------------------------------------------------------------------------
void __fastcall TMsgForm::FlashTimerTimer(TObject *Sender)
{
  FlashWindow(Handle, !flashCurrentState); // Reverse flash state
}
//---------------------------------------------------------------------------
void TMsgForm::Version()
{
  AnsiString verStr; // String for cobbling version together in
  enum blakeCipherID cipher_id;

#if 0
  OSVERSIONINFOEX osvi;

  ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
  osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);

  if( !(bOsVersionInfoEx = GetVersionEx ((OSVERSIONINFO *) &osvi)) ) {
    // If OSVERSIONINFOEX doesn't work, try OSVERSIONINFO.
    osvi.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
    if (! GetVersionEx ( (OSVERSIONINFO *) &osvi) )
      return FALSE;
  }
#endif /*0*/

  verStr = "Good morning!  I am Oberchatten " +
    (AnsiString)OBERCHATTEN_VERMAJ +
    "." +
    (AnsiString)OBERCHATTEN_VERMIN +
    "." +
    (AnsiString)OBERCHATTEN_VERPATCH +
    " (Restronguet)";

  cipher_id = Encipher(verStr); // Encipher the version string
  blake_Msg(
    GlobalNetBuffer.GetSocket(),
    remoteUserName.c_str(),
    verStr.c_str(),
    cipher_id,
    BLAKEMESSAGE_FLAGS1_NOTICE
  );
}
//---------------------------------------------------------------------------
void TMsgForm::AwayMessage()
{
  AnsiString msg;
  enum blakeCipherID cipher_id;

  if ( !printingAwayMsg ) {
    printingAwayMsg = true;
    AwayMessageDlg->GetAwayMessage(msg);
    cipher_id = Encipher(msg); // Encipher the away message
    // Send the notice and then add it to the conversation
    blake_Msg(
      GlobalNetBuffer.GetSocket(),
      remoteUserName.c_str(),
      msg.c_str(),
      cipher_id,
      BLAKEMESSAGE_FLAGS1_NOTICE
    );
    AddToConversation(
      time(NULL),
      MainForm->MyUser.GetUserName(),
      msg.c_str(),
      cipher_id,
      BLAKEMESSAGE_FLAGS1_NOTICE
    );
    printingAwayMsg = false;
  }
}
//---------------------------------------------------------------------------
void __fastcall TMsgForm::CipherChange(TObject *Sender)
{
  TMenuItem* menuitem;

  menuitem = dynamic_cast<TMenuItem*>(Sender);
  if ( menuitem ) {
    menuitem->Checked = true;
    MnuCryptoSetKey->Enabled = (bool)menuitem->Tag; // The tag specifies whether a key should bet set
  }
}
//---------------------------------------------------------------------------
void __fastcall TMsgForm::MnuCryptoSetKeyClick(TObject *Sender)
{
  TSetKeyForm* setKeyForm = new TSetKeyForm(this);

  if ( setKeyForm ) {
    setKeyForm->SetPassphrase(keyphrase); // Set phrase
    if ( setKeyForm->ShowModal() == mrOk ) { // If user has changed...
      keyphrase = setKeyForm->GetPassphrase(); // Get phrase back
    }
  }

  delete setKeyForm;
}
//---------------------------------------------------------------------------
void TMsgForm::WipeKeyPhrase()
{
  int i, l = keyphrase.Length();
  for ( i = 0; i < l; i++ )
    keyphrase.c_str()[i] = '#'; // Range errors keep tripping me out, there is nowt wrong with this so use C pointer to avoid >=)

  keyphrase = "";
  return;
}
//---------------------------------------------------------------------------
void __fastcall TMsgForm::PopupMenu1Popup(TObject *Sender)
{
  TMemo* memo;
  TPopupMenu* popupmenu;

  popupmenu = dynamic_cast<TPopupMenu*>(Sender);
  if ( !popupmenu ) return;

  // Deal with all the clipboard commands here.
  memo = dynamic_cast<TMemo*>(popupmenu->PopupComponent);
  if ( memo ) { // Control is really a memo?
    EnableClipboard(false); // Reset all commands to disabled
    EnableClipboard(); // Enable clipboard commands
    if ( !memo->ReadOnly ) { /* Read write mode? */
      MnuClipUndo->Enabled = static_cast<bool>(memo->Tag); // Only enable undo if an action has occurred
      // Cut & paste menu items can be enabled as long as there is selected text...
      if ( memo->SelLength ) {
        MnuClipCut->Enabled = true;
        MnuClipDelete->Enabled = true;
      }
      // Paste can only be on if there is stuff on the clipboard
      if ( ClipboardHasText() )
        MnuClipPaste->Enabled = true;
    }
    // Work out select all, only enable if there is unselected text, copy can be on if there is any selected text
    if ( !memo->Text.IsEmpty() ) { // Must have text
      if ( memo->SelLength < memo->Text.Length() ) // Not all selected?
        MnuClipSelectAll->Enabled = true;

      if ( memo->SelLength )
        MnuClipCopy->Enabled = true;
    }
  }
  else
    EnableClipboard(false); // Clipboard commands disabled for non-memos
}
//---------------------------------------------------------------------------
void TMsgForm::EnableClipboard(bool Yes)
{
  clipboardAllowed = Yes;
  if ( !Yes ) {
    MnuClipUndo->Enabled = Yes;
    MnuClipCut->Enabled = Yes;
    MnuClipCopy->Enabled = Yes;
    MnuClipPaste->Enabled = Yes;
    MnuClipDelete->Enabled = Yes;
    MnuClipSelectAll->Enabled = Yes;
  }
}
//---------------------------------------------------------------------------
void __fastcall TMsgForm::MnuClipUndoClick(TObject *Sender)
{
  if ( Sender ) {
    TMemo* memo = dynamic_cast<TMemo*>(ActiveControl);
    if ( memo ) {
      memo->Undo();
      SetTag(Sender); // Has been modified
    }
  }
}
//---------------------------------------------------------------------------
void __fastcall TMsgForm::MnuClipCutClick(TObject *Sender)
{
  if ( Sender ) {
    TMemo* memo = dynamic_cast<TMemo*>(ActiveControl);
    if ( memo ) {
      memo->CutToClipboard();
      SetTag(Sender); // Has been modified
    }
  }
}
//---------------------------------------------------------------------------
void __fastcall TMsgForm::MnuClipCopyClick(TObject *Sender)
{
  if ( Sender ) {
    TMemo* memo = dynamic_cast<TMemo*>(ActiveControl);
    if ( memo ) {
      memo->CopyToClipboard();
      SetTag(Sender); // Has been modified
    }
  }
}
//---------------------------------------------------------------------------
void __fastcall TMsgForm::MnuClipPasteClick(TObject *Sender)
{
  if ( Sender ) {
    TMemo* memo = dynamic_cast<TMemo*>(ActiveControl);
    if ( memo ) {
      memo->PasteFromClipboard();
      SetTag(Sender); // Has been modified
    }
  }
}
//---------------------------------------------------------------------------
void __fastcall TMsgForm::MnuClipDeleteClick(TObject *Sender)
{
  if ( Sender ) {
    TMemo* memo = dynamic_cast<TMemo*>(ActiveControl);
    if ( memo ) {
      memo->ClearSelection();
      SetTag(Sender); // Has been modified
    }
  }
}
//---------------------------------------------------------------------------
void __fastcall TMsgForm::MnuClipSelectAllClick(TObject *Sender)
{
  if ( Sender ) {
    TMemo* memo = dynamic_cast<TMemo*>(ActiveControl);
    if ( memo ) {
      memo->SelectAll();
      SetTag(Sender); // Has been modified
    }
  }
}
//---------------------------------------------------------------------------
void __fastcall TMsgForm::SetTag(TObject* Sender)
{
  if ( Sender ) {
    TComponent* component = dynamic_cast<TComponent*>(Sender);
    if ( component ) {
      if ( !component->Tag ) component->Tag = 1;
    }
  }
}
//---------------------------------------------------------------------------
void __fastcall TMsgForm::ConversationMemoChange(TObject *Sender)
{
  SetTag(Sender); // Mark memo as changed
}
//---------------------------------------------------------------------------
void __fastcall TMsgForm::FormDestroy(TObject *Sender)
{
  this->WipeKeyPhrase(); // Securely get rid of password for the conversation
}
//---------------------------------------------------------------------------
enum blakeCipherID TMsgForm::Encipher(AnsiString& Message)
{
  if ( MnuCryptoCaesar->Checked ) {
    daybocrypt_CaesarCipher(ccmEncipher, Message.c_str(), daybocrypt_CaesarKeyGen(keyphrase.c_str()));
    return bcidCaesar;
  }
  return bcidPlain;
}
//---------------------------------------------------------------------------
enum blakeCipherID TMsgForm::Decipher(AnsiString& Message)
{
  if ( MnuCryptoCaesar->Checked ) {
    daybocrypt_CaesarCipher(ccmDecipher, Message.c_str(), daybocrypt_CaesarKeyGen(keyphrase.c_str()));
    return bcidCaesar;
  }
  return bcidPlain;
}
//---------------------------------------------------------------------------
void __fastcall TMsgForm::MnuWobbleClick(TObject *Sender)
{
    // One day this will use a dedicated packet rather than messing with the user message (FIXME)
  MessageEdit->Text = "/wobblewindow";
  MsgBtnClick(NULL);
}
//---------------------------------------------------------------------------
void __fastcall TMsgForm::MnuLeetSpeakClick(TObject *Sender)
{
  MnuLeetSpeak->Checked = !MnuLeetSpeak->Checked;
}
//---------------------------------------------------------------------------
char* TMsgForm::PaddedNumber(char buffer[3], const int Number)
{
  char anotherBuffer[3];
  memset(buffer, 0, sizeof(buffer));
  memset(anotherBuffer, 0, sizeof(anotherBuffer));

  if ( Number < 10 ) {
    buffer[0] = '0';
    buffer[1] = '\0';
  }
  itoa(Number, anotherBuffer, 10);
  strncat(buffer, anotherBuffer, 2);
  return buffer;
}
//---------------------------------------------------------------------------
bool TMsgForm::Log(AnsiString& Message)
{
  int i;
  FILE* handle;
  char *normLocalUser, *normRemoteUser;
  size_t normLocalBuffSz, normRemoteBuffSz;
  bool ret = false;
  enum blakeError err = blakeSuccess;
  AnsiString appPath(Application->ExeName);

  // Strip the filename from the base path of the app
  i = appPath.Length();
  while ( --i ) {
    if ( appPath.IsPathDelimiter(i) ) {
      appPath.SetLength(i); // Terminate after last path delimiter
      break;
    }
  }

  // Add the directory name for logs
  appPath += (AnsiString)("logs\\");

  // Add the username (local and then remote)
  normLocalBuffSz = MainForm->MyUser.GetUserName().Length()+1;
  normLocalUser = new char[normLocalBuffSz];
  if ( normLocalUser ) {
    normRemoteBuffSz = remoteUserName.Length()+1;
    normRemoteUser = new char[normRemoteBuffSz];
    if ( normRemoteUser ) {
      err = blake_NormNick(remoteUserName.c_str(), normRemoteUser, normRemoteBuffSz);
      if ( err == blakeSuccess ) {
        err = blake_NormNick(MainForm->MyUser.GetUserName().c_str(), normLocalUser, normLocalBuffSz);
        if ( err == blakeSuccess ) {
          mkdir(appPath.c_str()); // Make logs dir
          appPath += normLocalUser;
          mkdir(appPath.c_str()); // Make dir for this name
          appPath += (AnsiString)("\\") + normRemoteUser + ".log"; // Complete path with remote user's name

          // Now append to log
          handle = fopen(appPath.c_str(), "at");
          if ( handle ) {
            fprintf(handle, "%s\n", Message.c_str());
            fclose(handle);
            ret = true;
          }
        }
      }
      delete[] normRemoteUser;
    }
    delete[] normLocalUser;
  }

  if ( err != blakeSuccess )
    MainForm->BlakeError(__FILE__, __LINE__, err);

  if ( !ret )
    InfoBox(MainForm, "Error writing logs", Application->Title.c_str(), MB_ICONSTOP | MB_OK, INFOBOX_NOHELP);

  return ret;
}
//---------------------------------------------------------------------------
void __fastcall TMsgForm::MessageEditKeyDown(TObject *Sender, WORD &Key,
      TShiftState Shift)
{
  // 38 is up, 40 is down
  if ( Key == 38 ) { // Going back into history?
    MessageEdit->Text = history.PreviousCompat();
  }
  else if ( Key == 40 ) { // Going forward into the future
    MessageEdit->Text = history.NextCompat();
  }
}
//---------------------------------------------------------------------------
void TMsgForm::GrabColors()
{
  this->ConversationMemo->Color = MainForm->OnlineChumsListBox->Color;
  this->MessageEdit->Color = MainForm->ChumsListBox->Color;
  this->CommandPanel->Color = MainForm->ToolPanel->Color;
}
//---------------------------------------------------------------------------