-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtcer.cpp
More file actions
1174 lines (1078 loc) · 39.8 KB
/
tcer.cpp
File metadata and controls
1174 lines (1078 loc) · 39.8 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
// tcer.cpp : Defines the entry point for the application.
//
#include "stdafx.h"
#include "tcer.h"
#include "WindowFinder.h"
#include <commctrl.h>
// Path to system directory
WCHAR DllPath[MAX_PATH];
size_t DllPathLen;
// Strips the Full View data: size, date, time, attributes
void strip_file_data(WCHAR* elem)
{
const WCHAR bad_chars[] = L"<>:|*\"";
size_t pos = cf_wcscspn(elem, bad_chars);
// Full path, colon at the second position => searching for the next bad character
if (pos == 1)
pos = 2 + cf_wcscspn(elem + 2, bad_chars);
// Not found
if (elem[pos] == L'\0')
return;
// Custom columns (separated from file name by space and '>')
if (elem[pos] == L'>')
{
if (pos > 1)
elem[pos - 1] = L'\0';
return;
}
// Full view mode
size_t len = wcslen(elem);
// Try to determine GetTextMode scheme
size_t delim_pos = cf_wcscspn(elem, L"\t\x0d");
if (elem[delim_pos] == L'\0')
{
// No special delimiters found => probably GetTextMode=0: columns are space-delimited (name size date time attributes)
for (int i = 0; i < 4; ++i)
{
len = cf_wcsrchr_pos(elem, len - 1, L' ');
if (len == 0)
return;
}
if ((elem[len] < L'0') || (elem[len] > L'9'))
{
// The Size value does not start with digit => it contains unit name delimited by space from the value,
// and only the unit was stripped, so now strip the value
len = cf_wcsrchr_pos(elem, len - 1, L' ');
if (len == 0)
return;
}
}
else
{
if (elem[delim_pos] == L'\t')
{
// Check if this is GetTextMode=4 or 5
size_t delim_pos2 = cf_wcscspn(elem, L"\x0d");
if (elem[delim_pos2] == L'\x0d')
{
// It is (Name:\t{name}<CR>Size:\t{size}<CR>Date:\t{date+time}<CR>Attrs:\t{attributes}, or same with <CR><LF>).
// Move the file name (substring between the first \t and \r chars) to the beginning of the text.
cf_memcpy_s(elem, len + 1, elem + delim_pos + 1, (delim_pos2 - delim_pos) * sizeof(WCHAR));
len = delim_pos2 - delim_pos;
}
else
// No, it's GetTextMode=1: columns are tab-delimited (name<TAB>size<TAB>date+time<TAB>attributes) => just cut by the first tab
len = delim_pos + 1;
}
else if (elem[delim_pos] == L'\x0d')
{
// GetTextMode=2: columns are \r-delimited (name<CR>size<CR>date+time<CR>attributes)
// GetTextMode=3: columns are \r\n-delimited (name<CR><LF>size<CR><LF>date time<CR><LF>attributes)
// In both cases \r is the the first non-filename character
len = delim_pos + 1;
}
}
elem[len - 1] = L'\0';
}
typedef void (WINAPI *tGetNativeSystemInfo)(LPSYSTEM_INFO lpSystemInfo);
typedef BOOL (WINAPI *tIsWow64Process)(HANDLE hProcess, PBOOL Wow64Process);
enum BITNESS
{
PROCESS_X32 = 0,
PROCESS_X64 = 1
};
// Checks whether process is 32- or 64-bit
BITNESS GetProcessBitness(DWORD pid)
{
BITNESS res = PROCESS_X32;
// Protection from loading DLL from current path
cf_wcscpylen_s(DllPath + DllPathLen, MAX_PATH - DllPathLen, L"kernel32.dll");
HMODULE kernel32 = LoadLibrary(DllPath);
if (kernel32 == NULL)
return res;
tGetNativeSystemInfo fGetNativeSystemInfo = (tGetNativeSystemInfo)GetProcAddress(kernel32, "GetNativeSystemInfo");
tIsWow64Process fIsWow64Process = (tIsWow64Process)GetProcAddress(kernel32, "IsWow64Process");
if ((fGetNativeSystemInfo != NULL) && (fIsWow64Process != NULL))
{
SYSTEM_INFO si;
fGetNativeSystemInfo(&si);
if (si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64)
{
HANDLE pHandle = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid);
if (pHandle != NULL)
{
BOOL is64;
// IsWow64Process returns FALSE for 64-bit process on 64-bit system
if (fIsWow64Process(pHandle, &is64) && !is64)
res = PROCESS_X64;
CloseHandle(pHandle);
}
}
}
FreeLibrary(kernel32);
return res;
}
HANDLE ProcessHeap;
#ifdef _DEBUG
int WINAPI wWinMain(
HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPWSTR lpCmdLine,
int nCmdShow
)
{
UNREFERENCED_PARAMETER(hInstance);
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(nCmdShow);
#else
int wWinMainCRTStartup()
{
LPWSTR lpCmdLine;
#endif
InitCommonControls();
/*
If this code is used somewhere else, keep in mind that when an error occurs,
resources are not freed (program terminates, so all resources are freed
by the system anyway).
*/
ProcessHeap = GetProcessHeap();
const WCHAR* const MsgBoxTitle = L"TC Edit Redirector";
const size_t BUF_SZ = 1024;
const size_t CMDLINE_BUF_SZ = 32 * 1024;
WCHAR* msg_buf = new WCHAR[BUF_SZ];
if (msg_buf == NULL)
{
MessageBox(NULL, L"Memory allocation error!", MsgBoxTitle, MB_ICONERROR | MB_OK);
ExitProcess(1);
}
DllPathLen = GetSystemDirectory(DllPath, MAX_PATH);
if (DllPathLen == 0)
{
cf_swprintf_s(msg_buf, BUF_SZ, L"Failed to get system directory (", GetLastError(), L")");
MessageBox(NULL, msg_buf, MsgBoxTitle, MB_ICONERROR | MB_OK);
ExitProcess(1);
}
else if (DllPathLen > MAX_PATH - 13)
{
MessageBox(NULL, L"Too long path to system directory!", MsgBoxTitle, MB_ICONERROR | MB_OK);
ExitProcess(1);
}
DllPath[DllPathLen++] = L'\\';
HWND tc_main_wnd = NULL;
ArrayHWND* tc_panels;
size_t i;
//////////////////////////////////////////////////////////////////////////
// Get the list of selected items from TC file panel //
//////////////////////////////////////////////////////////////////////////
/*
This part is the most performance-critical, because while this is working,
the user may change the cursor position, selection or even open another path.
So the very first thing we do is getting all the information we need from
TC window and its child windows/panels.
Algorithm:
1. Find window of the TC instance which initiated this TCER process:
a) get parent PID;
b) find TTOTAL_CMD window that belongs to the PID.
2. Find the active file panel handle:
a) find two TMyListBox'es (file panels);
b) get the focused child window of the TC's GUI thread;
c) compare to TMyListBox'es found.
3. Get current path from TC command line (needed for archives and FS plugins):
a) find all TMyPanel's that are direct children of the main window;
b) search for the one that has child TMyPanel but doesn't have TMyTabControl and THeaderClick
(for situations when tabs are on and off, respectively);
c) the remaining control is Command Line, get the path from its child TMyPanel.
4. Get active panel title:
TMyListBox and TPathPanel are independent, so we cannot get it from parent-child relationship
a) find all TPathPanel's that are children of the main window;
b) get the coordinates of the active panel;
c) check if left edges of TPathPanel are equal:
d1) yes: vertical layout; get the one which is above the listbox;
d2) no: horizontal layout; get the one whose left edge is closer to the listbox'es left edge.
5. Fetch the list of items to edit:
a) get the list of selected items;
b) if the list is empty, get the focused item.
*/
//////////////////////////////////////////////////////////////////////////
// 1. Find window of the TC instance which initiated this TCER process.
// Obtain address of NtQueryInformationProcess needed for getting PPID
// Protection from loading DLL from current path
cf_wcscpylen_s(DllPath + DllPathLen, MAX_PATH - DllPathLen, L"ntdll.dll");
HMODULE ntdll = LoadLibrary(DllPath);
if (ntdll == NULL)
{
cf_swprintf_s(msg_buf, BUF_SZ, L"Failed to load ntdll.dll (", GetLastError(), L")");
MessageBox(NULL, msg_buf, MsgBoxTitle, MB_ICONERROR | MB_OK);
ExitProcess(1);
}
tNtQueryInformationProcess fNtQueryInformationProcess = (tNtQueryInformationProcess)GetProcAddress(ntdll, "NtQueryInformationProcess");
if (fNtQueryInformationProcess == NULL)
{
cf_swprintf_s(msg_buf, BUF_SZ, L"Failed to find NtQueryInformationProcess (", GetLastError(), L")");
MessageBox(NULL, msg_buf, MsgBoxTitle, MB_ICONERROR | MB_OK);
ExitProcess(1);
}
// Get PID of the parent process (TC)
PROCESS_BASIC_INFORMATION proc_info;
ULONG ret_len;
NTSTATUS query_res = fNtQueryInformationProcess(GetCurrentProcess(), ProcessBasicInformation, &proc_info, sizeof(proc_info), &ret_len);
if (!NT_SUCCESS(query_res))
{
cf_swprintf_s_hex(msg_buf, BUF_SZ, L"NtQueryInformationProcess failed (0x", query_res, L")");
MessageBox(NULL, msg_buf, MsgBoxTitle, MB_ICONERROR | MB_OK);
ExitProcess(1);
}
FreeLibrary(ntdll);
BITNESS BitnessTC = GetProcessBitness((DWORD)proc_info.InheritedFromUniqueProcessId);
// Window class names for 32- and 64-bit TC controls
const WCHAR* ListBoxClass[2] = { L"TMyListBox", L"LCLListBox" };
const WCHAR* PanelClass[2] = { L"TMyPanel", L"Window" };
const WCHAR* CmdLineClass[2] = { L"TMyComboBox", L"LCLComboBox" };
//////////////////////////////////////////////////////////////////////////
// 2. Find the active file panel handle.
#ifdef _DEBUG
// DBG: When debugging, the debugger is parent; skip the PPID checks
proc_info.InheritedFromUniqueProcessId = 0;
#endif
// First, check if we are started from the Find Files dialog
bool parent_is_main_window = true;
tc_main_wnd = WindowFinder::FindWnd(NULL, false, L"TFindFile", proc_info.InheritedFromUniqueProcessId);
if (tc_main_wnd != NULL)
{
// Yes - remember this important fact
parent_is_main_window = false;
}
else
{
// No - try Sync Dirs
tc_main_wnd = WindowFinder::FindWnd(NULL, false, L"TCmpForm", proc_info.InheritedFromUniqueProcessId);
if (tc_main_wnd != NULL)
{
// Yes - remember this important fact
parent_is_main_window = false;
}
else
{
// No - find the main window of the TC instance
tc_main_wnd = WindowFinder::FindWnd(NULL, false, L"TTOTAL_CMD", proc_info.InheritedFromUniqueProcessId);
if (tc_main_wnd == NULL)
{
MessageBox(NULL, L"Could not find parent TC window!", MsgBoxTitle, MB_ICONERROR | MB_OK);
ExitProcess(1);
}
}
}
// Various variables calculated when TCER is started from the main TC window:
// Current path from TC command line
WCHAR* tc_curpath_cmdline = NULL;
size_t tc_curpath_cmdline_len = 0;
// List of selected items in the TC file panel
ArrayPtr<WCHAR>* sel_items_txt = NULL;
size_t sel_items_num = 0;
// Focused item in the TC file panel
WCHAR* focus_item_txt = NULL;
// Item to be used for selecting the appropriate editor
size_t active_item = 0;
// Work with TC file panel - only if started from the main TC window
if (parent_is_main_window)
{
// Find TC file panels
tc_panels = WindowFinder::FindWnds(tc_main_wnd, true, ListBoxClass[BitnessTC], 0);
if (tc_panels->GetLength() == 0)
{
MessageBox(tc_main_wnd, L"Could not find panels in the TC window!", MsgBoxTitle, MB_ICONERROR | MB_OK);
ExitProcess(1);
}
// Determine the focused panel
HWND tc_panel = NULL;
GUITHREADINFO gti;
gti.cbSize = sizeof(gti);
SetForegroundWindow(tc_main_wnd);
DWORD tid = GetWindowThreadProcessId(tc_main_wnd, NULL);
#ifdef _DEBUG
// DBG: Wait, so that application windows had time to switch and set focus
Sleep(500);
#endif
if (!GetGUIThreadInfo(tid, >i))
{
cf_swprintf_s(msg_buf, BUF_SZ, L"Failed to get TC GUI thread information (", GetLastError(), L")");
MessageBox(tc_main_wnd, msg_buf, MsgBoxTitle, MB_ICONERROR | MB_OK);
ExitProcess(1);
}
if (gti.hwndFocus == NULL)
{
MessageBox(tc_main_wnd, L"Failed to determine active panel!", MsgBoxTitle, MB_ICONERROR | MB_OK);
ExitProcess(1);
}
for (i = 0; i < tc_panels->GetLength(); ++i)
{
if ((*tc_panels)[i] == gti.hwndFocus)
{
tc_panel = gti.hwndFocus;
break;
}
}
delete tc_panels;
if (tc_panel == NULL)
{
MessageBox(tc_main_wnd, L"No TC panel is focused!", MsgBoxTitle, MB_ICONERROR | MB_OK);
ExitProcess(1);
}
if (GetWindowTextLength(tc_panel) != 0)
{
MessageBox(tc_main_wnd, L"No TC file panel is focused!", MsgBoxTitle, MB_ICONERROR | MB_OK);
ExitProcess(1);
}
//////////////////////////////////////////////////////////////////////////
// 3. Get current path from TC command line.
tc_curpath_cmdline = new WCHAR[BUF_SZ];
if (tc_curpath_cmdline == NULL)
{
MessageBox(tc_main_wnd, L"Memory allocation error!", MsgBoxTitle, MB_ICONERROR | MB_OK);
ExitProcess(1);
}
tc_curpath_cmdline[0] = L'\0';
tc_curpath_cmdline_len = 0;
tc_panels = WindowFinder::FindWnds(tc_main_wnd, true, PanelClass[BitnessTC], 0);
if (tc_panels->GetLength() == 0)
{
MessageBox(tc_main_wnd, L"Failed to find TC command line!", MsgBoxTitle, MB_ICONERROR | MB_OK);
ExitProcess(1);
}
for (i = 0; i < tc_panels->GetLength(); ++i)
{
if (WindowFinder::FindWnd((*tc_panels)[i], true, CmdLineClass[BitnessTC], 0) == NULL)
continue;
HWND tc_cmdline = WindowFinder::FindWnd((*tc_panels)[i], true, PanelClass[BitnessTC], 0);
if (tc_cmdline == NULL)
continue;
tc_curpath_cmdline_len = GetWindowText(tc_cmdline, tc_curpath_cmdline, BUF_SZ);
if (tc_curpath_cmdline_len + 1 >= BUF_SZ)
{
cf_swprintf_s(msg_buf, BUF_SZ, L"Too long path (", tc_curpath_cmdline_len, L" characters)!");
MessageBox(tc_main_wnd, msg_buf, MsgBoxTitle, MB_ICONERROR | MB_OK);
ExitProcess(1);
}
if (tc_curpath_cmdline_len > 0)
{
if ((tc_curpath_cmdline_len >= 2) && (tc_curpath_cmdline[tc_curpath_cmdline_len - 2] == L'\\'))
{
// The path ends with backslash (probably disk root) => just remove the angle bracket
tc_curpath_cmdline[--tc_curpath_cmdline_len] = L'\0';
}
else
{
// Path without trailing backslash => replace the angle bracket with backslash
tc_curpath_cmdline[tc_curpath_cmdline_len - 1] = L'\\';
}
}
break;
}
delete tc_panels;
//////////////////////////////////////////////////////////////////////////
// 4. Get active panel title.
/* Code reserved for future use!
// Find the two TPathPanel's that are children of the main window
tc_panels = WindowFinder::FindWnds(tc_main_wnd, false, L"TPathPanel", 0);
if (tc_panels->GetLength() != 2)
{
cf_swprintf_s(msg_buf, BUF_SZ, L"Invalid number of path bars (", tc_panels->GetLength(), L"), should be 2!");
MessageBox(tc_main_wnd, msg_buf, MsgBoxTitle, MB_ICONERROR | MB_OK);
ExitProcess(1);
}
// Get the coordinates of the active panel and path panels
RECT tc_panel_rect, path_panel1_rect, path_panel2_rect;
if (GetWindowRect(tc_panel, &tc_panel_rect) == 0)
{
cf_swprintf_s(msg_buf, BUF_SZ, L"Failed to obtain the panel placement (", GetLastError(), L")");
MessageBox(tc_main_wnd, msg_buf, MsgBoxTitle, MB_ICONERROR | MB_OK);
ExitProcess(1);
}
if ((GetWindowRect((*tc_panels)[0], &path_panel1_rect) == 0)
||
(GetWindowRect((*tc_panels)[1], &path_panel2_rect) == 0))
{
cf_swprintf_s(msg_buf, BUF_SZ, L"Failed to obtain the path panel placement (", GetLastError(), L")");
MessageBox(tc_main_wnd, msg_buf, MsgBoxTitle, MB_ICONERROR | MB_OK);
ExitProcess(1);
}
// Find the active path panel
HWND tc_path_panel;
if (path_panel1_rect.left == path_panel2_rect.left)
{
// Vertical panels placement
if (abs(tc_panel_rect.top - path_panel1_rect.top) < abs(tc_panel_rect.top - path_panel2_rect.top))
tc_path_panel = (*tc_panels)[0];
else
tc_path_panel = (*tc_panels)[1];
}
else
{
// Horizontal panels placement
if (abs(tc_panel_rect.left - path_panel1_rect.left) < abs(tc_panel_rect.left - path_panel2_rect.left))
tc_path_panel = (*tc_panels)[0];
else
tc_path_panel = (*tc_panels)[1];
}
delete tc_panels;
WCHAR* tc_curpath_panel = new WCHAR[BUF_SZ];
if (tc_curpath_panel == NULL)
{
MessageBox(tc_main_wnd, L"Memory allocation error!", MsgBoxTitle, MB_ICONERROR | MB_OK);
ExitProcess(1);
}
size_t tc_curpath_panel_len = GetWindowText(tc_path_panel, tc_curpath_panel, BUF_SZ);
if (tc_curpath_panel_len + 1 >= BUF_SZ)
{
cf_swprintf_s(msg_buf, BUF_SZ, L"Too long path (", tc_curpath_panel_len, L" characters)!");
MessageBox(tc_main_wnd, msg_buf, MsgBoxTitle, MB_ICONERROR | MB_OK);
ExitProcess(1);
}
delete[] tc_curpath_panel;
*/
//////////////////////////////////////////////////////////////////////////
// 5. Fetch the list of items to edit.
// Active item: the one to be used for choosing the editor.
// If focused item is selected it will be used, the first file otherwise.
active_item = 0;
// Get the focused item
UINT focus_item_idx = (UINT)SendMessage(tc_panel, LB_GETCARETINDEX, 0, 0);
// Get the number of selected elements and their indices
sel_items_num = SendMessage(tc_panel, LB_GETSELCOUNT, 0, 0);
UINT* sel_items_idx = NULL;
if (sel_items_num > 0)
{
sel_items_idx = new UINT[sel_items_num];
if (sel_items_idx == NULL)
{
MessageBox(tc_main_wnd, L"Memory allocation error!", MsgBoxTitle, MB_ICONERROR | MB_OK);
ExitProcess(1);
}
size_t sel_items_num2 = SendMessage(tc_panel, LB_GETSELITEMS, sel_items_num, (LPARAM)sel_items_idx);
if (sel_items_num2 < sel_items_num)
sel_items_num = sel_items_num2;
}
// Get the elements themselves
size_t invalid_paths = 0;
size_t elem_len = SendMessage(tc_panel, LB_GETTEXTLEN, focus_item_idx, NULL);
if ((elem_len != LB_ERR) && (elem_len > 0) && (elem_len + 1 < BUF_SZ))
{
focus_item_txt = new WCHAR[elem_len + 1];
if (focus_item_txt == NULL)
{
MessageBox(tc_main_wnd, L"Memory allocation error!", MsgBoxTitle, MB_ICONERROR | MB_OK);
ExitProcess(1);
}
if (SendMessage(tc_panel, LB_GETTEXT, focus_item_idx, (LPARAM)focus_item_txt) == 0)
{
delete[] focus_item_txt;
focus_item_txt = NULL;
}
}
sel_items_txt = new ArrayPtr<WCHAR>(sel_items_num);
if (sel_items_txt == NULL)
{
MessageBox(tc_main_wnd, L"Memory allocation error!", MsgBoxTitle, MB_ICONERROR | MB_OK);
ExitProcess(1);
}
for (i = 0; i < sel_items_num; ++i)
{
elem_len = SendMessage(tc_panel, LB_GETTEXTLEN, sel_items_idx[i], NULL);
if ((elem_len == LB_ERR) || (elem_len + 1 >= BUF_SZ))
{
++invalid_paths;
continue;
}
WCHAR* tmp = new WCHAR[elem_len + 1];
if (tmp == NULL)
{
MessageBox(tc_main_wnd, L"Memory allocation error!", MsgBoxTitle, MB_ICONERROR | MB_OK);
ExitProcess(1);
}
if (SendMessage(tc_panel, LB_GETTEXT, sel_items_idx[i], (LPARAM)tmp) == 0)
delete[] tmp;
else
{
sel_items_txt->Append(tmp);
if (focus_item_idx == sel_items_idx[i])
active_item = sel_items_txt->GetLength() - 1; // Remember the active item index
}
}
if (sel_items_idx != NULL)
delete[] sel_items_idx;
}
//////////////////////////////////////////////////////////////////////////
// Find TCER configuration file //
//////////////////////////////////////////////////////////////////////////
// Search for tcer.ini file: first own directory, then wincmd.ini directory
WCHAR* ini_path = new WCHAR[BUF_SZ];
WCHAR* ini_name = new WCHAR[BUF_SZ];
if ((ini_path == NULL) || (ini_name == NULL))
{
MessageBox(tc_main_wnd, L"Memory allocation error!", MsgBoxTitle, MB_ICONERROR | MB_OK);
ExitProcess(1);
}
if (GetModuleFileName(NULL, ini_path, BUF_SZ) == 0)
{
cf_swprintf_s(msg_buf, BUF_SZ, L"Failed to find myself (", GetLastError(), L")");
MessageBox(tc_main_wnd, msg_buf, MsgBoxTitle, MB_ICONERROR | MB_OK);
ExitProcess(1);
}
size_t path_len = wcslen(ini_path);
size_t idx_slash, idx_dot;
idx_slash = cf_wcsrchr_pos(ini_path, path_len, L'\\');
idx_dot = cf_wcsrchr_pos(ini_path, path_len, L'.');
size_t ini_name_len = path_len - idx_slash;
cf_wcscpylen_s(ini_name, BUF_SZ, ini_path + idx_slash);
if ((idx_dot == 0) || ((idx_slash != 0) && (idx_dot < idx_slash)))
{
// Extension not found, append '.ini'
if (ini_name_len + 5 > BUF_SZ)
{
MessageBox(tc_main_wnd, L"Too long INI file name!", MsgBoxTitle, MB_ICONERROR | MB_OK);
ExitProcess(1);
}
cf_wcscpylen_s(ini_name + ini_name_len, BUF_SZ - ini_name_len, L".ini");
}
else
{
// Extension found, replace with 'ini'
idx_dot -= idx_slash;
if (idx_dot + 4 > BUF_SZ)
{
MessageBox(tc_main_wnd, L"Too long INI file name!", MsgBoxTitle, MB_ICONERROR | MB_OK);
ExitProcess(1);
}
cf_wcscpylen_s(ini_name + idx_dot, BUF_SZ - idx_dot, L"ini");
ini_name_len = idx_dot + 3;
}
if (idx_slash + ini_name_len + 1 > BUF_SZ)
{
MessageBox(tc_main_wnd, L"Too long path to INI!", MsgBoxTitle, MB_ICONERROR | MB_OK);
ExitProcess(1);
}
cf_wcscpylen_s(ini_path + idx_slash, BUF_SZ - idx_slash, ini_name);
// INI file path constructed, check the file existence
if (GetFileAttributes(ini_path) == INVALID_FILE_ATTRIBUTES)
{
// File does not exist, search wincmd.ini directory
path_len = GetEnvironmentVariable(L"COMMANDER_INI", ini_path, BUF_SZ);
if (path_len == 0)
{
MessageBox(tc_main_wnd, L"COMMANDER_INI variable undefined!", MsgBoxTitle, MB_ICONERROR | MB_OK);
ExitProcess(1);
}
idx_slash = cf_wcsrchr_pos(ini_path, path_len, L'\\');
if (idx_slash == 0)
{
// File name only, replace it with INI file name
cf_wcscpylen_s(ini_path, BUF_SZ, ini_name);
}
else
{
// Keep path, replace file name
if (idx_slash + ini_name_len + 1 > BUF_SZ)
{
MessageBox(tc_main_wnd, L"Too long path to myself!", MsgBoxTitle, MB_ICONERROR | MB_OK);
ExitProcess(1);
}
cf_wcscpylen_s(ini_path + idx_slash, BUF_SZ - idx_slash, ini_name);
}
if (GetFileAttributes(ini_path) == INVALID_FILE_ATTRIBUTES)
{
MessageBox(tc_main_wnd, L"Configuration file not found!", MsgBoxTitle, MB_ICONERROR | MB_OK);
ExitProcess(1);
}
}
delete[] ini_name;
//////////////////////////////////////////////////////////////////////////
// Read general TCER configuration //
//////////////////////////////////////////////////////////////////////////
size_t MaxItems = GetPrivateProfileInt(L"Configuration", L"MaxItems", 256, ini_path);
size_t MaxShiftF4MSeconds = GetPrivateProfileInt(L"Configuration", L"MaxShiftF4MSeconds", 2000, ini_path);
bool ClearSelection = (GetPrivateProfileInt(L"Configuration", L"ClearSelection", 1, ini_path) != 0);
//////////////////////////////////////////////////////////////////////////
// Translate list of items into list of paths //
//////////////////////////////////////////////////////////////////////////
// TODO: [1:HIGH] Support opening files directly from %TEMP%\_tc\
/*
Current implementation:
1) Started from Find Files -> use lpCmdLine.
2) lpCmdLine =~ %TEMP%\_tc(_|)\.*
Archive/FS-plugin/FTP/etc. -> open lpCmdLine, wait till editor close.
3) tc_curpath_cmdline =~ \\\.*
TempPanel FS-plugin -> open lpCmdLine, do not wait.
4) lpCmdLine was just created
Shift+F4 -> open lpCmdLine, do not wait.
5) Otherwise
Combine tc_curpath_cmdline with selected elements.
6) If no elements selected, open the focused file.
7) If it fails, open the file supplied via command line.
*/
#ifndef _DEBUG
// CRT code did not run to prepare command line arguments, so do it now
lpCmdLine = GetCommandLine();
// Remove the TCER executable from comand line
bool InsideQuotes = false;
while ((*lpCmdLine > L' ') || (*lpCmdLine && InsideQuotes))
{
// Flip the InsideQuotes if current character is a double quote
if (*lpCmdLine == L'"')
InsideQuotes = !InsideQuotes;
++lpCmdLine;
}
// Skip past any white space preceeding the second token.
while (*lpCmdLine && (*lpCmdLine <= L' '))
++lpCmdLine;
#endif
bool WaitForTerminate = false;
ArrayPtr<WCHAR>* edit_paths = new ArrayPtr<WCHAR>;
if (edit_paths == NULL)
{
MessageBox(tc_main_wnd, L"Memory allocation error!", MsgBoxTitle, MB_ICONERROR | MB_OK);
ExitProcess(1);
}
size_t offset;
size_t len;
// Remove quotes from lpCmdLine (if present) and copy it into non-const buffer
WCHAR* input_file = new WCHAR[BUF_SZ];
if (input_file == NULL)
{
MessageBox(tc_main_wnd, L"Memory allocation error!", MsgBoxTitle, MB_ICONERROR | MB_OK);
ExitProcess(1);
}
input_file[0] = L'\0';
if ((lpCmdLine != NULL) && (lpCmdLine[0] != L'\0'))
{
offset = ((lpCmdLine[0] == L'"') ? 1 : 0);
len = cf_wcscpylen_s(input_file, BUF_SZ, lpCmdLine + offset);
if (input_file[len - 1] == L'"')
input_file[len - 1] = L'\0';
if (len >= BUF_SZ)
{
cf_swprintf_s(msg_buf, BUF_SZ, L"Too long input path (>=", len, L" characters)!");
MessageBox(tc_main_wnd, msg_buf, MsgBoxTitle, MB_ICONERROR | MB_OK);
ExitProcess(1);
}
}
// a. Check for Find Files / Sync Dirs being our parent
if (!parent_is_main_window)
{
edit_paths->Append(input_file);
input_file = NULL; // Memory block now is controlled by ArrayPtr, forget about it
WaitForTerminate = false;
}
// TODO: [3:MEDIUM] Get rid of code duplication
// b. Check for archive/FS-plugin/FTP/etc.
if (edit_paths->GetLength() == 0)
{
WCHAR* temp_dir = new WCHAR[BUF_SZ];
if (temp_dir == NULL)
{
MessageBox(tc_main_wnd, L"Memory allocation error!", MsgBoxTitle, MB_ICONERROR | MB_OK);
ExitProcess(1);
}
size_t temp_dir_len = GetTempPath(BUF_SZ, temp_dir);
if (temp_dir_len + 4 >= BUF_SZ)
{
cf_swprintf_s(msg_buf, BUF_SZ, L"Too long TEMP path (", temp_dir_len, L" characters)!");
MessageBox(tc_main_wnd, msg_buf, MsgBoxTitle, MB_ICONERROR | MB_OK);
ExitProcess(1);
}
temp_dir[temp_dir_len++] = L'_';
temp_dir[temp_dir_len++] = L't';
temp_dir[temp_dir_len++] = L'c';
if (cf_wcsnicmp(input_file, temp_dir, temp_dir_len) == 0)
{
if ((input_file[temp_dir_len] == L'\\')
||
((input_file[temp_dir_len] == L'_') && (input_file[temp_dir_len + 1] == L'\\')))
{
edit_paths->Append(input_file);
input_file = NULL; // Memory block now is controlled by ArrayPtr, forget about it
// FS-plugins do not need to wait; archives/FTP/LPT/etc. do need.
WaitForTerminate = (cf_wcsncmp(tc_curpath_cmdline, L"\\\\\\", 3) != 0);
}
}
delete[] temp_dir;
}
// c. Check for TemporaryPanel FS-plugin.
if (edit_paths->GetLength() == 0)
{
if (cf_wcsncmp(tc_curpath_cmdline, L"\\\\\\", 3) == 0)
{
edit_paths->Append(input_file);
input_file = NULL;
}
}
// TODO: [1:HIGH] If TC panel is not autorefreshed (NoReread) the new file does not appear, and TCER opens the file under cursor instead
// c. Check for Shift+F4.
/*
Using timestamp values of the input file.
Timestamp resolutions for different file systems:
NTFS:
CreationTime - 100 nanoseconds
LastWriteTime - 100 nanoseconds
LastAccessTime - 100 nanoseconds
(LastAccessTime is updated at a 60 minute granularity; in Vista/Server08 updates to LastAccessTime
are disabled by default and are updated only when the file is closed.)
FAT:
CreationTime - 10 milliseconds
LastWriteTime - 2 seconds
LastAccessTime - 1 day
exFAT:
CreationTime - 10 milliseconds
LastWriteTime - 10 milliseconds
LastAccessTime - 2 seconds
So, check whether CreationTime is close enough to the current system time.
*/
if (edit_paths->GetLength() == 0)
{
WIN32_FILE_ATTRIBUTE_DATA file_info;
if (GetFileAttributesEx(input_file, GetFileExInfoStandard, &file_info))
{
FILETIME local_time;
GetSystemTimeAsFileTime(&local_time);
ULARGE_INTEGER file_time64;
ULARGE_INTEGER local_time64;
file_time64.HighPart = file_info.ftCreationTime.dwHighDateTime;
file_time64.LowPart = file_info.ftCreationTime.dwLowDateTime;
local_time64.HighPart = local_time.dwHighDateTime;
local_time64.LowPart = local_time.dwLowDateTime;
// Consider the file just created if it is older than MaxShiftF4MSeconds milliseconds
// (2000 milliseconds by default)
if (local_time64.QuadPart - file_time64.QuadPart < MaxShiftF4MSeconds * 10000)
{
edit_paths->Append(input_file);
input_file = NULL;
}
}
}
// e. Get files from panel
if (edit_paths->GetLength() == 0)
{
for (i = 0; i < sel_items_num; ++i)
{
strip_file_data((*sel_items_txt)[i]);
WCHAR* tmp = new WCHAR[BUF_SZ];
if (tmp == NULL)
{
MessageBox(tc_main_wnd, L"Memory allocation error!", MsgBoxTitle, MB_ICONERROR | MB_OK);
ExitProcess(1);
}
cf_wcscpylen_s(tmp, BUF_SZ, tc_curpath_cmdline);
len = cf_wcscpylen_s(tmp + tc_curpath_cmdline_len, BUF_SZ - tc_curpath_cmdline_len, (*sel_items_txt)[i]);
if ((len < BUF_SZ) && ((GetFileAttributes(tmp) & FILE_ATTRIBUTE_DIRECTORY) == 0))
{
edit_paths->Append(tmp);
// Update the active item index in case some bad items did not pass the test
if (active_item == i)
active_item = edit_paths->GetLength() - 1;
}
else
{
delete[] tmp;
// The active item is bad; drop it and use the first item
if (active_item == i)
active_item = 0;
}
}
if ((sel_items_num > 0) && (edit_paths->GetLength() == 0))
{
MessageBox(tc_main_wnd, L"None of the selected elements could be opened!", MsgBoxTitle, MB_ICONERROR | MB_OK);
ExitProcess(1);
}
}
// e. Get focused element
if ((edit_paths->GetLength() == 0) && (focus_item_txt != NULL))
{
// No elements found, probably switched directory too fast in TC.
active_item = 0;
strip_file_data(focus_item_txt);
WCHAR* tmp = new WCHAR[BUF_SZ];
if (tmp == NULL)
{
MessageBox(tc_main_wnd, L"Memory allocation error!", MsgBoxTitle, MB_ICONERROR | MB_OK);
ExitProcess(1);
}
cf_wcscpylen_s(tmp, BUF_SZ, tc_curpath_cmdline);
len = cf_wcscpylen_s(tmp + tc_curpath_cmdline_len, BUF_SZ - tc_curpath_cmdline_len, focus_item_txt);
if ((len < BUF_SZ) && ((GetFileAttributes(tmp) & FILE_ATTRIBUTE_DIRECTORY) == 0))
edit_paths->Append(tmp);
else
delete[] tmp;
}
// f. Get the file from command line.
if (edit_paths->GetLength() == 0)
{
// No elements found, probably switched directory too fast in TC.
active_item = 0;
edit_paths->Append(input_file);
input_file = NULL;
}
// Check the final active item index
if (active_item >= edit_paths->GetLength())
active_item = 0;
delete sel_items_txt;
delete[] tc_curpath_cmdline;
if (focus_item_txt != NULL)
delete[] focus_item_txt;
if (input_file != NULL)
delete[] input_file;
// Check for the number of files to be opened
// (in case Ctrl+A, F4 was accidentally pressed in a huge directory)
sel_items_num = edit_paths->GetLength();
if ((MaxItems != 0) && (sel_items_num > MaxItems))
{
cf_swprintf_s(msg_buf, BUF_SZ, L"", sel_items_num, L" files are to be opened!\nAre you sure you wish to continue?");
if (MessageBox(tc_main_wnd, msg_buf, MsgBoxTitle, MB_ICONWARNING | MB_OKCANCEL) == IDCANCEL)
ExitProcess(0);
}
//////////////////////////////////////////////////////////////////////////
// Read TCER options for the 'active file' extension //
//////////////////////////////////////////////////////////////////////////
WCHAR* edit_path = (*edit_paths)[active_item];
WCHAR* file_ext = new WCHAR[BUF_SZ];
WCHAR* ini_section = new WCHAR[BUF_SZ];
WCHAR* editor_path = new WCHAR[2 * BUF_SZ];
if ((file_ext == NULL) || (ini_section == NULL) || (editor_path == NULL))
{
MessageBox(tc_main_wnd, L"Memory allocation error!", MsgBoxTitle, MB_ICONERROR | MB_OK);
ExitProcess(1);
}
// Extract the active file extension
path_len = wcslen(edit_path);
idx_slash = cf_wcsrchr_pos(edit_path, path_len, L'\\');
idx_dot = cf_wcsrchr_pos(edit_path, path_len, L'.');
size_t file_ext_len;
if ((idx_dot == 0) || ((idx_slash != 0) && (idx_dot < idx_slash)))
{
// Extension not found
file_ext_len = cf_wcscpylen_s(file_ext, BUF_SZ, L"<nil>");
}
else
{
// Extension found
file_ext_len = cf_wcscpylen_s(file_ext, BUF_SZ, edit_path + idx_dot);
}
// Get section name that describes the editor to use
WCHAR* all_exts = new WCHAR[32767];
if (GetPrivateProfileSection(L"Extensions", all_exts, 32767, ini_path) == 0)
{
// No extensions specified, use DefaultProgram
cf_wcscpylen_s(ini_section, BUF_SZ, L"DefaultProgram");
}
else
{
WCHAR* exts_block = all_exts;
bool found = false;
// INI section lines are 0-byte-delimited, and the whole section ends with two 0-bytes
while (*exts_block != L'\0')
{
WCHAR* pos = exts_block;
// Checking the list of extensions in the current line...
while (*pos != L'=')
{
if ((cf_wcsnicmp(pos, file_ext, file_ext_len) == 0) && ((pos[file_ext_len] == L',') || (pos[file_ext_len] == L'=')))
{
// Found the correct extension => store the application name and exit the loop
found = true;
pos += cf_wcscspn(pos, L"=") + 1;
cf_wcscpylen_s(ini_section, BUF_SZ, L"Program_");
cf_wcscpylen_s(ini_section + 8, BUF_SZ - 8, pos);
break;
}
// Go to the next extension
pos += cf_wcscspn(pos, L",=");
if (*pos == L',')
++pos;
}
if (found)
break;
else
{
// Go to the next line
pos += cf_wcscspn(pos, L"") + 1;
exts_block = pos;
}
}
if (!found)
{
// No editor specified, use DefaultProgram
cf_wcscpylen_s(ini_section, BUF_SZ, L"DefaultProgram");
}
}
delete[] all_exts;
delete[] file_ext;
// Read the editor settings
BOOL is_mdi = GetPrivateProfileInt(ini_section, L"MDI", 0, ini_path);
WCHAR* tmp_buf = new WCHAR[BUF_SZ];
if (tmp_buf == NULL)
{
MessageBox(tc_main_wnd, L"Memory allocation error!", MsgBoxTitle, MB_ICONERROR | MB_OK);