-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunterm.c
More file actions
1589 lines (1408 loc) · 45.5 KB
/
funterm.c
File metadata and controls
1589 lines (1408 loc) · 45.5 KB
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
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/***************************************************************************
* Copyright (C) 2008 by Blake Leverett *
* bleverett@gmail.com
* *
* FUNterm is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, see <http://www.gnu.org/licenses/>. *
***************************************************************************/
/*
CVS info:
$Id: funterm.c,v 1.11 2010/04/01 15:19:45 blakelev Exp $
$Revision: 1.11 $
$Date: 2010/04/01 15:19:45 $
*/
#include "funterm.h"
#include <windowsx.h>
#include <commctrl.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include "funtermres.h"
#include "serial.h"
/** @file
This file is the main module of the project. It contains the code
for the user interface and handling the strings that get displayed,
and every major function of the program.
@mainpage FUNterm
@section intro Introduction
This program is a basic terminal program, written for Windows, that communicates
with remote devices over a serial port.
Though this is a Win32 program, it was developed under GNU/Linux using the MinGW
compiler and run with Wine. As it only uses basic Win32 calls, with no high-level
libraries, it runs stably under Wine.
Also, the serial.c file contains a working Win32 serial port interface, which may
be used in any application that requires serial interface with Windows.
@section compiling Compiling
If you have MinGW loaded, the included Makefile should work. If you are compiling from
Windows, you may need to modify the makefile to work with Windows path conventions.
@section features Features
- Supports 128 COM ports.
- Supports escape sequences. All escape sequences start with the escape character, 0x1B.
- <b><ESC> T</b> - Clear to end of line.
- <b><ESC> Y</b> - Clear to end of screen.
- <b><ESC> . <i>x</i></b> - Turn cursor on/off. If <i>x</i> == '0', cursor is off.
Otherwise, cursor is turned on.
- <b><ESC> = <i>row col</i></b> - Set cursor position to <i>row, col</i>. Parameters
are biased by 0x20 (space character). For example, to set the column to 40,
<i>col</i> would be 0x20 + 40 = 32 + 40 = 72 = 0x48 = 'H'.
- Supports control-character commands. Note that these are characters received over the
serial port, not entered via the keyboard.
- <b>Control-X</b> - Move to home position.
- <b>Control-Z</b> - Clear screen and home.
@section reg Registry Usage
The registry is used so store program settings. Settings are stored in
HKEY_CURRENT_USER\\Software\\FUNterm. These parameters are saved:
- Comm Port
- Baud rate.
- OpenOnStart. If true the comport is opened on startup.
- Hardware flow control setting.
@defgroup term Terminal
@{
See Main Page for features. This file implements all of the terminal functions, except
for serial connectivity.
*/
// Defines:
#define Margin 5 ///< Margin in pixels between edge of main control's edge and text.
#define FIXED_CONFIG_1 0 ///< Special build flag to create a fixed config version, should be zero for most users
// Enumerations:
/// State variable for processing escape codes (VT100).
enum TEscProg {
Idle=-1, ///< Not processing escape sequence yet.
Ready, ///< Got the Escape character, waiting for command.
CursorOnOff, ///< Waiting for cursor on/off parameter character.
CursPosX, ///< Waiting for cursor X position.
CursPosY ///< Waiting for cursor Y position.
} EscProg=Idle;
/// Current state of serial port, used for updating the status bar.
enum TStatus {
stOff, ///< Serial port is off.
stError, ///< Serial port cannot be opened.
stRunning, ///< Serial port opened successfully.
stResize ///< Status bar is being resized.
};
// Functions:
void OnConfigComm(HWND wnd);
void DrawLEDs(DRAWITEMSTRUCT *dis);
void FillInStatus(int Status);
void CenterWindow(HWND wnd);
void CopyToClipboard(HWND wnd);
void PasteFromClipboard(HWND wnd);
void ShowMenu(HWND wnd);
void DrawChar(int x,int y,char ch);
void SetMinMaxInfo(MINMAXINFO *p);
void ClearScreen(void);
void SendFile(void);
void SaveFile(void);
void StartLog(void);
void EndLog(void);
void AddBinaryChar(char ch);
LRESULT CALLBACK BinWndProc(HWND hwnd,UINT msg,WPARAM wParam,LPARAM lParam);
// Variables:
HINSTANCE hInst; ///< Handle to this instance of the program.
HWND hwndMain; ///< Handle to the main window of the program.
HWND hwndBin; ///< Handle to the binary view window.
HWND hwndBinEdit; ///< Handle to the edit control in the bin view window.
TLines *Lines=NULL; ///< Pointer to the global TLines structure.
int TopLine=0; ///< Index of first line on screen.
int ScrnLineCount=1; ///< Number of lines on the screen.
TRegContents RegContents; ///< Global registry stuff.
/// Supported baud rates (in BPS).
int BaudRates[8] = {9600,19200,38400,57600,115200,230400,460800,921600};
char FileName[300]; ///< Filename string used anywhere a filename is needed.
HMENU PopupMenu=NULL; ///< Pointer to popup menu.
int CharWd=5,CharHt=5; /**< Size of a single character in pixels.
This is determined by calling GetTextExtentPoint32()
on an 'A'. */
int LineLength=80; ///< Current width of window in characters.
HFONT font; ///< Font used for drawing characters.
FILE *LogFile=0; ///< File pointer to the Logging file.
HWND hWndStatusbar; ///< Windows handle to the Status Bar
BOOL RxFlag=FALSE; ///< Flag used to signal the Rx "LED" to flash
BOOL TxFlag=FALSE; ///< Flag used to signal the Tx "LED" to flash
/**
Updates the statusbar control with the input text.
@param lpszStatusString Charactar string to be displayed.
@param partNumber Index of the status bar part number to be
used for display.
@param displayFlags Value passed to the statusbar. See the SB_SETTEXT
win32 message for details.
*/
void UpdateStatusBar(LPSTR lpszStatusString, WORD partNumber, WORD displayFlags)
{
SendMessage(hWndStatusbar,
SB_SETTEXT,
partNumber | displayFlags,
(LPARAM)lpszStatusString);
}
/**
Initializes the status bar.
@param hwndParent Handle to the parent window.
@param nrOfParts The status bar can contain more than one
pane, and this parameter specifies how many panes the status
bar will have.
*/
void InitializeStatusBar(HWND hwndParent,int nrOfParts)
{
const int cSpaceInBetween = 8;
int ptArray[6]; // Array defining the number of parts/sections
RECT rect;
HDC hDC;
/* Fill in the ptArray... */
hDC = GetDC(hwndParent);
GetClientRect(hwndParent, &rect);
LineLength = (rect.right - rect.left)/CharWd;
ptArray[0] = 46;
ptArray[1] = 100;
ptArray[2] = 151;
ptArray[3] = 194;
ptArray[4] = 326;
ptArray[nrOfParts-1] = -1; // Last part extends to right side of window
ReleaseDC(hwndParent, hDC);
SendMessage(hWndStatusbar,
SB_SETPARTS,
nrOfParts,
(LPARAM)(LPINT)ptArray);
}
/**
Calls CreateStatusWindow to create the status bar.
@param hwndParent Handle to the parent window that owns the new status bar.
@param initialText The initial contents of the status bar.
@param nrOfParts The number of panes in the status bar.
@return TRUE on success, or FALSE on failure.
*/
static BOOL CreateSBar(HWND hwndParent,char *initialText,int nrOfParts)
{
hWndStatusbar = CreateStatusWindow(WS_CHILD | WS_VISIBLE | WS_BORDER|SBARS_SIZEGRIP,
initialText,
hwndParent,
IDM_STATUSBAR);
if (hWndStatusbar)
{
InitializeStatusBar(hwndParent,nrOfParts);
return TRUE;
}
return FALSE;
}
/**
Initializes the application. This is the first function called from WinMain.
@return TRUE on success, or FALSE on failure.
*/
static BOOL InitApplication(void)
{
WNDCLASSEX wc;
memset(&wc,0,sizeof(WNDCLASSEX));
wc.cbSize = sizeof(WNDCLASSEX);
/// Sets main window with parameters CS_HREDRAW|CS_VREDRAW|CS_DBLCLKS
wc.style = CS_HREDRAW|CS_VREDRAW |CS_DBLCLKS;
wc.lpfnWndProc = (WNDPROC)MainWndProc;
wc.hInstance = hInst;
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
/// Main window has class name "funtermWndClass"
wc.lpszClassName = "funtermWndClass";
wc.lpszMenuName = MAKEINTRESOURCE(IDMAINMENU);
wc.hCursor = LoadCursor(NULL,IDC_ARROW);
wc.hIcon = LoadIcon(hInst,MAKEINTRESOURCE(IDAPPLICON));
if (!RegisterClassEx(&wc))
return 0;
/// Binary window has class name "binWndClass"
wc.lpszClassName = "binWndClass";
wc.lpszMenuName = NULL;
wc.hCursor = LoadCursor(NULL,IDC_ARROW);
wc.hIcon = 0;//LoadIcon(hInst,MAKEINTRESOURCE(IDAPPLICON));
wc.lpfnWndProc = (WNDPROC)BinWndProc;
if (!RegisterClassEx(&wc))
return 0;
return 1;
}
/**
Creates the Window Class for application.
@return Handle to main window created.
*/
HWND CreatefuntermWndClassWnd(void)
{
/** Window parameters include WS_MINIMIZEBOX, WS_VISIBLE, WS_CLIPSIBLINGS,
WS_CLIPCHILDREN, WS_MAXIMIZEBOX, WS_CAPTION, WS_BORDER, WS_SYSMENU,
and WS_THICKFRAME.
*/
return CreateWindowEx(0,"funtermWndClass","FUNterm",
WS_MINIMIZEBOX|WS_VISIBLE|WS_CLIPSIBLINGS|WS_CLIPCHILDREN|WS_MAXIMIZEBOX|WS_CAPTION|WS_BORDER|WS_SYSMENU|WS_THICKFRAME,
CW_USEDEFAULT,0,CW_USEDEFAULT,0,
NULL,
NULL,
hInst,
NULL);
}
/**
Win32 callback function for the config and help/about dialogs.
@param hwnd Handle to dialog box sending message.
@param msg Windows message to handle.
@param wParam First message parameter.
@param lParam Second message parameter.
@return Non-zero if message is processed, zero if not processed.
*/
BOOL _stdcall DlgWinProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch(msg)
{
case WM_CLOSE:
EndDialog(hwnd,0);
return 1;
case WM_COMMAND:
switch (LOWORD(wParam))
{
case IDOK:
OnConfigComm(hwnd);
case IDCANCEL:
EndDialog(hwnd,1);
return 1;
}
break;
case WM_INITDIALOG:
CenterWindow(hwnd);
if (lParam) // only for comm setup dlg.
{
InitCommDialog(hwnd);
return 1;
}
break;
}
return 0;
}
/**
Main windows command handler. See Win32 HANDLE_WM_COMMAND macro for details.
@param hwnd Handle to main window.
@param id Window message ID.
@param hwndCtl Handle to something.
@param codeNotify Code (unused).
*/
void MainWndProc_OnCommand(HWND hwnd, int id, HWND hwndCtl, UINT codeNotify)
{
switch(id)
{
case IDM_ABOUT:
DialogBox(hInst,MAKEINTRESOURCE(IDD_ABOUT),
hwndMain,DlgWinProc);
break;
case IDM_CONFIG:
DialogBoxParam(hInst,MAKEINTRESOURCE(IDD_CONFIG),
hwndMain,DlgWinProc,1);
break;
case IDM_STARTCOMM:
// start or stop serial port
if (SerialPortIsOpen()) // close it
{
CloseSerialPort();
FillInStatus(stOff);
}
else if (!OpenPort(RegContents.ComPort,
BaudRates[RegContents.Baud],
RegContents.HdwFlow,
hwndMain))
{
MessageBox(hwndMain,"Cannot open serial port!\n","Error",MB_OK|MB_ICONSTOP);
CloseSerialPort();
FillInStatus(stError);
}
else
FillInStatus(stRunning);
break;
case IDM_EXIT:
PostMessage(hwnd,WM_CLOSE,0,0);
break;
case IDM_COPY:
// copy contents to clipboard
CopyToClipboard(hwnd);
break;
case IDM_PASTE:
// paste from clipboard
PasteFromClipboard(hwnd);
break;
case IDM_CLEAR:
// clear screen
ClearScreen();
break;
case IDM_SEND:
// send file to port
SendFile();
break;
case IDM_CRLF:
// Toggle CR/LF usage
RegContents.CrLf = !RegContents.CrLf;
if (SerialPortIsOpen())
FillInStatus(stRunning);
break;
case IDM_LOG_START:
StartLog();
break;
case IDM_LOG_END:
EndLog();
break;
case IDM_SAVE:
// save screen data to file
SaveFile();
break;
case IDM_BINARY:
// Show binary in new window.
if (!hwndBin)
{
LOGFONT LogFont;
HFONT fnt;
hwndBin = CreateWindowEx(0,"binWndClass","Binary View",
WS_MINIMIZEBOX|WS_VISIBLE|WS_CLIPSIBLINGS|WS_CLIPCHILDREN|WS_MAXIMIZEBOX|WS_CAPTION|WS_BORDER|WS_SYSMENU|WS_THICKFRAME,
CW_USEDEFAULT,0,300,500,
NULL,
NULL,
hInst,
NULL);
hwndBinEdit = CreateWindowEx(0,"EDIT","",
WS_VISIBLE|WS_CHILD|ES_MULTILINE|ES_AUTOHSCROLL|ES_AUTOVSCROLL|WS_HSCROLL|WS_VSCROLL,
//CW_USEDEFAULT,0,CW_USEDEFAULT,0,
0, 0, 100, 100,
hwndBin,
NULL,
hInst,
NULL);
fnt = GetStockObject(ANSI_FIXED_FONT);
GetObject(fnt,sizeof(LOGFONT),&LogFont);
LogFont.lfHeight = LogFont.lfHeight * 4/3; //-MulDiv(10, GetDeviceCaps(DC, LOGPIXELSY), 72);
fnt = CreateFontIndirect(&LogFont);
SendMessage(hwndBinEdit, WM_SETFONT, (WPARAM)fnt, 0);
}
if (hwndBin)
ShowWindow(hwndBin,SW_SHOW);
break;
default:
break;
}
}
/**
The window procedure (callback) for the main window.
@param hwnd Handle to main window.
@param msg Windows message to handle.
@param wParam First message parameter.
@param lParam Second message parameter.
@return Depends on the specific message handled.
*/
LRESULT CALLBACK MainWndProc(HWND hwnd,UINT msg,WPARAM wParam,LPARAM lParam)
{
switch (msg)
{
case WM_SIZE:
SendMessage(hWndStatusbar,msg,wParam,lParam);
FillInStatus(stResize);
break;
case WM_GETMINMAXINFO:
// set minimum size of window
SetMinMaxInfo((MINMAXINFO*)lParam);
break;
case WM_COMMAND:
HANDLE_WM_COMMAND(hwnd,wParam,lParam,MainWndProc_OnCommand);
break;
case WM_CREATE:
Lines = CreateLines(4);
break;
case WM_DESTROY:
EndLog();
SaveReg();
// close serial port
CloseSerialPort();
DestroyLines(Lines);
DestroyMenu(PopupMenu);
PostQuitMessage(0);
break;
case WM_CHAR:
DoKey(hwnd,wParam);
break;
case WM_PAINT:
Paint(hwnd);
break;
/// This application includes a custom message type: MESS_SERIAL.
case MESS_SERIAL: // custom message: buf and count sent
{
int i;
for (i=0;i<wParam;i++)
{
AddChar(((char*)lParam)[i]);
RxFlag = TRUE; // signal LED to go on.
// send char to log file
if (LogFile)
fputc(((char*)lParam)[i],LogFile);
// Add to binary window
AddBinaryChar(((char*)lParam)[i]);
}
}
break;
case WM_DRAWITEM:
if (wParam == IDM_STATUSBAR)
DrawLEDs((DRAWITEMSTRUCT *)lParam);
break;
case WM_RBUTTONUP:
if (!wParam) // only do context menu if no other buttons/keys are down
ShowMenu(hwnd);
break;
default:
return DefWindowProc(hwnd,msg,wParam,lParam);
}
return 0;
}
/**
The window procedure (callback) for the binary window.
@param hwnd Handle to main window.
@param msg Windows message to handle.
@param wParam First message parameter.
@param lParam Second message parameter.
@return Depends on the specific message handled.
*/
LRESULT CALLBACK BinWndProc(HWND hwnd,UINT msg,WPARAM wParam,LPARAM lParam)
{
switch (msg)
{
case WM_SIZE:
MoveWindow(hwndBinEdit, 0, 0, LOWORD(lParam), HIWORD(lParam), 1);
break;
case WM_DESTROY:
// Destroy edit window
DestroyWindow(hwndBinEdit);
hwndBin = 0;
break;
default:
return DefWindowProc(hwnd,msg,wParam,lParam);
}
return 0;
}
/**
Sets a MINMAXINFO structure for the OS. Tells the OS the minimum size
for the main window, in response to a WM_GETMINMAXINFO message.
@param mmi Pointer to MINMAXINFO structure to be set.
*/
void SetMinMaxInfo(MINMAXINFO *mmi)
{
POINT P;
P.x = 325;
P.y = 150;
mmi->ptMinTrackSize = P;
}
/**
This is the main entry into the application. WinMain initializes everything,
and then executes a message loop until the application exits.
@param hInstance Handle to application instance.
@param hPrevInstance Always NULL.
@param lpCmdLine String containing the command line used to launch the application.
@param nCmdShow Specifies how the window is to be shown. See WinMain in the
Win32 help file.
@return Zero on error, nonzero otherwise.
*/
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPSTR lpCmdLine, INT nCmdShow)
{
MSG msg;
HANDLE hAccelTable;
HDC DC;
LOGFONT LogFont;
SIZE Size;
InitCommonControls();
hInst = hInstance;
if (!InitApplication())
return 0;
hAccelTable = LoadAccelerators(hInst,MAKEINTRESOURCE(IDACCEL));
if ((hwndMain = CreatefuntermWndClassWnd()) == (HWND)0)
return 0;
CreateSBar(hwndMain,"",2);
// Load popup menu from resource
PopupMenu = LoadMenu(hInst,MAKEINTRESOURCE(IDPOPUPMENU));
// read registry contents, config if no reg info found.
ReadReg();
// Open serial port, fill in status bar
if (RegContents.OpenOnStart && !OpenPort(RegContents.ComPort,
BaudRates[RegContents.Baud],
RegContents.HdwFlow,
hwndMain))
{
MessageBox(NULL,"Cannot open serial port!\n","Error",MB_OK|MB_ICONSTOP);
CloseSerialPort();
PostMessage(hwndMain,WM_COMMAND,IDM_CONFIG,0);
FillInStatus(stError);
}
else
{
if (SerialPortIsOpen())
FillInStatus(stRunning);
else
FillInStatus(stOff);
}
// draw LEDs
UpdateStatusBar(NULL, 0, SBT_OWNERDRAW);
// init char drawing stuff
DC = GetDC(hwndMain);
font = GetStockObject(ANSI_FIXED_FONT);
GetObject(font,sizeof(LOGFONT),&LogFont);
LogFont.lfHeight = LogFont.lfHeight * 4/3; //-MulDiv(10, GetDeviceCaps(DC, LOGPIXELSY), 72);
font = CreateFontIndirect(&LogFont);
SelectObject(DC,font);
GetTextExtentPoint32(DC,"A",1,&Size);
ReleaseDC(hwndMain,DC);
CharWd = Size.cx;
CharHt = Size.cy;
ShowWindow(hwndMain,SW_SHOW);
while (GetMessage(&msg,NULL,0,0))
{
if (!TranslateAccelerator(msg.hwnd,hAccelTable,&msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return msg.wParam;
}
/**
Adds a character to the terminal display. Called every time a character
is received from the serial port. This function implements escape sequences.
See the main page for a description of escape sequences supported.
@param ch The character to add to the display.
*/
void AddChar(char ch)
{
unsigned int x;
if (EscProg != Idle) // We're parsing escape sequence
{
switch (EscProg)
{
case Ready:
switch (toupper(ch))
{
case 'T':
// Clear to EOL
Lines->Lines[Lines->CursY][Lines->CursX] = 0;
EscProg = Idle;
return;
case 'Y':
// Clear to EOF
Lines->Lines[Lines->CursY][Lines->CursX] = 0;
for(x=Lines->CursY;x<Lines->Count;x++)
Lines->Lines[x][0] = 0;
EscProg = Idle;
return;
case '.':
EscProg = CursorOnOff;
return;
case '=':
EscProg = CursPosX;
return;
default:
EscProg = Idle; // kill the command sequence.
return;
}
case (CursorOnOff):
if (ch == '0')
Lines->Cursor = FALSE;
else
{
Lines->Cursor = TRUE;
InvalidateRect(hwndMain,NULL,FALSE);
}
EscProg = Idle;
return;
case (CursPosX):
SetCursY(Lines,ch - 0x20);
EscProg = CursPosY;
return;
case (CursPosY):
SetCursX(Lines,ch - 0x20);
EscProg = Idle;
return;
default:
EscProg = Idle; // kill the command sequence.
return;
}
}
switch (ch)
{
case (-1):
return;
case (0x1e):
case (0x18):
// Home position (??)
SetCursX(Lines,0);
SetCursY(Lines,0);
break;
case (0x1a): // Control-z
case 12: // Form-feed (cntrl-l)
// Clear Screen and home (cntrl-z)
ClearScreen();
break;
case (0x1b):
// Start escape sequence
EscProg = Ready;
break;
case 13:
SetCursX(Lines,0);
break;
case 10:
if (RegContents.CrLf)
// implied CR
SetCursX(Lines,0);
SetCursY(Lines,Lines->CursY+1);
break;
case 8: // backspace
SetCursX(Lines,Lines->CursX - 1);
break;
case 9: // tab
// Must add 8 spaces for tab
for (x=0;x<8;x++)
AddChar(' ');
SetCursX(Lines,(Lines->CursX + 8) % 8);
break;
default:
// check for word wrap
if (Lines->CursX >= LineLength -1)
{
// fake cr/lf
SetCursX(Lines,0);
SetCursY(Lines,Lines->CursY+1);
}
DrawChar(Lines->CursX,Lines->CursY,ch);
PushChar(Lines,ch);
break;
}
}
/**
Initializes the comm settings dialog. Called before displaying the dialog.
@param wnd Handle to dialog window.
*/
void InitCommDialog(HWND wnd)
{
HWND Control;
int i;
char str[40];
// init com port listbox
Control = GetDlgItem(wnd, ID_COMPORT);
for (i=0;i<128;i++)
{
sprintf(str,"COM%d",i+1);
SendMessage(Control,LB_ADDSTRING, 0, (long)str);
}
SendMessage(Control,LB_SETCURSEL, RegContents.ComPort-1, 0);
// init baud rate button
Control = GetDlgItem(wnd,ID_BAUD+RegContents.Baud);
SendMessage(Control,BM_SETCHECK,BST_CHECKED,0);
// init auto-open button
Control = GetDlgItem(wnd,ID_CBOPEN);
SendMessage(Control,BM_SETCHECK,RegContents.OpenOnStart ? BST_CHECKED : BST_UNCHECKED,0);
// init flow control button
Control = GetDlgItem(wnd,ID_CBFLOW);
SendMessage(Control,BM_SETCHECK,RegContents.HdwFlow ? BST_CHECKED : BST_UNCHECKED,0);
}
/**
Execute comport parameter settings. Called after user presses "OK" in the
comm config dialog.
@param wnd Handle to dialog window.
*/
void OnConfigComm(HWND wnd)
{
// get stuff from dialogs
HWND Control;
int i;
/// Closes and re-opens serial port if it is already open.
CloseSerialPort();
// get com port number
Control = GetDlgItem(wnd,ID_COMPORT);
RegContents.ComPort = SendMessage(Control, LB_GETCURSEL, 0, 0) + 1;
// read baud rate button
for (i=0;i<8;i++)
{
Control = GetDlgItem(wnd,ID_BAUD+i);
if (SendMessage(Control,BM_GETCHECK,0,0) == BST_CHECKED)
break;
}
RegContents.Baud = i;
/// Saves config settings to registry.
// auto-open button
Control = GetDlgItem(wnd,ID_CBOPEN);
RegContents.OpenOnStart = SendMessage(Control,BM_GETCHECK,0,0);
// init flow control button
Control = GetDlgItem(wnd,ID_CBFLOW);
RegContents.HdwFlow = SendMessage(Control,BM_GETCHECK,0,0);
/// Opens the serial port with the new settings.
PostMessage(hwndMain,WM_COMMAND,IDM_STARTCOMM,0);
}
/**
Paints the main window's terminal control area. Updates the status bar
if necessary. If the window is minimized, the painting is suspended to save
CPU time. The cursor is also drawn by this function. This function is called
in response to a WM_PAINT message.
@param wnd Handle to dialog window.
*/
void Paint(HWND wnd)
{
PAINTSTRUCT ps;
RECT R,T;
HBITMAP Bmp; // off-screen bitmap
HDC DC;
SIZE Size;
int i;
// tell statusbar to redraw if nec.
if (RxFlag || TxFlag)
UpdateStatusBar(NULL, 0, SBT_OWNERDRAW);
if (IsIconic(wnd))
{
// must do begin/end paint or WM_PAINTs will be
// continuously sent while window is minimized.
BeginPaint(wnd,&ps);
EndPaint(wnd,&ps);
// force the lines to scroll off screen if nec. (on resize shorter)
SetCursY(Lines,Lines->CursY);
return; // don't draw on minimized window
}
BeginPaint(wnd,&ps);
/** Painting is done by first drawing the screen to an off-screen bitmap, and
then copying the bitmap to the terminal control with a BitBlt() command.
Without this copying, the program flashes horribly.
*/
// draw to off-screen bitmap
GetClientRect(wnd,&R);
Bmp = CreateCompatibleBitmap(ps.hdc,R.right,R.bottom);
DC = CreateCompatibleDC(ps.hdc);
SelectObject(DC,Bmp);
SelectObject(DC,font);
// clear bitmap
FillRect(DC,&R,GetStockObject(WHITE_BRUSH));
// draw border around term window.
GetWindowRect(hWndStatusbar,&T);
ScreenToClient(wnd,(POINT *)&T);
R.bottom = T.top;
DrawEdge(DC,&R,EDGE_SUNKEN,BF_RECT);
// draw lines
if (Lines->CursX)
GetTextExtentPoint32(DC,Lines->Lines[Lines->CursY],Lines->CursX,&Size);
else
{GetTextExtentPoint32(DC,"ABC",3,&Size);
Size.cx = 0;
}
if (Size.cy)
ScrnLineCount = R.bottom/Size.cy; // number of lines on screen
for(i=TopLine;i<Lines->Count;i++)
TextOut(DC,Margin,Margin+(i-TopLine)*Size.cy,Lines->Lines[i],strlen(Lines->Lines[i]));
// draw cursor
if (Lines->Cursor)
{
int y; // y dim.
int x; // x dim of cursor
y = (Lines->CursY - TopLine + 1) * Size.cy + Margin - 2;
x = Size.cx + Margin;
MoveToEx(DC,x,y,NULL);
LineTo(DC,x+CharWd,y);
}
// draw bitmap to screen
BitBlt(ps.hdc,0,0,R.right,R.bottom,DC,0,0,SRCCOPY);
DeleteDC(DC);
DeleteObject(Bmp);
EndPaint(wnd,&ps);
// force the lines to scroll off screen if nec. (on resize shorter)
SetCursY(Lines,Lines->CursY);
}
/**
Creates and initializes a TLines structure. Includes the allocation of space for
the array of strings to be displayed.
@param Count Number of lines to be allocated.
@return Pointer to new TLines structure.
*/
TLines *CreateLines(int Count)
{
int i;
// create the struct.
TLines *Lines = malloc(sizeof(TLines));
memset(Lines,0,sizeof(TLines));
Lines->Count = 0;
Lines->Capacity = Count;
Lines->Cursor = TRUE;
// allocate ptr space
Lines->Lines = malloc(Count*sizeof(void*));
Lines->LineLen = malloc(Count*sizeof(int *));
// allocate string space
for (i=0;i<Count;i++)
{
Lines->Lines[i] = malloc(8);
Lines->Lines[i][0] = 0; // asciiz terminate
Lines->LineLen[i] = 8;
}
return Lines;
}
/**
De-allocates TLines structure. Also de-allocates the lines of text allocated
by CreateLines().
@param Lines Pointer to TLines structure to destroy.
*/
void DestroyLines(TLines *Lines)
{
int i;
// free strings
for (i=0;i<Lines->Capacity;i++)
free(Lines->Lines[i]);
// free pointers
free(Lines->Lines);
free(Lines->LineLen);
}
/**
Sets the current cursor's column position. Manages the TLines structure
to move the cursor.
@param Lines Pointer to TLines structure.
@param x New column position, zero-based.
*/
void SetCursX(TLines *Lines,int x)
{
int y = Lines->CursY;
char *p = Lines->Lines[y];
int z;
if (x < 0) return;
if (x > 300) return;
// expand line if nec.
if (x+1 >= Lines->LineLen[y])
{
p = realloc(p,x+10);
Lines->Lines[y] = p;
Lines->LineLen[y] = x+10;
}
// add spaces if nec.
z = strlen(p);
while (z < x)
{
p[z++] = ' ';
p[z] = 0;
}
// redraw if cursor is visible and has moved.
if ((x != Lines->CursX) && Lines->Cursor)
InvalidateRect(hwndMain,NULL,FALSE);
Lines->CursX = x;
}
/**
Sets the current cursor's row position. Manages the TLines structure
to move the cursor. Allocates and de-allocates lines as necessary.
@param Lines Pointer to TLines structure.
@param y New column position, zero-based.
*/
void SetCursY(TLines *Lines,int y)
{
int NewCap,i;
if (y > 300) return;
if (y < 0) return;
if (y >= Lines->Capacity)
{
// must re-alloc Line list