comctl32: rebar: Don't assume the first band is visible.
[wine] / programs / winefile / winefile.c
1 /*
2  * Winefile
3  *
4  * Copyright 2000, 2003, 2004, 2005 Martin Fuchs
5  * Copyright 2006 Jason Green
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20  */
21
22 #ifdef __WINE__
23 #include "config.h"
24 #include "wine/port.h"
25
26 /* for unix filesystem function calls */
27 #include <sys/stat.h>
28 #include <sys/types.h>
29 #include <dirent.h>
30 #endif
31
32 #define COBJMACROS
33
34 #include "winefile.h"
35 #include "resource.h"
36
37 #ifdef _NO_EXTENSIONS
38 #undef _LEFT_FILES
39 #endif
40
41 #ifndef _MAX_PATH
42 #define _MAX_DRIVE          3
43 #define _MAX_FNAME          256
44 #define _MAX_DIR            _MAX_FNAME
45 #define _MAX_EXT            _MAX_FNAME
46 #define _MAX_PATH           260
47 #endif
48
49 #ifdef NONAMELESSUNION
50 #define UNION_MEMBER(x) DUMMYUNIONNAME.x
51 #else
52 #define UNION_MEMBER(x) x
53 #endif
54
55
56 #ifdef _SHELL_FOLDERS
57 #define DEFAULT_SPLIT_POS       300
58 #else
59 #define DEFAULT_SPLIT_POS       200
60 #endif
61
62 static const WCHAR registry_key[] = { 'S','o','f','t','w','a','r','e','\\',
63                                       'W','i','n','e','\\',
64                                       'W','i','n','e','F','i','l','e','\0'};
65 static const WCHAR reg_start_x[] = { 's','t','a','r','t','X','\0'};
66 static const WCHAR reg_start_y[] = { 's','t','a','r','t','Y','\0'};
67 static const WCHAR reg_width[] = { 'w','i','d','t','h','\0'};
68 static const WCHAR reg_height[] = { 'h','e','i','g','h','t','\0'};
69 static const WCHAR reg_logfont[] = { 'l','o','g','f','o','n','t','\0'};
70
71 enum ENTRY_TYPE {
72         ET_WINDOWS,
73         ET_UNIX,
74 #ifdef _SHELL_FOLDERS
75         ET_SHELL
76 #endif
77 };
78
79 typedef struct _Entry {
80         struct _Entry*  next;
81         struct _Entry*  down;
82         struct _Entry*  up;
83
84         BOOL                    expanded;
85         BOOL                    scanned;
86         int                             level;
87
88         WIN32_FIND_DATA data;
89
90 #ifndef _NO_EXTENSIONS
91         BY_HANDLE_FILE_INFORMATION bhfi;
92         BOOL                    bhfi_valid;
93         enum ENTRY_TYPE etype;
94 #endif
95 #ifdef _SHELL_FOLDERS
96         LPITEMIDLIST    pidl;
97         IShellFolder*   folder;
98         HICON                   hicon;
99 #endif
100 } Entry;
101
102 typedef struct {
103         Entry   entry;
104         TCHAR   path[MAX_PATH];
105         TCHAR   volname[_MAX_FNAME];
106         TCHAR   fs[_MAX_DIR];
107         DWORD   drive_type;
108         DWORD   fs_flags;
109 } Root;
110
111 enum COLUMN_FLAGS {
112         COL_SIZE                = 0x01,
113         COL_DATE                = 0x02,
114         COL_TIME                = 0x04,
115         COL_ATTRIBUTES  = 0x08,
116         COL_DOSNAMES    = 0x10,
117 #ifdef _NO_EXTENSIONS
118         COL_ALL = COL_SIZE|COL_DATE|COL_TIME|COL_ATTRIBUTES|COL_DOSNAMES
119 #else
120         COL_INDEX               = 0x20,
121         COL_LINKS               = 0x40,
122         COL_ALL = COL_SIZE|COL_DATE|COL_TIME|COL_ATTRIBUTES|COL_DOSNAMES|COL_INDEX|COL_LINKS
123 #endif
124 };
125
126 typedef enum {
127         SORT_NAME,
128         SORT_EXT,
129         SORT_SIZE,
130         SORT_DATE
131 } SORT_ORDER;
132
133 typedef struct {
134         HWND    hwnd;
135 #ifndef _NO_EXTENSIONS
136         HWND    hwndHeader;
137 #endif
138
139 #ifndef _NO_EXTENSIONS
140 #define COLUMNS 10
141 #else
142 #define COLUMNS 5
143 #endif
144         int             widths[COLUMNS];
145         int             positions[COLUMNS+1];
146
147         BOOL    treePane;
148         int             visible_cols;
149         Entry*  root;
150         Entry*  cur;
151 } Pane;
152
153 typedef struct {
154         HWND    hwnd;
155         Pane    left;
156         Pane    right;
157         int             focus_pane;             /* 0: left  1: right */
158         WINDOWPLACEMENT pos;
159         int             split_pos;
160         BOOL    header_wdths_ok;
161
162         TCHAR   path[MAX_PATH];
163         TCHAR   filter_pattern[MAX_PATH];
164         int             filter_flags;
165         Root    root;
166
167         SORT_ORDER sortOrder;
168 } ChildWnd;
169
170
171
172 static void read_directory(Entry* dir, LPCTSTR path, SORT_ORDER sortOrder, HWND hwnd);
173 static void set_curdir(ChildWnd* child, Entry* entry, int idx, HWND hwnd);
174 static void refresh_child(ChildWnd* child);
175 static void refresh_drives(void);
176 static void get_path(Entry* dir, PTSTR path);
177 static void format_date(const FILETIME* ft, TCHAR* buffer, int visible_cols);
178
179 static LRESULT CALLBACK FrameWndProc(HWND hwnd, UINT nmsg, WPARAM wparam, LPARAM lparam);
180 static LRESULT CALLBACK ChildWndProc(HWND hwnd, UINT nmsg, WPARAM wparam, LPARAM lparam);
181 static LRESULT CALLBACK TreeWndProc(HWND hwnd, UINT nmsg, WPARAM wparam, LPARAM lparam);
182
183
184 /* globals */
185 WINEFILE_GLOBALS Globals;
186
187 static int last_split;
188
189 /* some common string constants */
190 static const TCHAR sEmpty[] = {'\0'};
191 static const WCHAR sSpace[] = {' ', '\0'};
192 static const TCHAR sNumFmt[] = {'%','d','\0'};
193 static const TCHAR sQMarks[] = {'?','?','?','\0'};
194
195 /* window class names */
196 static const TCHAR sWINEFILEFRAME[] = {'W','F','S','_','F','r','a','m','e','\0'};
197 static const TCHAR sWINEFILETREE[] = {'W','F','S','_','T','r','e','e','\0'};
198
199 #ifdef _MSC_VER
200 /* #define LONGLONGARG _T("I64") */
201 static const TCHAR sLongHexFmt[] = {'%','I','6','4','X','\0'};
202 static const TCHAR sLongNumFmt[] = {'%','I','6','4','d','\0'};
203 #else
204 /* #define LONGLONGARG _T("L") */
205 static const TCHAR sLongHexFmt[] = {'%','L','X','\0'};
206 static const TCHAR sLongNumFmt[] = {'%','L','d','\0'};
207 #endif
208
209
210 /* load resource string */
211 static LPTSTR load_string(LPTSTR buffer, UINT id)
212 {
213         LoadString(Globals.hInstance, id, buffer, BUFFER_LEN);
214
215         return buffer;
216 }
217
218 #define RS(b, i) load_string(b, i)
219
220
221 /* display error message for the specified WIN32 error code */
222 static void display_error(HWND hwnd, DWORD error)
223 {
224         TCHAR b1[BUFFER_LEN], b2[BUFFER_LEN];
225         PTSTR msg;
226
227         if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
228                 0, error, MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT), (PTSTR)&msg, 0, NULL))
229                 MessageBox(hwnd, msg, RS(b2,IDS_WINEFILE), MB_OK);
230         else
231                 MessageBox(hwnd, RS(b1,IDS_ERROR), RS(b2,IDS_WINEFILE), MB_OK);
232
233         LocalFree(msg);
234 }
235
236
237 /* display network error message using WNetGetLastError() */
238 static void display_network_error(HWND hwnd)
239 {
240         TCHAR msg[BUFFER_LEN], provider[BUFFER_LEN], b2[BUFFER_LEN];
241         DWORD error;
242
243         if (WNetGetLastError(&error, msg, BUFFER_LEN, provider, BUFFER_LEN) == NO_ERROR)
244                 MessageBox(hwnd, msg, RS(b2,IDS_WINEFILE), MB_OK);
245 }
246
247 static VOID WineLicense(HWND Wnd)
248 {
249         WCHAR cap[20], text[1024];
250         LoadStringW(Globals.hInstance, IDS_LICENSE, text, 1024);
251         LoadStringW(Globals.hInstance, IDS_LICENSE_CAPTION, cap, 20);
252         MessageBoxW(Wnd, text, cap, MB_ICONINFORMATION | MB_OK);
253 }
254
255 static VOID WineWarranty(HWND Wnd)
256 {
257         WCHAR cap[20], text[1024];
258         LoadStringW(Globals.hInstance, IDS_WARRANTY, text, 1024);
259         LoadStringW(Globals.hInstance, IDS_WARRANTY_CAPTION, cap, 20);
260         MessageBoxW(Wnd, text, cap, MB_ICONEXCLAMATION | MB_OK);
261 }
262
263 static inline BOOL get_check(HWND hwnd, INT id)
264 {
265         return BST_CHECKED&SendMessageW(GetDlgItem(hwnd, id), BM_GETSTATE, 0, 0);
266 }
267
268 static inline INT set_check(HWND hwnd, INT id, BOOL on)
269 {
270         return SendMessageW(GetDlgItem(hwnd, id), BM_SETCHECK, on?BST_CHECKED:BST_UNCHECKED, 0);
271 }
272
273 static inline void choose_font(HWND hwnd)
274 {
275         WCHAR dlg_name[BUFFER_LEN], dlg_info[BUFFER_LEN];
276         CHOOSEFONTW chFont;
277         LOGFONTW lFont;
278
279         HDC hdc = GetDC(hwnd);
280         chFont.lStructSize = sizeof(CHOOSEFONT);
281         chFont.hwndOwner = hwnd;
282         chFont.hDC = NULL;
283         chFont.lpLogFont = &lFont;
284         chFont.Flags = CF_SCREENFONTS | CF_FORCEFONTEXIST | CF_LIMITSIZE | CF_NOSCRIPTSEL;
285         chFont.rgbColors = RGB(0,0,0);
286         chFont.lCustData = 0;
287         chFont.lpfnHook = NULL;
288         chFont.lpTemplateName = NULL;
289         chFont.hInstance = Globals.hInstance;
290         chFont.lpszStyle = NULL;
291         chFont.nFontType = SIMULATED_FONTTYPE;
292         chFont.nSizeMin = 0;
293         chFont.nSizeMax = 24;
294
295         if (ChooseFontW(&chFont)) {
296                 HWND childWnd;
297                 HFONT hFontOld;
298
299                 DeleteObject(Globals.hfont);
300                 Globals.hfont = CreateFontIndirectW(&lFont);
301                 hFontOld = SelectObject(hdc, Globals.hfont);
302                 GetTextExtentPoint32W(hdc, sSpace, 1, &Globals.spaceSize);
303
304                 /* change font in all open child windows */
305                 for(childWnd=GetWindow(Globals.hmdiclient,GW_CHILD); childWnd; childWnd=GetNextWindow(childWnd,GW_HWNDNEXT)) {
306                         ChildWnd* child = (ChildWnd*) GetWindowLongPtrW(childWnd, GWLP_USERDATA);
307                         SendMessageW(child->left.hwnd, WM_SETFONT, (WPARAM)Globals.hfont, TRUE);
308                         SendMessageW(child->right.hwnd, WM_SETFONT, (WPARAM)Globals.hfont, TRUE);
309                         SendMessageW(child->left.hwnd, LB_SETITEMHEIGHT, 1, max(Globals.spaceSize.cy,IMAGE_HEIGHT+3));
310                         SendMessageW(child->right.hwnd, LB_SETITEMHEIGHT, 1, max(Globals.spaceSize.cy,IMAGE_HEIGHT+3));
311                         InvalidateRect(child->left.hwnd, NULL, TRUE);
312                         InvalidateRect(child->right.hwnd, NULL, TRUE);
313                 }
314
315                 SelectObject(hdc, hFontOld);
316         }
317         else if (CommDlgExtendedError()) {
318                 LoadStringW(Globals.hInstance, IDS_FONT_SEL_DLG_NAME, dlg_name, BUFFER_LEN);
319                 LoadStringW(Globals.hInstance, IDS_FONT_SEL_ERROR, dlg_info, BUFFER_LEN);
320                 MessageBoxW(hwnd, dlg_info, dlg_name, MB_OK);
321         }
322
323         ReleaseDC(hwnd, hdc);
324 }
325
326 #ifdef __WINE__
327
328 #ifdef UNICODE
329
330 /* call vswprintf() in msvcrt.dll */
331 /*TODO: fix swprintf() in non-msvcrt mode, so that this dynamic linking function can be removed */
332 static int msvcrt_swprintf(WCHAR* buffer, const WCHAR* fmt, ...)
333 {
334         static int (__cdecl *pvswprintf)(WCHAR*, const WCHAR*, va_list) = NULL;
335         va_list ap;
336         int ret;
337
338         if (!pvswprintf) {
339                 HMODULE hModMsvcrt = LoadLibraryA("msvcrt");
340                 pvswprintf = (int(__cdecl*)(WCHAR*,const WCHAR*,va_list)) GetProcAddress(hModMsvcrt, "vswprintf");
341         }
342
343         va_start(ap, fmt);
344         ret = (*pvswprintf)(buffer, fmt, ap);
345         va_end(ap);
346
347         return ret;
348 }
349
350 static LPCWSTR my_wcsrchr(LPCWSTR str, WCHAR c)
351 {
352         LPCWSTR p = str;
353
354         while(*p)
355                 ++p;
356
357         do {
358                 if (--p < str)
359                         return NULL;
360         } while(*p != c);
361
362         return p;
363 }
364
365 #define _tcsrchr my_wcsrchr
366 #else   /* UNICODE */
367 #define _tcsrchr strrchr
368 #endif  /* UNICODE */
369
370 #endif  /* __WINE__ */
371
372
373 /* allocate and initialise a directory entry */
374 static Entry* alloc_entry(void)
375 {
376         Entry* entry = HeapAlloc(GetProcessHeap(), 0, sizeof(Entry));
377
378 #ifdef _SHELL_FOLDERS
379         entry->pidl = NULL;
380         entry->folder = NULL;
381         entry->hicon = 0;
382 #endif
383
384         return entry;
385 }
386
387 /* free a directory entry */
388 static void free_entry(Entry* entry)
389 {
390 #ifdef _SHELL_FOLDERS
391         if (entry->hicon && entry->hicon!=(HICON)-1)
392                 DestroyIcon(entry->hicon);
393
394         if (entry->folder && entry->folder!=Globals.iDesktop)
395                 IShellFolder_Release(entry->folder);
396
397         if (entry->pidl)
398                 IMalloc_Free(Globals.iMalloc, entry->pidl);
399 #endif
400
401         HeapFree(GetProcessHeap(), 0, entry);
402 }
403
404 /* recursively free all child entries */
405 static void free_entries(Entry* dir)
406 {
407         Entry *entry, *next=dir->down;
408
409         if (next) {
410                 dir->down = 0;
411
412                 do {
413                         entry = next;
414                         next = entry->next;
415
416                         free_entries(entry);
417                         free_entry(entry);
418                 } while(next);
419         }
420 }
421
422
423 static void read_directory_win(Entry* dir, LPCTSTR path)
424 {
425         Entry* first_entry = NULL;
426         Entry* last = NULL;
427         Entry* entry;
428
429         int level = dir->level + 1;
430         WIN32_FIND_DATA w32fd;
431         HANDLE hFind;
432 #ifndef _NO_EXTENSIONS
433         HANDLE hFile;
434 #endif
435
436         TCHAR buffer[MAX_PATH], *p;
437         for(p=buffer; *path; )
438                 *p++ = *path++;
439
440         *p++ = '\\';
441         p[0] = '*';
442         p[1] = '\0';
443
444         hFind = FindFirstFile(buffer, &w32fd);
445
446         if (hFind != INVALID_HANDLE_VALUE) {
447                 do {
448 #ifdef _NO_EXTENSIONS
449                         /* hide directory entry "." */
450                         if (w32fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
451                                 LPCTSTR name = w32fd.cFileName;
452
453                                 if (name[0]=='.' && name[1]=='\0')
454                                         continue;
455                         }
456 #endif
457                         entry = alloc_entry();
458
459                         if (!first_entry)
460                                 first_entry = entry;
461
462                         if (last)
463                                 last->next = entry;
464
465                         memcpy(&entry->data, &w32fd, sizeof(WIN32_FIND_DATA));
466                         entry->down = NULL;
467                         entry->up = dir;
468                         entry->expanded = FALSE;
469                         entry->scanned = FALSE;
470                         entry->level = level;
471
472 #ifndef _NO_EXTENSIONS
473                         entry->etype = ET_WINDOWS;
474                         entry->bhfi_valid = FALSE;
475
476                         lstrcpy(p, entry->data.cFileName);
477
478                         hFile = CreateFile(buffer, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
479                                                                 0, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0);
480
481                         if (hFile != INVALID_HANDLE_VALUE) {
482                                 if (GetFileInformationByHandle(hFile, &entry->bhfi))
483                                         entry->bhfi_valid = TRUE;
484
485                                 CloseHandle(hFile);
486                         }
487 #endif
488
489                         last = entry;
490                 } while(FindNextFile(hFind, &w32fd));
491
492                 if (last)
493                         last->next = NULL;
494
495                 FindClose(hFind);
496         }
497
498         dir->down = first_entry;
499         dir->scanned = TRUE;
500 }
501
502
503 static Entry* find_entry_win(Entry* dir, LPCTSTR name)
504 {
505         Entry* entry;
506
507         for(entry=dir->down; entry; entry=entry->next) {
508                 LPCTSTR p = name;
509                 LPCTSTR q = entry->data.cFileName;
510
511                 do {
512                         if (!*p || *p == '\\' || *p == '/')
513                                 return entry;
514                 } while(tolower(*p++) == tolower(*q++));
515
516                 p = name;
517                 q = entry->data.cAlternateFileName;
518
519                 do {
520                         if (!*p || *p == '\\' || *p == '/')
521                                 return entry;
522                 } while(tolower(*p++) == tolower(*q++));
523         }
524
525         return 0;
526 }
527
528
529 static Entry* read_tree_win(Root* root, LPCTSTR path, SORT_ORDER sortOrder, HWND hwnd)
530 {
531         TCHAR buffer[MAX_PATH];
532         Entry* entry = &root->entry;
533         LPCTSTR s = path;
534         PTSTR d = buffer;
535
536         HCURSOR old_cursor = SetCursor(LoadCursor(0, IDC_WAIT));
537
538 #ifndef _NO_EXTENSIONS
539         entry->etype = ET_WINDOWS;
540 #endif
541
542         while(entry) {
543                 while(*s && *s != '\\' && *s != '/')
544                         *d++ = *s++;
545
546                 while(*s == '\\' || *s == '/')
547                         s++;
548
549                 *d++ = '\\';
550                 *d = '\0';
551
552                 read_directory(entry, buffer, sortOrder, hwnd);
553
554                 if (entry->down)
555                         entry->expanded = TRUE;
556
557                 if (!*s)
558                         break;
559
560                 entry = find_entry_win(entry, s);
561         }
562
563         SetCursor(old_cursor);
564
565         return entry;
566 }
567
568
569 #if !defined(_NO_EXTENSIONS) && defined(__WINE__)
570
571 static BOOL time_to_filetime(const time_t* t, FILETIME* ftime)
572 {
573         struct tm* tm = gmtime(t);
574         SYSTEMTIME stime;
575
576         if (!tm)
577                 return FALSE;
578
579         stime.wYear = tm->tm_year+1900;
580         stime.wMonth = tm->tm_mon+1;
581         /*      stime.wDayOfWeek */
582         stime.wDay = tm->tm_mday;
583         stime.wHour = tm->tm_hour;
584         stime.wMinute = tm->tm_min;
585         stime.wSecond = tm->tm_sec;
586
587         return SystemTimeToFileTime(&stime, ftime);
588 }
589
590 static void read_directory_unix(Entry* dir, LPCTSTR path)
591 {
592         Entry* first_entry = NULL;
593         Entry* last = NULL;
594         Entry* entry;
595         DIR* pdir;
596
597         int level = dir->level + 1;
598 #ifdef UNICODE
599         char cpath[MAX_PATH];
600
601         WideCharToMultiByte(CP_UNIXCP, 0, path, -1, cpath, MAX_PATH, NULL, NULL);
602 #else
603         const char* cpath = path;
604 #endif
605
606         pdir = opendir(cpath);
607
608         if (pdir) {
609                 struct stat st;
610                 struct dirent* ent;
611                 char buffer[MAX_PATH], *p;
612                 const char* s;
613
614                 for(p=buffer,s=cpath; *s; )
615                         *p++ = *s++;
616
617                 if (p==buffer || p[-1]!='/')
618                         *p++ = '/';
619
620                 while((ent=readdir(pdir))) {
621                         entry = alloc_entry();
622
623                         if (!first_entry)
624                                 first_entry = entry;
625
626                         if (last)
627                                 last->next = entry;
628
629                         entry->etype = ET_UNIX;
630
631                         strcpy(p, ent->d_name);
632 #ifdef UNICODE
633                         MultiByteToWideChar(CP_UNIXCP, 0, p, -1, entry->data.cFileName, MAX_PATH);
634 #else
635                         lstrcpy(entry->data.cFileName, p);
636 #endif
637
638                         if (!stat(buffer, &st)) {
639                                 entry->data.dwFileAttributes = p[0]=='.'? FILE_ATTRIBUTE_HIDDEN: 0;
640
641                                 if (S_ISDIR(st.st_mode))
642                                         entry->data.dwFileAttributes |= FILE_ATTRIBUTE_DIRECTORY;
643
644                                 entry->data.nFileSizeLow = st.st_size & 0xFFFFFFFF;
645                                 entry->data.nFileSizeHigh = st.st_size >> 32;
646
647                                 memset(&entry->data.ftCreationTime, 0, sizeof(FILETIME));
648                                 time_to_filetime(&st.st_atime, &entry->data.ftLastAccessTime);
649                                 time_to_filetime(&st.st_mtime, &entry->data.ftLastWriteTime);
650
651                                 entry->bhfi.nFileIndexLow = ent->d_ino;
652                                 entry->bhfi.nFileIndexHigh = 0;
653
654                                 entry->bhfi.nNumberOfLinks = st.st_nlink;
655
656                                 entry->bhfi_valid = TRUE;
657                         } else {
658                                 entry->data.nFileSizeLow = 0;
659                                 entry->data.nFileSizeHigh = 0;
660                                 entry->bhfi_valid = FALSE;
661                         }
662
663                         entry->down = NULL;
664                         entry->up = dir;
665                         entry->expanded = FALSE;
666                         entry->scanned = FALSE;
667                         entry->level = level;
668
669                         last = entry;
670                 }
671
672                 if (last)
673                         last->next = NULL;
674
675                 closedir(pdir);
676         }
677
678         dir->down = first_entry;
679         dir->scanned = TRUE;
680 }
681
682 static Entry* find_entry_unix(Entry* dir, LPCTSTR name)
683 {
684         Entry* entry;
685
686         for(entry=dir->down; entry; entry=entry->next) {
687                 LPCTSTR p = name;
688                 LPCTSTR q = entry->data.cFileName;
689
690                 do {
691                         if (!*p || *p == '/')
692                                 return entry;
693                 } while(*p++ == *q++);
694         }
695
696         return 0;
697 }
698
699 static Entry* read_tree_unix(Root* root, LPCTSTR path, SORT_ORDER sortOrder, HWND hwnd)
700 {
701         TCHAR buffer[MAX_PATH];
702         Entry* entry = &root->entry;
703         LPCTSTR s = path;
704         PTSTR d = buffer;
705
706         HCURSOR old_cursor = SetCursor(LoadCursor(0, IDC_WAIT));
707
708         entry->etype = ET_UNIX;
709
710         while(entry) {
711                 while(*s && *s != '/')
712                         *d++ = *s++;
713
714                 while(*s == '/')
715                         s++;
716
717                 *d++ = '/';
718                 *d = '\0';
719
720                 read_directory(entry, buffer, sortOrder, hwnd);
721
722                 if (entry->down)
723                         entry->expanded = TRUE;
724
725                 if (!*s)
726                         break;
727
728                 entry = find_entry_unix(entry, s);
729         }
730
731         SetCursor(old_cursor);
732
733         return entry;
734 }
735
736 #endif /* !defined(_NO_EXTENSIONS) && defined(__WINE__) */
737
738
739 #ifdef _SHELL_FOLDERS
740
741 #ifdef UNICODE
742 #define get_strret get_strretW
743 #define path_from_pidl path_from_pidlW
744 #else
745 #define get_strret get_strretA
746 #define path_from_pidl path_from_pidlA
747 #endif
748
749
750 static void free_strret(STRRET* str)
751 {
752         if (str->uType == STRRET_WSTR)
753                 IMalloc_Free(Globals.iMalloc, str->UNION_MEMBER(pOleStr));
754 }
755
756
757 #ifndef UNICODE
758
759 static LPSTR strcpyn(LPSTR dest, LPCSTR source, size_t count)
760 {
761  LPCSTR s;
762  LPSTR d = dest;
763
764  for(s=source; count&&(*d++=*s++); )
765   count--;
766
767  return dest;
768 }
769
770 static void get_strretA(STRRET* str, const SHITEMID* shiid, LPSTR buffer, int len)
771 {
772  switch(str->uType) {
773   case STRRET_WSTR:
774         WideCharToMultiByte(CP_ACP, 0, str->UNION_MEMBER(pOleStr), -1, buffer, len, NULL, NULL);
775         break;
776
777   case STRRET_OFFSET:
778         strcpyn(buffer, (LPCSTR)shiid+str->UNION_MEMBER(uOffset), len);
779         break;
780
781   case STRRET_CSTR:
782         strcpyn(buffer, str->UNION_MEMBER(cStr), len);
783  }
784 }
785
786 static HRESULT path_from_pidlA(IShellFolder* folder, LPITEMIDLIST pidl, LPSTR buffer, int len)
787 {
788         STRRET str;
789
790          /* SHGDN_FORPARSING: get full path of id list */
791         HRESULT hr = IShellFolder_GetDisplayNameOf(folder, pidl, SHGDN_FORPARSING, &str);
792
793         if (SUCCEEDED(hr)) {
794                 get_strretA(&str, &pidl->mkid, buffer, len);
795                 free_strret(&str);
796         } else
797                 buffer[0] = '\0';
798
799         return hr;
800 }
801
802 #endif
803
804 static LPWSTR wcscpyn(LPWSTR dest, LPCWSTR source, size_t count)
805 {
806  LPCWSTR s;
807  LPWSTR d = dest;
808
809  for(s=source; count&&(*d++=*s++); )
810   count--;
811
812  return dest;
813 }
814
815 static void get_strretW(STRRET* str, const SHITEMID* shiid, LPWSTR buffer, int len)
816 {
817  switch(str->uType) {
818   case STRRET_WSTR:
819         wcscpyn(buffer, str->UNION_MEMBER(pOleStr), len);
820         break;
821
822   case STRRET_OFFSET:
823         MultiByteToWideChar(CP_ACP, 0, (LPCSTR)shiid+str->UNION_MEMBER(uOffset), -1, buffer, len);
824         break;
825
826   case STRRET_CSTR:
827         MultiByteToWideChar(CP_ACP, 0, str->UNION_MEMBER(cStr), -1, buffer, len);
828  }
829 }
830
831
832 static HRESULT name_from_pidl(IShellFolder* folder, LPITEMIDLIST pidl, LPTSTR buffer, int len, SHGDNF flags)
833 {
834         STRRET str;
835
836         HRESULT hr = IShellFolder_GetDisplayNameOf(folder, pidl, flags, &str);
837
838         if (SUCCEEDED(hr)) {
839                 get_strret(&str, &pidl->mkid, buffer, len);
840                 free_strret(&str);
841         } else
842                 buffer[0] = '\0';
843
844         return hr;
845 }
846
847
848 static HRESULT path_from_pidlW(IShellFolder* folder, LPITEMIDLIST pidl, LPWSTR buffer, int len)
849 {
850         STRRET str;
851
852          /* SHGDN_FORPARSING: get full path of id list */
853         HRESULT hr = IShellFolder_GetDisplayNameOf(folder, pidl, SHGDN_FORPARSING, &str);
854
855         if (SUCCEEDED(hr)) {
856                 get_strretW(&str, &pidl->mkid, buffer, len);
857                 free_strret(&str);
858         } else
859                 buffer[0] = '\0';
860
861         return hr;
862 }
863
864
865  /* create an item id list from a file system path */
866
867 static LPITEMIDLIST get_path_pidl(LPTSTR path, HWND hwnd)
868 {
869         LPITEMIDLIST pidl;
870         HRESULT hr;
871         ULONG len;
872
873 #ifdef UNICODE
874         LPWSTR buffer = path;
875 #else
876         WCHAR buffer[MAX_PATH];
877         MultiByteToWideChar(CP_ACP, 0, path, -1, buffer, MAX_PATH);
878 #endif
879
880         hr = IShellFolder_ParseDisplayName(Globals.iDesktop, hwnd, NULL, buffer, &len, &pidl, NULL);
881         if (FAILED(hr))
882                 return NULL;
883
884         return pidl;
885 }
886
887
888  /* convert an item id list from relative to absolute (=relative to the desktop) format */
889
890 static LPITEMIDLIST get_to_absolute_pidl(Entry* entry, HWND hwnd)
891 {
892         if (entry->up && entry->up->etype==ET_SHELL) {
893                 IShellFolder* folder = entry->up->folder;
894                 WCHAR buffer[MAX_PATH];
895
896                 HRESULT hr = path_from_pidlW(folder, entry->pidl, buffer, MAX_PATH);
897
898                 if (SUCCEEDED(hr)) {
899                         LPITEMIDLIST pidl;
900                         ULONG len;
901
902                         hr = IShellFolder_ParseDisplayName(Globals.iDesktop, hwnd, NULL, buffer, &len, &pidl, NULL);
903
904                         if (SUCCEEDED(hr))
905                                 return pidl;
906                 }
907         } else if (entry->etype == ET_WINDOWS) {
908                 TCHAR path[MAX_PATH];
909
910                 get_path(entry, path);
911
912                 return get_path_pidl(path, hwnd);
913         } else if (entry->pidl)
914                 return ILClone(entry->pidl);
915
916         return NULL;
917 }
918
919
920 static HICON extract_icon(IShellFolder* folder, LPCITEMIDLIST pidl)
921 {
922         IExtractIcon* pExtract;
923
924         if (SUCCEEDED(IShellFolder_GetUIObjectOf(folder, 0, 1, (LPCITEMIDLIST*)&pidl, &IID_IExtractIcon, 0, (LPVOID*)&pExtract))) {
925                 TCHAR path[_MAX_PATH];
926                 unsigned flags;
927                 HICON hicon;
928                 int idx;
929
930                 if (SUCCEEDED(IExtractIconW_GetIconLocation(pExtract, GIL_FORSHELL, path, _MAX_PATH, &idx, &flags))) {
931                         if (!(flags & GIL_NOTFILENAME)) {
932                                 if (idx == -1)
933                                         idx = 0;        /* special case for some control panel applications */
934
935                                 if ((int)ExtractIconEx(path, idx, 0, &hicon, 1) > 0)
936                                         flags &= ~GIL_DONTCACHE;
937                         } else {
938                                 HICON hIconLarge = 0;
939
940                                 HRESULT hr = IExtractIconW_Extract(pExtract, path, idx, &hIconLarge, &hicon, MAKELONG(0/*GetSystemMetrics(SM_CXICON)*/,GetSystemMetrics(SM_CXSMICON)));
941
942                                 if (SUCCEEDED(hr))
943                                         DestroyIcon(hIconLarge);
944                         }
945
946                         return hicon;
947                 }
948         }
949
950         return 0;
951 }
952
953
954 static Entry* find_entry_shell(Entry* dir, LPCITEMIDLIST pidl)
955 {
956         Entry* entry;
957
958         for(entry=dir->down; entry; entry=entry->next) {
959                 if (entry->pidl->mkid.cb == pidl->mkid.cb &&
960                         !memcmp(entry->pidl, pidl, entry->pidl->mkid.cb))
961                         return entry;
962         }
963
964         return 0;
965 }
966
967 static Entry* read_tree_shell(Root* root, LPITEMIDLIST pidl, SORT_ORDER sortOrder, HWND hwnd)
968 {
969         Entry* entry = &root->entry;
970         Entry* next;
971         LPITEMIDLIST next_pidl = pidl;
972         IShellFolder* folder;
973         IShellFolder* child = NULL;
974         HRESULT hr;
975
976         HCURSOR old_cursor = SetCursor(LoadCursor(0, IDC_WAIT));
977
978 #ifndef _NO_EXTENSIONS
979         entry->etype = ET_SHELL;
980 #endif
981
982         folder = Globals.iDesktop;
983
984         while(entry) {
985                 entry->pidl = next_pidl;
986                 entry->folder = folder;
987
988                 if (!pidl->mkid.cb)
989                         break;
990
991                  /* copy first element of item idlist */
992                 next_pidl = IMalloc_Alloc(Globals.iMalloc, pidl->mkid.cb+sizeof(USHORT));
993                 memcpy(next_pidl, pidl, pidl->mkid.cb);
994                 ((LPITEMIDLIST)((LPBYTE)next_pidl+pidl->mkid.cb))->mkid.cb = 0;
995
996                 hr = IShellFolder_BindToObject(folder, next_pidl, 0, &IID_IShellFolder, (void**)&child);
997                 if (!SUCCEEDED(hr))
998                         break;
999
1000                 read_directory(entry, NULL, sortOrder, hwnd);
1001
1002                 if (entry->down)
1003                         entry->expanded = TRUE;
1004
1005                 next = find_entry_shell(entry, next_pidl);
1006                 if (!next)
1007                         break;
1008
1009                 folder = child;
1010                 entry = next;
1011
1012                  /* go to next element */
1013                 pidl = (LPITEMIDLIST) ((LPBYTE)pidl+pidl->mkid.cb);
1014         }
1015
1016         SetCursor(old_cursor);
1017
1018         return entry;
1019 }
1020
1021
1022 static void fill_w32fdata_shell(IShellFolder* folder, LPCITEMIDLIST pidl, SFGAOF attribs, WIN32_FIND_DATA* w32fdata)
1023 {
1024         if (!(attribs & SFGAO_FILESYSTEM) ||
1025                   FAILED(SHGetDataFromIDList(folder, pidl, SHGDFIL_FINDDATA, w32fdata, sizeof(WIN32_FIND_DATA)))) {
1026                 WIN32_FILE_ATTRIBUTE_DATA fad;
1027                 IDataObject* pDataObj;
1028
1029                 STGMEDIUM medium = {0, {0}, 0};
1030                 FORMATETC fmt = {Globals.cfStrFName, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL};
1031
1032                 HRESULT hr = IShellFolder_GetUIObjectOf(folder, 0, 1, &pidl, &IID_IDataObject, 0, (LPVOID*)&pDataObj);
1033
1034                 if (SUCCEEDED(hr)) {
1035                         hr = IDataObject_GetData(pDataObj, &fmt, &medium);
1036
1037                         IDataObject_Release(pDataObj);
1038
1039                         if (SUCCEEDED(hr)) {
1040                                 LPCTSTR path = (LPCTSTR)GlobalLock(medium.UNION_MEMBER(hGlobal));
1041                                 UINT sem_org = SetErrorMode(SEM_FAILCRITICALERRORS);
1042
1043                                 if (GetFileAttributesEx(path, GetFileExInfoStandard, &fad)) {
1044                                         w32fdata->dwFileAttributes = fad.dwFileAttributes;
1045                                         w32fdata->ftCreationTime = fad.ftCreationTime;
1046                                         w32fdata->ftLastAccessTime = fad.ftLastAccessTime;
1047                                         w32fdata->ftLastWriteTime = fad.ftLastWriteTime;
1048
1049                                         if (!(fad.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
1050                                                 w32fdata->nFileSizeLow = fad.nFileSizeLow;
1051                                                 w32fdata->nFileSizeHigh = fad.nFileSizeHigh;
1052                                         }
1053                                 }
1054
1055                                 SetErrorMode(sem_org);
1056
1057                                 GlobalUnlock(medium.UNION_MEMBER(hGlobal));
1058                                 GlobalFree(medium.UNION_MEMBER(hGlobal));
1059                         }
1060                 }
1061         }
1062
1063         if (attribs & (SFGAO_FOLDER|SFGAO_HASSUBFOLDER))
1064                 w32fdata->dwFileAttributes |= FILE_ATTRIBUTE_DIRECTORY;
1065
1066         if (attribs & SFGAO_READONLY)
1067                 w32fdata->dwFileAttributes |= FILE_ATTRIBUTE_READONLY;
1068
1069         if (attribs & SFGAO_COMPRESSED)
1070                 w32fdata->dwFileAttributes |= FILE_ATTRIBUTE_COMPRESSED;
1071 }
1072
1073
1074 static void read_directory_shell(Entry* dir, HWND hwnd)
1075 {
1076         IShellFolder* folder = dir->folder;
1077         int level = dir->level + 1;
1078         HRESULT hr;
1079
1080         IShellFolder* child;
1081         IEnumIDList* idlist;
1082
1083         Entry* first_entry = NULL;
1084         Entry* last = NULL;
1085         Entry* entry;
1086
1087         if (!folder)
1088                 return;
1089
1090         hr = IShellFolder_EnumObjects(folder, hwnd, SHCONTF_FOLDERS|SHCONTF_NONFOLDERS|SHCONTF_INCLUDEHIDDEN|SHCONTF_SHAREABLE|SHCONTF_STORAGE, &idlist);
1091
1092         if (SUCCEEDED(hr)) {
1093                 for(;;) {
1094 #define FETCH_ITEM_COUNT        32
1095                         LPITEMIDLIST pidls[FETCH_ITEM_COUNT];
1096                         SFGAOF attribs;
1097                         ULONG cnt = 0;
1098                         ULONG n;
1099
1100                         memset(pidls, 0, sizeof(pidls));
1101
1102                         hr = IEnumIDList_Next(idlist, FETCH_ITEM_COUNT, pidls, &cnt);
1103                         if (!SUCCEEDED(hr))
1104                                 break;
1105
1106                         if (hr == S_FALSE)
1107                                 break;
1108
1109                         for(n=0; n<cnt; ++n) {
1110                                 entry = alloc_entry();
1111
1112                                 if (!first_entry)
1113                                         first_entry = entry;
1114
1115                                 if (last)
1116                                         last->next = entry;
1117
1118                                 memset(&entry->data, 0, sizeof(WIN32_FIND_DATA));
1119                                 entry->bhfi_valid = FALSE;
1120
1121                                 attribs = ~SFGAO_FILESYSTEM;    /*SFGAO_HASSUBFOLDER|SFGAO_FOLDER; SFGAO_FILESYSTEM sorgt dafür, daß "My Documents" anstatt von "Martin's Documents" angezeigt wird */
1122
1123                                 hr = IShellFolder_GetAttributesOf(folder, 1, (LPCITEMIDLIST*)&pidls[n], &attribs);
1124
1125                                 if (SUCCEEDED(hr)) {
1126                                         if (attribs != (SFGAOF)~SFGAO_FILESYSTEM) {
1127                                                 fill_w32fdata_shell(folder, pidls[n], attribs, &entry->data);
1128
1129                                                 entry->bhfi_valid = TRUE;
1130                                         } else
1131                                                 attribs = 0;
1132                                 } else
1133                                         attribs = 0;
1134
1135                                 entry->pidl = pidls[n];
1136
1137                                 if (entry->data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
1138                                         hr = IShellFolder_BindToObject(folder, pidls[n], 0, &IID_IShellFolder, (void**)&child);
1139
1140                                         if (SUCCEEDED(hr))
1141                                                 entry->folder = child;
1142                                         else
1143                                                 entry->folder = NULL;
1144                                 }
1145                                 else
1146                                         entry->folder = NULL;
1147
1148                                 if (!entry->data.cFileName[0])
1149                                         /*hr = */name_from_pidl(folder, pidls[n], entry->data.cFileName, MAX_PATH, /*SHGDN_INFOLDER*/0x2000/*0x2000=SHGDN_INCLUDE_NONFILESYS*/);
1150
1151                                  /* get display icons for files and virtual objects */
1152                                 if (!(entry->data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ||
1153                                         !(attribs & SFGAO_FILESYSTEM)) {
1154                                         entry->hicon = extract_icon(folder, pidls[n]);
1155
1156                                         if (!entry->hicon)
1157                                                 entry->hicon = (HICON)-1;       /* don't try again later */
1158                                 }
1159
1160                                 entry->down = NULL;
1161                                 entry->up = dir;
1162                                 entry->expanded = FALSE;
1163                                 entry->scanned = FALSE;
1164                                 entry->level = level;
1165
1166 #ifndef _NO_EXTENSIONS
1167                                 entry->etype = ET_SHELL;
1168                                 entry->bhfi_valid = FALSE;
1169 #endif
1170
1171                                 last = entry;
1172                         }
1173                 }
1174
1175                 IEnumIDList_Release(idlist);
1176         }
1177
1178         if (last)
1179                 last->next = NULL;
1180
1181         dir->down = first_entry;
1182         dir->scanned = TRUE;
1183 }
1184
1185 #endif /* _SHELL_FOLDERS */
1186
1187
1188 /* sort order for different directory/file types */
1189 enum TYPE_ORDER {
1190         TO_DIR = 0,
1191         TO_DOT = 1,
1192         TO_DOTDOT = 2,
1193         TO_OTHER_DIR = 3,
1194         TO_FILE = 4
1195 };
1196
1197 /* distinguish between ".", ".." and any other directory names */
1198 static int TypeOrderFromDirname(LPCTSTR name)
1199 {
1200         if (name[0] == '.') {
1201                 if (name[1] == '\0')
1202                         return TO_DOT;  /* "." */
1203
1204                 if (name[1]=='.' && name[2]=='\0')
1205                         return TO_DOTDOT;       /* ".." */
1206         }
1207
1208         return TO_OTHER_DIR;    /* anything else */
1209 }
1210
1211 /* directories first... */
1212 static int compareType(const WIN32_FIND_DATA* fd1, const WIN32_FIND_DATA* fd2)
1213 {
1214         int order1 = fd1->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY? TO_DIR: TO_FILE;
1215         int order2 = fd2->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY? TO_DIR: TO_FILE;
1216
1217         /* Handle "." and ".." as special case and move them at the very first beginning. */
1218         if (order1==TO_DIR && order2==TO_DIR) {
1219                 order1 = TypeOrderFromDirname(fd1->cFileName);
1220                 order2 = TypeOrderFromDirname(fd2->cFileName);
1221         }
1222
1223         return order2==order1? 0: order1<order2? -1: 1;
1224 }
1225
1226
1227 static int compareName(const void* arg1, const void* arg2)
1228 {
1229         const WIN32_FIND_DATA* fd1 = &(*(const Entry* const*)arg1)->data;
1230         const WIN32_FIND_DATA* fd2 = &(*(const Entry* const*)arg2)->data;
1231
1232         int cmp = compareType(fd1, fd2);
1233         if (cmp)
1234                 return cmp;
1235
1236         return lstrcmpi(fd1->cFileName, fd2->cFileName);
1237 }
1238
1239 static int compareExt(const void* arg1, const void* arg2)
1240 {
1241         const WIN32_FIND_DATA* fd1 = &(*(const Entry* const*)arg1)->data;
1242         const WIN32_FIND_DATA* fd2 = &(*(const Entry* const*)arg2)->data;
1243         const TCHAR *name1, *name2, *ext1, *ext2;
1244
1245         int cmp = compareType(fd1, fd2);
1246         if (cmp)
1247                 return cmp;
1248
1249         name1 = fd1->cFileName;
1250         name2 = fd2->cFileName;
1251
1252         ext1 = _tcsrchr(name1, '.');
1253         ext2 = _tcsrchr(name2, '.');
1254
1255         if (ext1)
1256                 ext1++;
1257         else
1258                 ext1 = sEmpty;
1259
1260         if (ext2)
1261                 ext2++;
1262         else
1263                 ext2 = sEmpty;
1264
1265         cmp = lstrcmpi(ext1, ext2);
1266         if (cmp)
1267                 return cmp;
1268
1269         return lstrcmpi(name1, name2);
1270 }
1271
1272 static int compareSize(const void* arg1, const void* arg2)
1273 {
1274         const WIN32_FIND_DATA* fd1 = &(*(const Entry* const*)arg1)->data;
1275         const WIN32_FIND_DATA* fd2 = &(*(const Entry* const*)arg2)->data;
1276
1277         int cmp = compareType(fd1, fd2);
1278         if (cmp)
1279                 return cmp;
1280
1281         cmp = fd2->nFileSizeHigh - fd1->nFileSizeHigh;
1282
1283         if (cmp < 0)
1284                 return -1;
1285         else if (cmp > 0)
1286                 return 1;
1287
1288         cmp = fd2->nFileSizeLow - fd1->nFileSizeLow;
1289
1290         return cmp<0? -1: cmp>0? 1: 0;
1291 }
1292
1293 static int compareDate(const void* arg1, const void* arg2)
1294 {
1295         const WIN32_FIND_DATA* fd1 = &(*(const Entry* const*)arg1)->data;
1296         const WIN32_FIND_DATA* fd2 = &(*(const Entry* const*)arg2)->data;
1297
1298         int cmp = compareType(fd1, fd2);
1299         if (cmp)
1300                 return cmp;
1301
1302         return CompareFileTime(&fd2->ftLastWriteTime, &fd1->ftLastWriteTime);
1303 }
1304
1305
1306 static int (*sortFunctions[])(const void* arg1, const void* arg2) = {
1307         compareName,    /* SORT_NAME */
1308         compareExt,             /* SORT_EXT */
1309         compareSize,    /* SORT_SIZE */
1310         compareDate             /* SORT_DATE */
1311 };
1312
1313
1314 static void SortDirectory(Entry* dir, SORT_ORDER sortOrder)
1315 {
1316         Entry* entry = dir->down;
1317         Entry** array, **p;
1318         int len;
1319
1320         len = 0;
1321         for(entry=dir->down; entry; entry=entry->next)
1322                 len++;
1323
1324         if (len) {
1325                 array = HeapAlloc(GetProcessHeap(), 0, len*sizeof(Entry*));
1326
1327                 p = array;
1328                 for(entry=dir->down; entry; entry=entry->next)
1329                         *p++ = entry;
1330
1331                 /* call qsort with the appropriate compare function */
1332                 qsort(array, len, sizeof(array[0]), sortFunctions[sortOrder]);
1333
1334                 dir->down = array[0];
1335
1336                 for(p=array; --len; p++)
1337                         p[0]->next = p[1];
1338
1339                 (*p)->next = 0;
1340
1341                 HeapFree(GetProcessHeap(), 0, array);
1342         }
1343 }
1344
1345
1346 static void read_directory(Entry* dir, LPCTSTR path, SORT_ORDER sortOrder, HWND hwnd)
1347 {
1348         TCHAR buffer[MAX_PATH];
1349         Entry* entry;
1350         LPCTSTR s;
1351         PTSTR d;
1352
1353 #ifdef _SHELL_FOLDERS
1354         if (dir->etype == ET_SHELL)
1355         {
1356                 read_directory_shell(dir, hwnd);
1357
1358                 if (Globals.prescan_node) {
1359                         s = path;
1360                         d = buffer;
1361
1362                         while(*s)
1363                                 *d++ = *s++;
1364
1365                         *d++ = '\\';
1366
1367                         for(entry=dir->down; entry; entry=entry->next)
1368                                 if (entry->data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
1369                                         read_directory_shell(entry, hwnd);
1370                                         SortDirectory(entry, sortOrder);
1371                                 }
1372                 }
1373         }
1374         else
1375 #endif
1376 #if !defined(_NO_EXTENSIONS) && defined(__WINE__)
1377         if (dir->etype == ET_UNIX)
1378         {
1379                 read_directory_unix(dir, path);
1380
1381                 if (Globals.prescan_node) {
1382                         s = path;
1383                         d = buffer;
1384
1385                         while(*s)
1386                                 *d++ = *s++;
1387
1388                         *d++ = '/';
1389
1390                         for(entry=dir->down; entry; entry=entry->next)
1391                                 if (entry->data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
1392                                         lstrcpy(d, entry->data.cFileName);
1393                                         read_directory_unix(entry, buffer);
1394                                         SortDirectory(entry, sortOrder);
1395                                 }
1396                 }
1397         }
1398         else
1399 #endif
1400         {
1401                 read_directory_win(dir, path);
1402
1403                 if (Globals.prescan_node) {
1404                         s = path;
1405                         d = buffer;
1406
1407                         while(*s)
1408                                 *d++ = *s++;
1409
1410                         *d++ = '\\';
1411
1412                         for(entry=dir->down; entry; entry=entry->next)
1413                                 if (entry->data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
1414                                         lstrcpy(d, entry->data.cFileName);
1415                                         read_directory_win(entry, buffer);
1416                                         SortDirectory(entry, sortOrder);
1417                                 }
1418                 }
1419         }
1420
1421         SortDirectory(dir, sortOrder);
1422 }
1423
1424
1425 static Entry* read_tree(Root* root, LPCTSTR path, LPITEMIDLIST pidl, LPTSTR drv, SORT_ORDER sortOrder, HWND hwnd)
1426 {
1427 #if !defined(_NO_EXTENSIONS) && defined(__WINE__)
1428         static const TCHAR sSlash[] = {'/', '\0'};
1429 #endif
1430         static const TCHAR sBackslash[] = {'\\', '\0'};
1431
1432 #ifdef _SHELL_FOLDERS
1433         if (pidl)
1434         {
1435                  /* read shell namespace tree */
1436                 root->drive_type = DRIVE_UNKNOWN;
1437                 drv[0] = '\\';
1438                 drv[1] = '\0';
1439                 load_string(root->volname, IDS_DESKTOP);
1440                 root->fs_flags = 0;
1441                 load_string(root->fs, IDS_SHELL);
1442
1443                 return read_tree_shell(root, pidl, sortOrder, hwnd);
1444         }
1445         else
1446 #endif
1447 #if !defined(_NO_EXTENSIONS) && defined(__WINE__)
1448         if (*path == '/')
1449         {
1450                  /* read unix file system tree */
1451                 root->drive_type = GetDriveType(path);
1452
1453                 lstrcat(drv, sSlash);
1454                 load_string(root->volname, IDS_ROOT_FS);
1455                 root->fs_flags = 0;
1456                 load_string(root->fs, IDS_UNIXFS);
1457
1458                 lstrcpy(root->path, sSlash);
1459
1460                 return read_tree_unix(root, path, sortOrder, hwnd);
1461         }
1462 #endif
1463
1464          /* read WIN32 file system tree */
1465         root->drive_type = GetDriveType(path);
1466
1467         lstrcat(drv, sBackslash);
1468         GetVolumeInformation(drv, root->volname, _MAX_FNAME, 0, 0, &root->fs_flags, root->fs, _MAX_DIR);
1469
1470         lstrcpy(root->path, drv);
1471
1472         return read_tree_win(root, path, sortOrder, hwnd);
1473 }
1474
1475
1476 /* flags to filter different file types */
1477 enum TYPE_FILTER {
1478         TF_DIRECTORIES  = 0x01,
1479         TF_PROGRAMS             = 0x02,
1480         TF_DOCUMENTS    = 0x04,
1481         TF_OTHERS               = 0x08,
1482         TF_HIDDEN               = 0x10,
1483         TF_ALL                  = 0x1F
1484 };
1485
1486
1487 static ChildWnd* alloc_child_window(LPCTSTR path, LPITEMIDLIST pidl, HWND hwnd)
1488 {
1489         TCHAR drv[_MAX_DRIVE+1], dir[_MAX_DIR], name[_MAX_FNAME], ext[_MAX_EXT];
1490         TCHAR dir_path[MAX_PATH];
1491         TCHAR b1[BUFFER_LEN];
1492         static const TCHAR sAsterics[] = {'*', '\0'};
1493
1494         ChildWnd* child = HeapAlloc(GetProcessHeap(), 0, sizeof(ChildWnd));
1495         Root* root = &child->root;
1496         Entry* entry;
1497
1498         memset(child, 0, sizeof(ChildWnd));
1499
1500         child->left.treePane = TRUE;
1501         child->left.visible_cols = 0;
1502
1503         child->right.treePane = FALSE;
1504 #ifndef _NO_EXTENSIONS
1505         child->right.visible_cols = COL_SIZE|COL_DATE|COL_TIME|COL_ATTRIBUTES|COL_INDEX|COL_LINKS;
1506 #else
1507         child->right.visible_cols = COL_SIZE|COL_DATE|COL_TIME|COL_ATTRIBUTES;
1508 #endif
1509
1510         child->pos.length = sizeof(WINDOWPLACEMENT);
1511         child->pos.flags = 0;
1512         child->pos.showCmd = SW_SHOWNORMAL;
1513         child->pos.rcNormalPosition.left = CW_USEDEFAULT;
1514         child->pos.rcNormalPosition.top = CW_USEDEFAULT;
1515         child->pos.rcNormalPosition.right = CW_USEDEFAULT;
1516         child->pos.rcNormalPosition.bottom = CW_USEDEFAULT;
1517
1518         child->focus_pane = 0;
1519         child->split_pos = DEFAULT_SPLIT_POS;
1520         child->sortOrder = SORT_NAME;
1521         child->header_wdths_ok = FALSE;
1522
1523         if (path)
1524         {
1525                 lstrcpy(child->path, path);
1526
1527                 _tsplitpath(path, drv, dir, name, ext);
1528         }
1529
1530         lstrcpy(child->filter_pattern, sAsterics);
1531         child->filter_flags = TF_ALL;
1532
1533         root->entry.level = 0;
1534
1535         lstrcpy(dir_path, drv);
1536         lstrcat(dir_path, dir);
1537         entry = read_tree(root, dir_path, pidl, drv, child->sortOrder, hwnd);
1538
1539 #ifdef _SHELL_FOLDERS
1540         if (root->entry.etype == ET_SHELL)
1541                 load_string(root->entry.data.cFileName, IDS_DESKTOP);
1542         else
1543 #endif
1544                 wsprintf(root->entry.data.cFileName, RS(b1,IDS_TITLEFMT), drv, root->fs);
1545
1546         root->entry.data.dwFileAttributes = FILE_ATTRIBUTE_DIRECTORY;
1547
1548         child->left.root = &root->entry;
1549         child->right.root = NULL;
1550
1551         set_curdir(child, entry, 0, hwnd);
1552
1553         return child;
1554 }
1555
1556
1557 /* free all memory associated with a child window */
1558 static void free_child_window(ChildWnd* child)
1559 {
1560         free_entries(&child->root.entry);
1561         HeapFree(GetProcessHeap(), 0, child);
1562 }
1563
1564
1565 /* get full path of specified directory entry */
1566 static void get_path(Entry* dir, PTSTR path)
1567 {
1568         Entry* entry;
1569         int len = 0;
1570         int level = 0;
1571
1572 #ifdef _SHELL_FOLDERS
1573         if (dir->etype == ET_SHELL)
1574         {
1575                 SFGAOF attribs;
1576                 HRESULT hr = S_OK;
1577
1578                 path[0] = '\0';
1579
1580                 attribs = 0;
1581
1582                 if (dir->folder)
1583                         hr = IShellFolder_GetAttributesOf(dir->folder, 1, (LPCITEMIDLIST*)&dir->pidl, &attribs);
1584
1585                 if (SUCCEEDED(hr) && (attribs&SFGAO_FILESYSTEM)) {
1586                         IShellFolder* parent = dir->up? dir->up->folder: Globals.iDesktop;
1587
1588                         hr = path_from_pidl(parent, dir->pidl, path, MAX_PATH);
1589                 }
1590         }
1591         else
1592 #endif
1593         {
1594                 for(entry=dir; entry; level++) {
1595                         LPCTSTR name;
1596                         int l;
1597
1598                         {
1599                                 LPCTSTR s;
1600                                 name = entry->data.cFileName;
1601                                 s = name;
1602
1603                                 for(l=0; *s && *s != '/' && *s != '\\'; s++)
1604                                         l++;
1605                         }
1606
1607                         if (entry->up) {
1608                                 if (l > 0) {
1609                                         memmove(path+l+1, path, len*sizeof(TCHAR));
1610                                         memcpy(path+1, name, l*sizeof(TCHAR));
1611                                         len += l+1;
1612
1613 #ifndef _NO_EXTENSIONS
1614                                         if (entry->etype == ET_UNIX)
1615                                                 path[0] = '/';
1616                                         else
1617 #endif
1618                                         path[0] = '\\';
1619                                 }
1620
1621                                 entry = entry->up;
1622                         } else {
1623                                 memmove(path+l, path, len*sizeof(TCHAR));
1624                                 memcpy(path, name, l*sizeof(TCHAR));
1625                                 len += l;
1626                                 break;
1627                         }
1628                 }
1629
1630                 if (!level) {
1631 #ifndef _NO_EXTENSIONS
1632                         if (entry->etype == ET_UNIX)
1633                                 path[len++] = '/';
1634                         else
1635 #endif
1636                                 path[len++] = '\\';
1637                 }
1638
1639                 path[len] = '\0';
1640         }
1641 }
1642
1643 static windowOptions load_registry_settings(void)
1644 {
1645         DWORD size;
1646         DWORD type;
1647         HKEY hKey;
1648         windowOptions opts;
1649         LOGFONT logfont;
1650
1651         RegOpenKeyExW( HKEY_CURRENT_USER, registry_key,
1652                        0, KEY_QUERY_VALUE, &hKey );
1653
1654         size = sizeof(DWORD);
1655
1656         if( RegQueryValueExW( hKey, reg_start_x, NULL, &type,
1657                               (LPBYTE) &opts.start_x, &size ) != ERROR_SUCCESS )
1658                 opts.start_x = CW_USEDEFAULT;
1659
1660         if( RegQueryValueExW( hKey, reg_start_y, NULL, &type,
1661                               (LPBYTE) &opts.start_y, &size ) != ERROR_SUCCESS )
1662                 opts.start_y = CW_USEDEFAULT;
1663
1664         if( RegQueryValueExW( hKey, reg_width, NULL, &type,
1665                               (LPBYTE) &opts.width, &size ) != ERROR_SUCCESS )
1666                 opts.width = CW_USEDEFAULT;
1667
1668         if( RegQueryValueExW( hKey, reg_height, NULL, &type,
1669                               (LPBYTE) &opts.height, &size ) != ERROR_SUCCESS )
1670                 opts.height = CW_USEDEFAULT;
1671         size=sizeof(logfont);
1672         if( RegQueryValueExW( hKey, reg_logfont, NULL, &type,
1673                               (LPBYTE) &logfont, &size ) != ERROR_SUCCESS )
1674                 GetObject(GetStockObject(DEFAULT_GUI_FONT),sizeof(logfont),&logfont);
1675
1676         RegCloseKey( hKey );
1677
1678         Globals.hfont = CreateFontIndirect(&logfont);
1679         return opts;
1680 }
1681
1682 static void save_registry_settings(void)
1683 {
1684         WINDOWINFO wi;
1685         HKEY hKey;
1686         INT width, height;
1687         LOGFONT logfont;
1688
1689         wi.cbSize = sizeof( WINDOWINFO );
1690         GetWindowInfo(Globals.hMainWnd, &wi);
1691         width = wi.rcWindow.right - wi.rcWindow.left;
1692         height = wi.rcWindow.bottom - wi.rcWindow.top;
1693
1694         if ( RegOpenKeyExW( HKEY_CURRENT_USER, registry_key,
1695                             0, KEY_SET_VALUE, &hKey ) != ERROR_SUCCESS )
1696         {
1697                 /* Unable to save registry settings - try to create key */
1698                 if ( RegCreateKeyExW( HKEY_CURRENT_USER, registry_key,
1699                                       0, NULL, REG_OPTION_NON_VOLATILE,
1700                                       KEY_SET_VALUE, NULL, &hKey, NULL ) != ERROR_SUCCESS )
1701                 {
1702                         /* FIXME: Cannot create key */
1703                         return;
1704                 }
1705         }
1706         /* Save all of the settings */
1707         RegSetValueExW( hKey, reg_start_x, 0, REG_DWORD,
1708                         (LPBYTE) &wi.rcWindow.left, sizeof(DWORD) );
1709         RegSetValueExW( hKey, reg_start_y, 0, REG_DWORD,
1710                         (LPBYTE) &wi.rcWindow.top, sizeof(DWORD) );
1711         RegSetValueExW( hKey, reg_width, 0, REG_DWORD,
1712                         (LPBYTE) &width, sizeof(DWORD) );
1713         RegSetValueExW( hKey, reg_height, 0, REG_DWORD,
1714                         (LPBYTE) &height, sizeof(DWORD) );
1715         GetObject(Globals.hfont, sizeof(logfont), &logfont);
1716         RegSetValueExW( hKey, reg_logfont, 0, REG_BINARY,
1717                         (LPBYTE) &logfont, sizeof(LOGFONT) );
1718
1719         /* TODO: Save more settings here (List vs. Detailed View, etc.) */
1720         RegCloseKey( hKey );
1721 }
1722
1723 static void resize_frame_rect(HWND hwnd, PRECT prect)
1724 {
1725         int new_top;
1726         RECT rt;
1727
1728         if (IsWindowVisible(Globals.htoolbar)) {
1729                 SendMessage(Globals.htoolbar, WM_SIZE, 0, 0);
1730                 GetClientRect(Globals.htoolbar, &rt);
1731                 prect->top = rt.bottom+3;
1732                 prect->bottom -= rt.bottom+3;
1733         }
1734
1735         if (IsWindowVisible(Globals.hdrivebar)) {
1736                 SendMessage(Globals.hdrivebar, WM_SIZE, 0, 0);
1737                 GetClientRect(Globals.hdrivebar, &rt);
1738                 new_top = --prect->top + rt.bottom+3;
1739                 MoveWindow(Globals.hdrivebar, 0, prect->top, rt.right, new_top, TRUE);
1740                 prect->top = new_top;
1741                 prect->bottom -= rt.bottom+2;
1742         }
1743
1744         if (IsWindowVisible(Globals.hstatusbar)) {
1745                 int parts[] = {300, 500};
1746
1747                 SendMessage(Globals.hstatusbar, WM_SIZE, 0, 0);
1748                 SendMessage(Globals.hstatusbar, SB_SETPARTS, 2, (LPARAM)&parts);
1749                 GetClientRect(Globals.hstatusbar, &rt);
1750                 prect->bottom -= rt.bottom;
1751         }
1752
1753         MoveWindow(Globals.hmdiclient, prect->left-1,prect->top-1,prect->right+2,prect->bottom+1, TRUE);
1754 }
1755
1756 static void resize_frame(HWND hwnd, int cx, int cy)
1757 {
1758         RECT rect;
1759
1760         rect.left   = 0;
1761         rect.top    = 0;
1762         rect.right  = cx;
1763         rect.bottom = cy;
1764
1765         resize_frame_rect(hwnd, &rect);
1766 }
1767
1768 static void resize_frame_client(HWND hwnd)
1769 {
1770         RECT rect;
1771
1772         GetClientRect(hwnd, &rect);
1773
1774         resize_frame_rect(hwnd, &rect);
1775 }
1776
1777
1778 static HHOOK hcbthook;
1779 static ChildWnd* newchild = NULL;
1780
1781 static LRESULT CALLBACK CBTProc(int code, WPARAM wparam, LPARAM lparam)
1782 {
1783         if (code==HCBT_CREATEWND && newchild) {
1784                 ChildWnd* child = newchild;
1785                 newchild = NULL;
1786
1787                 child->hwnd = (HWND) wparam;
1788                 SetWindowLongPtr(child->hwnd, GWLP_USERDATA, (LPARAM)child);
1789         }
1790
1791         return CallNextHookEx(hcbthook, code, wparam, lparam);
1792 }
1793
1794 static HWND create_child_window(ChildWnd* child)
1795 {
1796         MDICREATESTRUCT mcs;
1797         int idx;
1798
1799         mcs.szClass = sWINEFILETREE;
1800         mcs.szTitle = (LPTSTR)child->path;
1801         mcs.hOwner  = Globals.hInstance;
1802         mcs.x       = child->pos.rcNormalPosition.left;
1803         mcs.y       = child->pos.rcNormalPosition.top;
1804         mcs.cx      = child->pos.rcNormalPosition.right-child->pos.rcNormalPosition.left;
1805         mcs.cy      = child->pos.rcNormalPosition.bottom-child->pos.rcNormalPosition.top;
1806         mcs.style   = 0;
1807         mcs.lParam  = 0;
1808
1809         hcbthook = SetWindowsHookEx(WH_CBT, CBTProc, 0, GetCurrentThreadId());
1810
1811         newchild = child;
1812         child->hwnd = (HWND) SendMessage(Globals.hmdiclient, WM_MDICREATE, 0, (LPARAM)&mcs);
1813         if (!child->hwnd) {
1814                 UnhookWindowsHookEx(hcbthook);
1815                 return 0;
1816         }
1817
1818         UnhookWindowsHookEx(hcbthook);
1819
1820         SendMessage(child->left.hwnd, LB_SETITEMHEIGHT, 1, max(Globals.spaceSize.cy,IMAGE_HEIGHT+3));
1821         SendMessage(child->right.hwnd, LB_SETITEMHEIGHT, 1, max(Globals.spaceSize.cy,IMAGE_HEIGHT+3));
1822
1823         idx = SendMessage(child->left.hwnd, LB_FINDSTRING, 0, (LPARAM)child->left.cur);
1824         SendMessage(child->left.hwnd, LB_SETCURSEL, idx, 0);
1825
1826         return child->hwnd;
1827 }
1828
1829
1830 struct ExecuteDialog {
1831         TCHAR   cmd[MAX_PATH];
1832         int             cmdshow;
1833 };
1834
1835 static INT_PTR CALLBACK ExecuteDialogDlgProc(HWND hwnd, UINT nmsg, WPARAM wparam, LPARAM lparam)
1836 {
1837         static struct ExecuteDialog* dlg;
1838
1839         switch(nmsg) {
1840                 case WM_INITDIALOG:
1841                         dlg = (struct ExecuteDialog*) lparam;
1842                         return 1;
1843
1844                 case WM_COMMAND: {
1845                         int id = (int)wparam;
1846
1847                         if (id == IDOK) {
1848                                 GetWindowText(GetDlgItem(hwnd, 201), dlg->cmd, MAX_PATH);
1849                                 dlg->cmdshow = get_check(hwnd,214) ? SW_SHOWMINIMIZED : SW_SHOWNORMAL;
1850                                 EndDialog(hwnd, id);
1851                         } else if (id == IDCANCEL)
1852                                 EndDialog(hwnd, id);
1853
1854                         return 1;}
1855         }
1856
1857         return 0;
1858 }
1859
1860
1861 static INT_PTR CALLBACK DestinationDlgProc(HWND hwnd, UINT nmsg, WPARAM wparam, LPARAM lparam)
1862 {
1863         TCHAR b1[BUFFER_LEN], b2[BUFFER_LEN];
1864
1865         switch(nmsg) {
1866                 case WM_INITDIALOG:
1867                         SetWindowLongPtr(hwnd, GWLP_USERDATA, lparam);
1868                         SetWindowText(GetDlgItem(hwnd, 201), (LPCTSTR)lparam);
1869                         return 1;
1870
1871                 case WM_COMMAND: {
1872                         int id = (int)wparam;
1873
1874                         switch(id) {
1875                           case IDOK: {
1876                                 LPTSTR dest = (LPTSTR) GetWindowLongPtr(hwnd, GWLP_USERDATA);
1877                                 GetWindowText(GetDlgItem(hwnd, 201), dest, MAX_PATH);
1878                                 EndDialog(hwnd, id);
1879                                 break;}
1880
1881                           case IDCANCEL:
1882                                 EndDialog(hwnd, id);
1883                                 break;
1884
1885                           case 254:
1886                                 MessageBox(hwnd, RS(b1,IDS_NO_IMPL), RS(b2,IDS_WINEFILE), MB_OK);
1887                                 break;
1888                         }
1889
1890                         return 1;
1891                 }
1892         }
1893
1894         return 0;
1895 }
1896
1897
1898 struct FilterDialog {
1899         TCHAR   pattern[MAX_PATH];
1900         int             flags;
1901 };
1902
1903 static INT_PTR CALLBACK FilterDialogDlgProc(HWND hwnd, UINT nmsg, WPARAM wparam, LPARAM lparam)
1904 {
1905         static struct FilterDialog* dlg;
1906
1907         switch(nmsg) {
1908                 case WM_INITDIALOG:
1909                         dlg = (struct FilterDialog*) lparam;
1910                         SetWindowText(GetDlgItem(hwnd, IDC_VIEW_PATTERN), dlg->pattern);
1911                         set_check(hwnd, IDC_VIEW_TYPE_DIRECTORIES, dlg->flags&TF_DIRECTORIES);
1912                         set_check(hwnd, IDC_VIEW_TYPE_PROGRAMS, dlg->flags&TF_PROGRAMS);
1913                         set_check(hwnd, IDC_VIEW_TYPE_DOCUMENTS, dlg->flags&TF_DOCUMENTS);
1914                         set_check(hwnd, IDC_VIEW_TYPE_OTHERS, dlg->flags&TF_OTHERS);
1915                         set_check(hwnd, IDC_VIEW_TYPE_HIDDEN, dlg->flags&TF_HIDDEN);
1916                         return 1;
1917
1918                 case WM_COMMAND: {
1919                         int id = (int)wparam;
1920
1921                         if (id == IDOK) {
1922                                 int flags = 0;
1923
1924                                 GetWindowText(GetDlgItem(hwnd, IDC_VIEW_PATTERN), dlg->pattern, MAX_PATH);
1925
1926                                 flags |= get_check(hwnd, IDC_VIEW_TYPE_DIRECTORIES) ? TF_DIRECTORIES : 0;
1927                                 flags |= get_check(hwnd, IDC_VIEW_TYPE_PROGRAMS) ? TF_PROGRAMS : 0;
1928                                 flags |= get_check(hwnd, IDC_VIEW_TYPE_DOCUMENTS) ? TF_DOCUMENTS : 0;
1929                                 flags |= get_check(hwnd, IDC_VIEW_TYPE_OTHERS) ? TF_OTHERS : 0;
1930                                 flags |= get_check(hwnd, IDC_VIEW_TYPE_HIDDEN) ? TF_HIDDEN : 0;
1931
1932                                 dlg->flags = flags;
1933
1934                                 EndDialog(hwnd, id);
1935                         } else if (id == IDCANCEL)
1936                                 EndDialog(hwnd, id);
1937
1938                         return 1;}
1939         }
1940
1941         return 0;
1942 }
1943
1944
1945 struct PropertiesDialog {
1946         TCHAR   path[MAX_PATH];
1947         Entry   entry;
1948         void*   pVersionData;
1949 };
1950
1951 /* Structure used to store enumerated languages and code pages. */
1952 struct LANGANDCODEPAGE {
1953         WORD wLanguage;
1954         WORD wCodePage;
1955 } *lpTranslate;
1956
1957 static LPCSTR InfoStrings[] = {
1958         "Comments",
1959         "CompanyName",
1960         "FileDescription",
1961         "FileVersion",
1962         "InternalName",
1963         "LegalCopyright",
1964         "LegalTrademarks",
1965         "OriginalFilename",
1966         "PrivateBuild",
1967         "ProductName",
1968         "ProductVersion",
1969         "SpecialBuild",
1970         NULL
1971 };
1972
1973 static void PropDlg_DisplayValue(HWND hlbox, HWND hedit)
1974 {
1975         int idx = SendMessage(hlbox, LB_GETCURSEL, 0, 0);
1976
1977         if (idx != LB_ERR) {
1978                 LPCTSTR pValue = (LPCTSTR) SendMessage(hlbox, LB_GETITEMDATA, idx, 0);
1979
1980                 if (pValue)
1981                         SetWindowText(hedit, pValue);
1982         }
1983 }
1984
1985 static void CheckForFileInfo(struct PropertiesDialog* dlg, HWND hwnd, LPCTSTR strFilename)
1986 {
1987         static TCHAR sBackSlash[] = {'\\','\0'};
1988         static TCHAR sTranslation[] = {'\\','V','a','r','F','i','l','e','I','n','f','o','\\','T','r','a','n','s','l','a','t','i','o','n','\0'};
1989         static TCHAR sStringFileInfo[] = {'\\','S','t','r','i','n','g','F','i','l','e','I','n','f','o','\\',
1990                                                                                 '%','0','4','x','%','0','4','x','\\','%','s','\0'};
1991         DWORD dwVersionDataLen = GetFileVersionInfoSize(strFilename, NULL);
1992
1993         if (dwVersionDataLen) {
1994                 dlg->pVersionData = HeapAlloc(GetProcessHeap(), 0, dwVersionDataLen);
1995
1996                 if (GetFileVersionInfo(strFilename, 0, dwVersionDataLen, dlg->pVersionData)) {
1997                         LPVOID pVal;
1998                         UINT nValLen;
1999
2000                         if (VerQueryValue(dlg->pVersionData, sBackSlash, &pVal, &nValLen)) {
2001                                 if (nValLen == sizeof(VS_FIXEDFILEINFO)) {
2002                                         VS_FIXEDFILEINFO* pFixedFileInfo = (VS_FIXEDFILEINFO*)pVal;
2003                                         char buffer[BUFFER_LEN];
2004
2005                                         sprintf(buffer, "%d.%d.%d.%d",
2006                                                 HIWORD(pFixedFileInfo->dwFileVersionMS), LOWORD(pFixedFileInfo->dwFileVersionMS),
2007                                                 HIWORD(pFixedFileInfo->dwFileVersionLS), LOWORD(pFixedFileInfo->dwFileVersionLS));
2008
2009                                         SetDlgItemTextA(hwnd, IDC_STATIC_PROP_VERSION, buffer);
2010                                 }
2011                         }
2012
2013                         /* Read the list of languages and code pages. */
2014                         if (VerQueryValue(dlg->pVersionData, sTranslation, &pVal, &nValLen)) {
2015                                 struct LANGANDCODEPAGE* pTranslate = (struct LANGANDCODEPAGE*)pVal;
2016                                 struct LANGANDCODEPAGE* pEnd = (struct LANGANDCODEPAGE*)((LPBYTE)pVal+nValLen);
2017
2018                                 HWND hlbox = GetDlgItem(hwnd, IDC_LIST_PROP_VERSION_TYPES);
2019
2020                                 /* Read the file description for each language and code page. */
2021                                 for(; pTranslate<pEnd; ++pTranslate) {
2022                                         LPCSTR* p;
2023
2024                                         for(p=InfoStrings; *p; ++p) {
2025                                                 TCHAR subblock[200];
2026 #ifdef UNICODE
2027                                                 TCHAR infoStr[100];
2028 #endif
2029                                                 LPCTSTR pTxt;
2030                                                 UINT nValLen;
2031
2032                                                 LPCSTR pInfoString = *p;
2033 #ifdef UNICODE
2034                                                 MultiByteToWideChar(CP_ACP, 0, pInfoString, -1, infoStr, 100);
2035 #else
2036 #define infoStr pInfoString
2037 #endif
2038                                                 wsprintf(subblock, sStringFileInfo, pTranslate->wLanguage, pTranslate->wCodePage, infoStr);
2039
2040                                                 /* Retrieve file description for language and code page */
2041                                                 if (VerQueryValue(dlg->pVersionData, subblock, (PVOID)&pTxt, &nValLen)) {
2042                                                         int idx = SendMessage(hlbox, LB_ADDSTRING, 0L, (LPARAM)infoStr);
2043                                                         SendMessage(hlbox, LB_SETITEMDATA, idx, (LPARAM) pTxt);
2044                                                 }
2045                                         }
2046                                 }
2047
2048                                 SendMessage(hlbox, LB_SETCURSEL, 0, 0);
2049
2050                                 PropDlg_DisplayValue(hlbox, GetDlgItem(hwnd,IDC_LIST_PROP_VERSION_VALUES));
2051                         }
2052                 }
2053         }
2054 }
2055
2056 static INT_PTR CALLBACK PropertiesDialogDlgProc(HWND hwnd, UINT nmsg, WPARAM wparam, LPARAM lparam)
2057 {
2058         static struct PropertiesDialog* dlg;
2059
2060         switch(nmsg) {
2061                 case WM_INITDIALOG: {
2062                         static const TCHAR sByteFmt[] = {'%','s',' ','B','y','t','e','s','\0'};
2063                         TCHAR b1[BUFFER_LEN], b2[BUFFER_LEN];
2064                         LPWIN32_FIND_DATA pWFD;
2065                         ULONGLONG size;
2066
2067                         dlg = (struct PropertiesDialog*) lparam;
2068                         pWFD = (LPWIN32_FIND_DATA) &dlg->entry.data;
2069
2070                         GetWindowText(hwnd, b1, MAX_PATH);
2071                         wsprintf(b2, b1, pWFD->cFileName);
2072                         SetWindowText(hwnd, b2);
2073
2074                         format_date(&pWFD->ftLastWriteTime, b1, COL_DATE|COL_TIME);
2075                         SetWindowText(GetDlgItem(hwnd, IDC_STATIC_PROP_LASTCHANGE), b1);
2076
2077                         size = ((ULONGLONG)pWFD->nFileSizeHigh << 32) | pWFD->nFileSizeLow;
2078                         _stprintf(b1, sLongNumFmt, size);
2079                         wsprintf(b2, sByteFmt, b1);
2080                         SetWindowText(GetDlgItem(hwnd, IDC_STATIC_PROP_SIZE), b2);
2081
2082                         SetWindowText(GetDlgItem(hwnd, IDC_STATIC_PROP_FILENAME), pWFD->cFileName);
2083                         SetWindowText(GetDlgItem(hwnd, IDC_STATIC_PROP_PATH), dlg->path);
2084
2085                         set_check(hwnd, IDC_CHECK_READONLY, pWFD->dwFileAttributes&FILE_ATTRIBUTE_READONLY);
2086                         set_check(hwnd, IDC_CHECK_ARCHIVE, pWFD->dwFileAttributes&FILE_ATTRIBUTE_ARCHIVE);
2087                         set_check(hwnd, IDC_CHECK_COMPRESSED, pWFD->dwFileAttributes&FILE_ATTRIBUTE_COMPRESSED);
2088                         set_check(hwnd, IDC_CHECK_HIDDEN, pWFD->dwFileAttributes&FILE_ATTRIBUTE_HIDDEN);
2089                         set_check(hwnd, IDC_CHECK_SYSTEM, pWFD->dwFileAttributes&FILE_ATTRIBUTE_SYSTEM);
2090
2091                         CheckForFileInfo(dlg, hwnd, dlg->path);
2092                         return 1;}
2093
2094                 case WM_COMMAND: {
2095                         int id = (int)wparam;
2096
2097                         switch(HIWORD(wparam)) {
2098                           case LBN_SELCHANGE: {
2099                                 HWND hlbox = GetDlgItem(hwnd, IDC_LIST_PROP_VERSION_TYPES);
2100                                 PropDlg_DisplayValue(hlbox, GetDlgItem(hwnd,IDC_LIST_PROP_VERSION_VALUES));
2101                                 break;
2102                           }
2103
2104                           case BN_CLICKED:
2105                                 if (id==IDOK || id==IDCANCEL)
2106                                         EndDialog(hwnd, id);
2107                         }
2108
2109                         return 1;}
2110
2111                 case WM_NCDESTROY:
2112                         HeapFree(GetProcessHeap(), 0, dlg->pVersionData);
2113                         dlg->pVersionData = NULL;
2114                         break;
2115         }
2116
2117         return 0;
2118 }
2119
2120 static void show_properties_dlg(Entry* entry, HWND hwnd)
2121 {
2122         struct PropertiesDialog dlg;
2123
2124         memset(&dlg, 0, sizeof(struct PropertiesDialog));
2125         get_path(entry, dlg.path);
2126         memcpy(&dlg.entry, entry, sizeof(Entry));
2127
2128         DialogBoxParam(Globals.hInstance, MAKEINTRESOURCE(IDD_DIALOG_PROPERTIES), hwnd, PropertiesDialogDlgProc, (LPARAM)&dlg);
2129 }
2130
2131
2132 #ifndef _NO_EXTENSIONS
2133
2134 static struct FullScreenParameters {
2135         BOOL    mode;
2136         RECT    orgPos;
2137         BOOL    wasZoomed;
2138 } g_fullscreen = {
2139     FALSE,      /* mode */
2140         {0, 0, 0, 0},
2141         FALSE
2142 };
2143
2144 static void frame_get_clientspace(HWND hwnd, PRECT prect)
2145 {
2146         RECT rt;
2147
2148         if (!IsIconic(hwnd))
2149                 GetClientRect(hwnd, prect);
2150         else {
2151                 WINDOWPLACEMENT wp;
2152
2153                 GetWindowPlacement(hwnd, &wp);
2154
2155                 prect->left = prect->top = 0;
2156                 prect->right = wp.rcNormalPosition.right-wp.rcNormalPosition.left-
2157                                                 2*(GetSystemMetrics(SM_CXSIZEFRAME)+GetSystemMetrics(SM_CXEDGE));
2158                 prect->bottom = wp.rcNormalPosition.bottom-wp.rcNormalPosition.top-
2159                                                 2*(GetSystemMetrics(SM_CYSIZEFRAME)+GetSystemMetrics(SM_CYEDGE))-
2160                                                 GetSystemMetrics(SM_CYCAPTION)-GetSystemMetrics(SM_CYMENUSIZE);
2161         }
2162
2163         if (IsWindowVisible(Globals.htoolbar)) {
2164                 GetClientRect(Globals.htoolbar, &rt);
2165                 prect->top += rt.bottom+2;
2166         }
2167
2168         if (IsWindowVisible(Globals.hdrivebar)) {
2169                 GetClientRect(Globals.hdrivebar, &rt);
2170                 prect->top += rt.bottom+2;
2171         }
2172
2173         if (IsWindowVisible(Globals.hstatusbar)) {
2174                 GetClientRect(Globals.hstatusbar, &rt);
2175                 prect->bottom -= rt.bottom;
2176         }
2177 }
2178
2179 static BOOL toggle_fullscreen(HWND hwnd)
2180 {
2181         RECT rt;
2182
2183         if ((g_fullscreen.mode=!g_fullscreen.mode)) {
2184                 GetWindowRect(hwnd, &g_fullscreen.orgPos);
2185                 g_fullscreen.wasZoomed = IsZoomed(hwnd);
2186
2187                 Frame_CalcFrameClient(hwnd, &rt);
2188                 ClientToScreen(hwnd, (LPPOINT)&rt.left);
2189                 ClientToScreen(hwnd, (LPPOINT)&rt.right);
2190
2191                 rt.left = g_fullscreen.orgPos.left-rt.left;
2192                 rt.top = g_fullscreen.orgPos.top-rt.top;
2193                 rt.right = GetSystemMetrics(SM_CXSCREEN)+g_fullscreen.orgPos.right-rt.right;
2194                 rt.bottom = GetSystemMetrics(SM_CYSCREEN)+g_fullscreen.orgPos.bottom-rt.bottom;
2195
2196                 MoveWindow(hwnd, rt.left, rt.top, rt.right-rt.left, rt.bottom-rt.top, TRUE);
2197         } else {
2198                 MoveWindow(hwnd, g_fullscreen.orgPos.left, g_fullscreen.orgPos.top,
2199                                                         g_fullscreen.orgPos.right-g_fullscreen.orgPos.left,
2200                                                         g_fullscreen.orgPos.bottom-g_fullscreen.orgPos.top, TRUE);
2201
2202                 if (g_fullscreen.wasZoomed)
2203                         ShowWindow(hwnd, WS_MAXIMIZE);
2204         }
2205
2206         return g_fullscreen.mode;
2207 }
2208
2209 static void fullscreen_move(HWND hwnd)
2210 {
2211         RECT rt, pos;
2212         GetWindowRect(hwnd, &pos);
2213
2214         Frame_CalcFrameClient(hwnd, &rt);
2215         ClientToScreen(hwnd, (LPPOINT)&rt.left);
2216         ClientToScreen(hwnd, (LPPOINT)&rt.right);
2217
2218         rt.left = pos.left-rt.left;
2219         rt.top = pos.top-rt.top;
2220         rt.right = GetSystemMetrics(SM_CXSCREEN)+pos.right-rt.right;
2221         rt.bottom = GetSystemMetrics(SM_CYSCREEN)+pos.bottom-rt.bottom;
2222
2223         MoveWindow(hwnd, rt.left, rt.top, rt.right-rt.left, rt.bottom-rt.top, TRUE);
2224 }
2225
2226 #endif
2227
2228
2229 static void toggle_child(HWND hwnd, UINT cmd, HWND hchild)
2230 {
2231         BOOL vis = IsWindowVisible(hchild);
2232
2233         CheckMenuItem(Globals.hMenuOptions, cmd, vis?MF_BYCOMMAND:MF_BYCOMMAND|MF_CHECKED);
2234
2235         ShowWindow(hchild, vis?SW_HIDE:SW_SHOW);
2236
2237 #ifndef _NO_EXTENSIONS
2238         if (g_fullscreen.mode)
2239                 fullscreen_move(hwnd);
2240 #endif
2241
2242         resize_frame_client(hwnd);
2243 }
2244
2245 static BOOL activate_drive_window(LPCTSTR path)
2246 {
2247         TCHAR drv1[_MAX_DRIVE], drv2[_MAX_DRIVE];
2248         HWND child_wnd;
2249
2250         _tsplitpath(path, drv1, 0, 0, 0);
2251
2252         /* search for a already open window for the same drive */
2253         for(child_wnd=GetNextWindow(Globals.hmdiclient,GW_CHILD); child_wnd; child_wnd=GetNextWindow(child_wnd, GW_HWNDNEXT)) {
2254                 ChildWnd* child = (ChildWnd*) GetWindowLongPtr(child_wnd, GWLP_USERDATA);
2255
2256                 if (child) {
2257                         _tsplitpath(child->root.path, drv2, 0, 0, 0);
2258
2259                         if (!lstrcmpi(drv2, drv1)) {
2260                                 SendMessage(Globals.hmdiclient, WM_MDIACTIVATE, (WPARAM)child_wnd, 0);
2261
2262                                 if (IsIconic(child_wnd))
2263                                         ShowWindow(child_wnd, SW_SHOWNORMAL);
2264
2265                                 return TRUE;
2266                         }
2267                 }
2268         }
2269
2270         return FALSE;
2271 }
2272
2273 static BOOL activate_fs_window(LPCTSTR filesys)
2274 {
2275         HWND child_wnd;
2276
2277         /* search for a already open window of the given file system name */
2278         for(child_wnd=GetNextWindow(Globals.hmdiclient,GW_CHILD); child_wnd; child_wnd=GetNextWindow(child_wnd, GW_HWNDNEXT)) {
2279                 ChildWnd* child = (ChildWnd*) GetWindowLongPtr(child_wnd, GWLP_USERDATA);
2280
2281                 if (child) {
2282                         if (!lstrcmpi(child->root.fs, filesys)) {
2283                                 SendMessage(Globals.hmdiclient, WM_MDIACTIVATE, (WPARAM)child_wnd, 0);
2284
2285                                 if (IsIconic(child_wnd))
2286                                         ShowWindow(child_wnd, SW_SHOWNORMAL);
2287
2288                                 return TRUE;
2289                         }
2290                 }
2291         }
2292
2293         return FALSE;
2294 }
2295
2296 static LRESULT CALLBACK FrameWndProc(HWND hwnd, UINT nmsg, WPARAM wparam, LPARAM lparam)
2297 {
2298         TCHAR b1[BUFFER_LEN], b2[BUFFER_LEN];
2299
2300         switch(nmsg) {
2301                 case WM_CLOSE:
2302                         if (Globals.saveSettings)
2303                                 save_registry_settings();  
2304                         
2305                         DestroyWindow(hwnd);
2306
2307                          /* clear handle variables */
2308                         Globals.hMenuFrame = 0;
2309                         Globals.hMenuView = 0;
2310                         Globals.hMenuOptions = 0;
2311                         Globals.hMainWnd = 0;
2312                         Globals.hmdiclient = 0;
2313                         Globals.hdrivebar = 0;
2314                         break;
2315
2316                 case WM_DESTROY:
2317                         PostQuitMessage(0);
2318                         break;
2319
2320                 case WM_INITMENUPOPUP: {
2321                         HWND hwndClient = (HWND) SendMessage(Globals.hmdiclient, WM_MDIGETACTIVE, 0, 0);
2322
2323                         if (!SendMessage(hwndClient, WM_INITMENUPOPUP, wparam, lparam))
2324                                 return 0;
2325                         break;}
2326
2327                 case WM_COMMAND: {
2328                         UINT cmd = LOWORD(wparam);
2329                         HWND hwndClient = (HWND) SendMessage(Globals.hmdiclient, WM_MDIGETACTIVE, 0, 0);
2330
2331                         if (SendMessage(hwndClient, WM_DISPATCH_COMMAND, wparam, lparam))
2332                                 break;
2333
2334                         if (cmd>=ID_DRIVE_FIRST && cmd<=ID_DRIVE_FIRST+0xFF) {
2335                                 TCHAR drv[_MAX_DRIVE], path[MAX_PATH];
2336                                 ChildWnd* child;
2337                                 LPCTSTR root = Globals.drives;
2338                                 int i;
2339
2340                                 for(i=cmd-ID_DRIVE_FIRST; i--; root++)
2341                                         while(*root)
2342                                                 root++;
2343
2344                                 if (activate_drive_window(root))
2345                                         return 0;
2346
2347                                 _tsplitpath(root, drv, 0, 0, 0);
2348
2349                                 if (!SetCurrentDirectory(drv)) {
2350                                         display_error(hwnd, GetLastError());
2351                                         return 0;
2352                                 }
2353
2354                                 GetCurrentDirectory(MAX_PATH, path); /*TODO: store last directory per drive */
2355                                 child = alloc_child_window(path, NULL, hwnd);
2356
2357                                 if (!create_child_window(child))
2358                                         HeapFree(GetProcessHeap(), 0, child);
2359                         } else switch(cmd) {
2360                                 case ID_FILE_EXIT:
2361                                         SendMessage(hwnd, WM_CLOSE, 0, 0);
2362                                         break;
2363
2364                                 case ID_WINDOW_NEW: {
2365                                         TCHAR path[MAX_PATH];
2366                                         ChildWnd* child;
2367
2368                                         GetCurrentDirectory(MAX_PATH, path);
2369                                         child = alloc_child_window(path, NULL, hwnd);
2370
2371                                         if (!create_child_window(child))
2372                                                 HeapFree(GetProcessHeap(), 0, child);
2373                                         break;}
2374
2375                                 case ID_REFRESH:
2376                                         refresh_drives();
2377                                         break;
2378
2379                                 case ID_WINDOW_CASCADE:
2380                                         SendMessage(Globals.hmdiclient, WM_MDICASCADE, 0, 0);
2381                                         break;
2382
2383                                 case ID_WINDOW_TILE_HORZ:
2384                                         SendMessage(Globals.hmdiclient, WM_MDITILE, MDITILE_HORIZONTAL, 0);
2385                                         break;
2386
2387                                 case ID_WINDOW_TILE_VERT:
2388                                         SendMessage(Globals.hmdiclient, WM_MDITILE, MDITILE_VERTICAL, 0);
2389                                         break;
2390
2391                                 case ID_WINDOW_ARRANGE:
2392                                         SendMessage(Globals.hmdiclient, WM_MDIICONARRANGE, 0, 0);
2393                                         break;
2394
2395                                 case ID_SELECT_FONT:
2396                                         choose_font(hwnd);
2397                                         break;
2398
2399                                 case ID_VIEW_TOOL_BAR:
2400                                         toggle_child(hwnd, cmd, Globals.htoolbar);
2401                                         break;
2402
2403                                 case ID_VIEW_DRIVE_BAR:
2404                                         toggle_child(hwnd, cmd, Globals.hdrivebar);
2405                                         break;
2406
2407                                 case ID_VIEW_STATUSBAR:
2408                                         toggle_child(hwnd, cmd, Globals.hstatusbar);
2409                                         break;
2410
2411                                 case ID_VIEW_SAVESETTINGS:
2412                                         Globals.saveSettings = !Globals.saveSettings;
2413                                         CheckMenuItem(Globals.hMenuOptions, ID_VIEW_SAVESETTINGS,
2414                                                       Globals.saveSettings ? MF_CHECKED : MF_UNCHECKED );
2415                                         break;
2416
2417                                 case ID_EXECUTE: {
2418                                         struct ExecuteDialog dlg;
2419
2420                                         memset(&dlg, 0, sizeof(struct ExecuteDialog));
2421
2422                                         if (DialogBoxParam(Globals.hInstance, MAKEINTRESOURCE(IDD_EXECUTE), hwnd, ExecuteDialogDlgProc, (LPARAM)&dlg) == IDOK) {
2423                                                 HINSTANCE hinst = ShellExecute(hwnd, NULL/*operation*/, dlg.cmd/*file*/, NULL/*parameters*/, NULL/*dir*/, dlg.cmdshow);
2424
2425                                                 if ((int)hinst <= 32)
2426                                                         display_error(hwnd, GetLastError());
2427                                         }
2428                                         break;}
2429
2430                                 case ID_CONNECT_NETWORK_DRIVE: {
2431                                         DWORD ret = WNetConnectionDialog(hwnd, RESOURCETYPE_DISK);
2432                                         if (ret == NO_ERROR)
2433                                                 refresh_drives();
2434                                         else if (ret != (DWORD)-1) {
2435                                                 if (ret == ERROR_EXTENDED_ERROR)
2436                                                         display_network_error(hwnd);
2437                                                 else
2438                                                         display_error(hwnd, ret);
2439                                         }
2440                                         break;}
2441
2442                                 case ID_DISCONNECT_NETWORK_DRIVE: {
2443                                         DWORD ret = WNetDisconnectDialog(hwnd, RESOURCETYPE_DISK);
2444                                         if (ret == NO_ERROR)
2445                                                 refresh_drives();
2446                                         else if (ret != (DWORD)-1) {
2447                                                 if (ret == ERROR_EXTENDED_ERROR)
2448                                                         display_network_error(hwnd);
2449                                                 else
2450                                                         display_error(hwnd, ret);
2451                                         }
2452                                         break;}
2453
2454                                 case ID_FORMAT_DISK: {
2455                                         UINT sem_org = SetErrorMode(0); /* Get the current Error Mode settings. */
2456                                         SetErrorMode(sem_org & ~SEM_FAILCRITICALERRORS); /* Force O/S to handle */
2457                                         SHFormatDrive(hwnd, 0 /* A: */, SHFMT_ID_DEFAULT, 0);
2458                                         SetErrorMode(sem_org); /* Put it back the way it was. */
2459                                         break;}
2460
2461                                 case ID_HELP:
2462                                         WinHelp(hwnd, RS(b1,IDS_WINEFILE), HELP_INDEX, 0);
2463                                         break;
2464
2465 #ifndef _NO_EXTENSIONS
2466                                 case ID_VIEW_FULLSCREEN:
2467                                         CheckMenuItem(Globals.hMenuOptions, cmd, toggle_fullscreen(hwnd)?MF_CHECKED:0);
2468                                         break;
2469
2470 #ifdef __WINE__
2471                                 case ID_DRIVE_UNIX_FS: {
2472                                         TCHAR path[MAX_PATH];
2473 #ifdef UNICODE
2474                                         char cpath[MAX_PATH];
2475 #endif
2476                                         ChildWnd* child;
2477
2478                                         if (activate_fs_window(RS(b1,IDS_UNIXFS)))
2479                                                 break;
2480
2481 #ifdef UNICODE
2482                                         getcwd(cpath, MAX_PATH);
2483                                         MultiByteToWideChar(CP_UNIXCP, 0, cpath, -1, path, MAX_PATH);
2484 #else
2485                                         getcwd(path, MAX_PATH);
2486 #endif
2487                                         child = alloc_child_window(path, NULL, hwnd);
2488
2489                                         if (!create_child_window(child))
2490                                                 HeapFree(GetProcessHeap(), 0, child);
2491                                         break;}
2492 #endif
2493 #ifdef _SHELL_FOLDERS
2494                                 case ID_DRIVE_SHELL_NS: {
2495                                         TCHAR path[MAX_PATH];
2496                                         ChildWnd* child;
2497
2498                                         if (activate_fs_window(RS(b1,IDS_SHELL)))
2499                                                 break;
2500
2501                                         GetCurrentDirectory(MAX_PATH, path);
2502                                         child = alloc_child_window(path, get_path_pidl(path,hwnd), hwnd);
2503
2504                                         if (!create_child_window(child))
2505                                                 HeapFree(GetProcessHeap(), 0, child);
2506                                         break;}
2507 #endif
2508 #endif
2509
2510                                 /*TODO: There are even more menu items! */
2511
2512 #ifndef _NO_EXTENSIONS
2513 #ifdef __WINE__
2514                                 case ID_LICENSE:
2515                                         WineLicense(Globals.hMainWnd);
2516                                         break;
2517
2518                                 case ID_NO_WARRANTY:
2519                                         WineWarranty(Globals.hMainWnd);
2520                                         break;
2521
2522                                 case ID_ABOUT_WINE:
2523                                         ShellAbout(hwnd, RS(b2,IDS_WINE), RS(b1,IDS_WINEFILE), 0);
2524                                         break;
2525 #endif
2526
2527                                 case ID_ABOUT:
2528                                         ShellAbout(hwnd, RS(b1,IDS_WINEFILE), NULL, 0);
2529                                         break;
2530 #endif  /* _NO_EXTENSIONS */
2531
2532                                 default:
2533                                         /*TODO: if (wParam >= PM_FIRST_LANGUAGE && wParam <= PM_LAST_LANGUAGE)
2534                                                 STRING_SelectLanguageByNumber(wParam - PM_FIRST_LANGUAGE);
2535                                         else */if ((cmd<IDW_FIRST_CHILD || cmd>=IDW_FIRST_CHILD+0x100) &&
2536                                                 (cmd<SC_SIZE || cmd>SC_RESTORE))
2537                                                 MessageBox(hwnd, RS(b2,IDS_NO_IMPL), RS(b1,IDS_WINEFILE), MB_OK);
2538
2539                                         return DefFrameProc(hwnd, Globals.hmdiclient, nmsg, wparam, lparam);
2540                         }
2541                         break;}
2542
2543                 case WM_SIZE:
2544                         resize_frame(hwnd, LOWORD(lparam), HIWORD(lparam));
2545                         break;  /* do not pass message to DefFrameProc */
2546
2547                 case WM_DEVICECHANGE:
2548                         SendMessage(hwnd, WM_COMMAND, MAKELONG(ID_REFRESH,0), 0);
2549                         break;
2550
2551 #ifndef _NO_EXTENSIONS
2552                 case WM_GETMINMAXINFO: {
2553                         LPMINMAXINFO lpmmi = (LPMINMAXINFO)lparam;
2554
2555                         lpmmi->ptMaxTrackSize.x <<= 1;/*2*GetSystemMetrics(SM_CXSCREEN) / SM_CXVIRTUALSCREEN */
2556                         lpmmi->ptMaxTrackSize.y <<= 1;/*2*GetSystemMetrics(SM_CYSCREEN) / SM_CYVIRTUALSCREEN */
2557                         break;}
2558
2559                 case FRM_CALC_CLIENT:
2560                         frame_get_clientspace(hwnd, (PRECT)lparam);
2561                         return TRUE;
2562 #endif /* _NO_EXTENSIONS */
2563
2564                 default:
2565                         return DefFrameProc(hwnd, Globals.hmdiclient, nmsg, wparam, lparam);
2566         }
2567
2568         return 0;
2569 }
2570
2571
2572 static TCHAR g_pos_names[COLUMNS][20] = {
2573         {'\0'}  /* symbol */
2574 };
2575
2576 static const int g_pos_align[] = {
2577         0,
2578         HDF_LEFT,       /* Name */
2579         HDF_RIGHT,      /* Size */
2580         HDF_LEFT,       /* CDate */
2581 #ifndef _NO_EXTENSIONS
2582         HDF_LEFT,       /* ADate */
2583         HDF_LEFT,       /* MDate */
2584         HDF_LEFT,       /* Index */
2585         HDF_CENTER,     /* Links */
2586 #endif
2587         HDF_CENTER,     /* Attributes */
2588 #ifndef _NO_EXTENSIONS
2589         HDF_LEFT        /* Security */
2590 #endif
2591 };
2592
2593 static void resize_tree(ChildWnd* child, int cx, int cy)
2594 {
2595         HDWP hdwp = BeginDeferWindowPos(4);
2596         RECT rt;
2597
2598         rt.left   = 0;
2599         rt.top    = 0;
2600         rt.right  = cx;
2601         rt.bottom = cy;
2602
2603         cx = child->split_pos + SPLIT_WIDTH/2;
2604
2605 #ifndef _NO_EXTENSIONS
2606         {
2607                 WINDOWPOS wp;
2608                 HD_LAYOUT hdl;
2609
2610                 hdl.prc   = &rt;
2611                 hdl.pwpos = &wp;
2612
2613                 SendMessage(child->left.hwndHeader, HDM_LAYOUT, 0, (LPARAM)&hdl);
2614
2615                 DeferWindowPos(hdwp, child->left.hwndHeader, wp.hwndInsertAfter,
2616                                                 wp.x-1, wp.y, child->split_pos-SPLIT_WIDTH/2+1, wp.cy, wp.flags);
2617                 DeferWindowPos(hdwp, child->right.hwndHeader, wp.hwndInsertAfter,
2618                                                 rt.left+cx+1, wp.y, wp.cx-cx+2, wp.cy, wp.flags);
2619         }
2620 #endif /* _NO_EXTENSIONS */
2621
2622         DeferWindowPos(hdwp, child->left.hwnd, 0, rt.left, rt.top, child->split_pos-SPLIT_WIDTH/2-rt.left, rt.bottom-rt.top, SWP_NOZORDER|SWP_NOACTIVATE);
2623         DeferWindowPos(hdwp, child->right.hwnd, 0, rt.left+cx+1, rt.top, rt.right-cx, rt.bottom-rt.top, SWP_NOZORDER|SWP_NOACTIVATE);
2624
2625         EndDeferWindowPos(hdwp);
2626 }
2627
2628
2629 #ifndef _NO_EXTENSIONS
2630
2631 static HWND create_header(HWND parent, Pane* pane, int id)
2632 {
2633         HD_ITEM hdi;
2634         int idx;
2635
2636         HWND hwnd = CreateWindow(WC_HEADER, 0, WS_CHILD|WS_VISIBLE|HDS_HORZ|HDS_FULLDRAG/*TODO: |HDS_BUTTONS + sort orders*/,
2637                                                                 0, 0, 0, 0, parent, (HMENU)id, Globals.hInstance, 0);
2638         if (!hwnd)
2639                 return 0;
2640
2641         SendMessage(hwnd, WM_SETFONT, (WPARAM)GetStockObject(DEFAULT_GUI_FONT), FALSE);
2642
2643         hdi.mask = HDI_TEXT|HDI_WIDTH|HDI_FORMAT;
2644
2645         for(idx=0; idx<COLUMNS; idx++) {
2646                 hdi.pszText = g_pos_names[idx];
2647                 hdi.fmt = HDF_STRING | g_pos_align[idx];
2648                 hdi.cxy = pane->widths[idx];
2649                 SendMessage(hwnd, HDM_INSERTITEM, idx, (LPARAM) &hdi);
2650         }
2651
2652         return hwnd;
2653 }
2654
2655 #endif /* _NO_EXTENSIONS */
2656
2657
2658 static void init_output(HWND hwnd)
2659 {
2660         static const WCHAR s1000[] = {'1','0','0','0','\0'};
2661         WCHAR b[16];
2662         HFONT old_font;
2663         HDC hdc = GetDC(hwnd);
2664
2665         if (GetNumberFormatW(LOCALE_USER_DEFAULT, 0, s1000, 0, b, 16) > 4)
2666                 Globals.num_sep = b[1];
2667         else
2668                 Globals.num_sep = '.';
2669
2670         old_font = SelectObject(hdc, Globals.hfont);
2671         GetTextExtentPoint32W(hdc, sSpace, 1, &Globals.spaceSize);
2672         SelectObject(hdc, old_font);
2673         ReleaseDC(hwnd, hdc);
2674 }
2675
2676 static void draw_item(Pane* pane, LPDRAWITEMSTRUCT dis, Entry* entry, int calcWidthCol);
2677
2678
2679 /* calculate preferred width for all visible columns */
2680
2681 static BOOL calc_widths(Pane* pane, BOOL anyway)
2682 {
2683         int col, x, cx, spc=3*Globals.spaceSize.cx;
2684         int entries = SendMessage(pane->hwnd, LB_GETCOUNT, 0, 0);
2685         int orgWidths[COLUMNS];
2686         int orgPositions[COLUMNS+1];
2687         HFONT hfontOld;
2688         HDC hdc;
2689         int cnt;
2690
2691         if (!anyway) {
2692                 memcpy(orgWidths, pane->widths, sizeof(orgWidths));
2693                 memcpy(orgPositions, pane->positions, sizeof(orgPositions));
2694         }
2695
2696         for(col=0; col<COLUMNS; col++)
2697                 pane->widths[col] = 0;
2698
2699         hdc = GetDC(pane->hwnd);
2700         hfontOld = SelectObject(hdc, Globals.hfont);
2701
2702         for(cnt=0; cnt<entries; cnt++) {
2703                 Entry* entry = (Entry*) SendMessage(pane->hwnd, LB_GETITEMDATA, cnt, 0);
2704
2705                 DRAWITEMSTRUCT dis;
2706
2707                 dis.CtlType               = 0;
2708                 dis.CtlID                 = 0;
2709                 dis.itemID                = 0;
2710                 dis.itemAction    = 0;
2711                 dis.itemState     = 0;
2712                 dis.hwndItem      = pane->hwnd;
2713                 dis.hDC                   = hdc;
2714                 dis.rcItem.left   = 0;
2715                 dis.rcItem.top    = 0;
2716                 dis.rcItem.right  = 0;
2717                 dis.rcItem.bottom = 0;
2718                 /*dis.itemData    = 0; */
2719
2720                 draw_item(pane, &dis, entry, COLUMNS);
2721         }
2722
2723         SelectObject(hdc, hfontOld);
2724         ReleaseDC(pane->hwnd, hdc);
2725
2726         x = 0;
2727         for(col=0; col<COLUMNS; col++) {
2728                 pane->positions[col] = x;
2729                 cx = pane->widths[col];
2730
2731                 if (cx) {
2732                         cx += spc;
2733
2734                         if (cx < IMAGE_WIDTH)
2735                                 cx = IMAGE_WIDTH;
2736
2737                         pane->widths[col] = cx;
2738                 }
2739
2740                 x += cx;
2741         }
2742
2743         pane->positions[COLUMNS] = x;
2744
2745         SendMessage(pane->hwnd, LB_SETHORIZONTALEXTENT, x, 0);
2746
2747         /* no change? */
2748         if (!memcmp(orgWidths, pane->widths, sizeof(orgWidths)))
2749                 return FALSE;
2750
2751         /* don't move, if only collapsing an entry */
2752         if (!anyway && pane->widths[0]<orgWidths[0] &&
2753                 !memcmp(orgWidths+1, pane->widths+1, sizeof(orgWidths)-sizeof(int))) {
2754                 pane->widths[0] = orgWidths[0];
2755                 memcpy(pane->positions, orgPositions, sizeof(orgPositions));
2756
2757                 return FALSE;
2758         }
2759
2760         InvalidateRect(pane->hwnd, 0, TRUE);
2761
2762         return TRUE;
2763 }
2764
2765
2766 /* calculate one preferred column width */
2767
2768 static void calc_single_width(Pane* pane, int col)
2769 {
2770         HFONT hfontOld;
2771         int x, cx;
2772         int entries = SendMessage(pane->hwnd, LB_GETCOUNT, 0, 0);
2773         int cnt;
2774         HDC hdc;
2775
2776         pane->widths[col] = 0;
2777
2778         hdc = GetDC(pane->hwnd);
2779         hfontOld = SelectObject(hdc, Globals.hfont);
2780
2781         for(cnt=0; cnt<entries; cnt++) {
2782                 Entry* entry = (Entry*) SendMessage(pane->hwnd, LB_GETITEMDATA, cnt, 0);
2783                 DRAWITEMSTRUCT dis;
2784
2785                 dis.CtlType               = 0;
2786                 dis.CtlID                 = 0;
2787                 dis.itemID                = 0;
2788                 dis.itemAction    = 0;
2789                 dis.itemState     = 0;
2790                 dis.hwndItem      = pane->hwnd;
2791                 dis.hDC                   = hdc;
2792                 dis.rcItem.left   = 0;
2793                 dis.rcItem.top    = 0;
2794                 dis.rcItem.right  = 0;
2795                 dis.rcItem.bottom = 0;
2796                 /*dis.itemData    = 0; */
2797
2798                 draw_item(pane, &dis, entry, col);
2799         }
2800
2801         SelectObject(hdc, hfontOld);
2802         ReleaseDC(pane->hwnd, hdc);
2803
2804         cx = pane->widths[col];
2805
2806         if (cx) {
2807                 cx += 3*Globals.spaceSize.cx;
2808
2809                 if (cx < IMAGE_WIDTH)
2810                         cx = IMAGE_WIDTH;
2811         }
2812
2813         pane->widths[col] = cx;
2814
2815         x = pane->positions[col] + cx;
2816
2817         for(; col<COLUMNS; ) {
2818                 pane->positions[++col] = x;
2819                 x += pane->widths[col];
2820         }
2821
2822         SendMessage(pane->hwnd, LB_SETHORIZONTALEXTENT, x, 0);
2823 }
2824
2825
2826 static BOOL pattern_match(LPCTSTR str, LPCTSTR pattern)
2827 {
2828         for( ; *str&&*pattern; str++,pattern++) {
2829                 if (*pattern == '*') {
2830                         do pattern++;
2831                         while(*pattern == '*');
2832
2833                         if (!*pattern)
2834                                 return TRUE;
2835
2836                         for(; *str; str++)
2837                                 if (*str==*pattern && pattern_match(str, pattern))
2838                                         return TRUE;
2839
2840                         return FALSE;
2841                 }
2842                 else if (*str!=*pattern && *pattern!='?')
2843                         return FALSE;
2844         }
2845
2846         if (*str || *pattern)
2847                 if (*pattern!='*' || pattern[1]!='\0')
2848                         return FALSE;
2849
2850         return TRUE;
2851 }
2852
2853 static BOOL pattern_imatch(LPCTSTR str, LPCTSTR pattern)
2854 {
2855         TCHAR b1[BUFFER_LEN], b2[BUFFER_LEN];
2856
2857         lstrcpy(b1, str);
2858         lstrcpy(b2, pattern);
2859         CharUpper(b1);
2860         CharUpper(b2);
2861
2862         return pattern_match(b1, b2);
2863 }
2864
2865
2866 enum FILE_TYPE {
2867         FT_OTHER                = 0,
2868         FT_EXECUTABLE   = 1,
2869         FT_DOCUMENT             = 2
2870 };
2871
2872 static enum FILE_TYPE get_file_type(LPCTSTR filename);
2873
2874
2875 /* insert listbox entries after index idx */
2876
2877 static int insert_entries(Pane* pane, Entry* dir, LPCTSTR pattern, int filter_flags, int idx)
2878 {
2879         Entry* entry = dir;
2880
2881         if (!entry)
2882                 return idx;
2883
2884         ShowWindow(pane->hwnd, SW_HIDE);
2885
2886         for(; entry; entry=entry->next) {
2887 #ifndef _LEFT_FILES
2888                 if (pane->treePane && !(entry->data.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY))
2889                         continue;
2890 #endif
2891
2892                 if (entry->data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
2893                         /* don't display entries "." and ".." in the left pane */
2894                         if (pane->treePane && entry->data.cFileName[0] == '.')
2895                                 if (
2896 #ifndef _NO_EXTENSIONS
2897                                         entry->data.cFileName[1] == '\0' ||
2898 #endif
2899                                         (entry->data.cFileName[1] == '.' && entry->data.cFileName[2] == '\0'))
2900                                         continue;
2901
2902                         /* filter directories in right pane */
2903                         if (!pane->treePane && !(filter_flags&TF_DIRECTORIES))
2904                                 continue;
2905                 }
2906
2907                 /* filter using the file name pattern */
2908                 if (pattern)
2909                         if (!pattern_imatch(entry->data.cFileName, pattern))
2910                                 continue;
2911
2912                 /* filter system and hidden files */
2913                 if (!(filter_flags&TF_HIDDEN) && (entry->data.dwFileAttributes&(FILE_ATTRIBUTE_HIDDEN|FILE_ATTRIBUTE_SYSTEM)))
2914                         continue;
2915
2916                 /* filter looking at the file type */
2917                 if ((filter_flags&(TF_PROGRAMS|TF_DOCUMENTS|TF_OTHERS)) != (TF_PROGRAMS|TF_DOCUMENTS|TF_OTHERS))
2918                         switch(get_file_type(entry->data.cFileName)) {
2919                           case FT_EXECUTABLE:
2920                                 if (!(filter_flags & TF_PROGRAMS))
2921                                         continue;
2922                                 break;
2923
2924                           case FT_DOCUMENT:
2925                                 if (!(filter_flags & TF_DOCUMENTS))
2926                                         continue;
2927                                 break;
2928
2929                           default: /* TF_OTHERS */
2930                                 if (!(filter_flags & TF_OTHERS))
2931                                         continue;
2932                         }
2933
2934                 if (idx != -1)
2935                         idx++;
2936
2937                 SendMessage(pane->hwnd, LB_INSERTSTRING, idx, (LPARAM) entry);
2938
2939                 if (pane->treePane && entry->expanded)
2940                         idx = insert_entries(pane, entry->down, pattern, filter_flags, idx);
2941         }
2942
2943         ShowWindow(pane->hwnd, SW_SHOW);
2944
2945         return idx;
2946 }
2947
2948
2949 static void format_bytes(LPTSTR buffer, LONGLONG bytes)
2950 {
2951         static const TCHAR sFmtGB[] = {'%', '.', '1', 'f', ' ', 'G', 'B', '\0'};
2952         static const TCHAR sFmtMB[] = {'%', '.', '1', 'f', ' ', 'M', 'B', '\0'};
2953         static const TCHAR sFmtkB[] = {'%', '.', '1', 'f', ' ', 'k', 'B', '\0'};
2954
2955         float fBytes = (float)bytes;
2956
2957         if (bytes >= 1073741824)        /* 1 GB */
2958                 _stprintf(buffer, sFmtGB, fBytes/1073741824.f+.5f);
2959         else if (bytes >= 1048576)      /* 1 MB */
2960                 _stprintf(buffer, sFmtMB, fBytes/1048576.f+.5f);
2961         else if (bytes >= 1024)         /* 1 kB */
2962                 _stprintf(buffer, sFmtkB, fBytes/1024.f+.5f);
2963         else
2964                 _stprintf(buffer, sLongNumFmt, bytes);
2965 }
2966
2967 static void set_space_status(void)
2968 {
2969         ULARGE_INTEGER ulFreeBytesToCaller, ulTotalBytes, ulFreeBytes;
2970         TCHAR fmt[64], b1[64], b2[64], buffer[BUFFER_LEN];
2971
2972         if (GetDiskFreeSpaceEx(NULL, &ulFreeBytesToCaller, &ulTotalBytes, &ulFreeBytes)) {
2973                 format_bytes(b1, ulFreeBytesToCaller.QuadPart);
2974                 format_bytes(b2, ulTotalBytes.QuadPart);
2975                 wsprintf(buffer, RS(fmt,IDS_FREE_SPACE_FMT), b1, b2);
2976         } else
2977                 lstrcpy(buffer, sQMarks);
2978
2979         SendMessage(Globals.hstatusbar, SB_SETTEXT, 0, (LPARAM)buffer);
2980 }
2981
2982
2983 static WNDPROC g_orgTreeWndProc;
2984
2985 static void create_tree_window(HWND parent, Pane* pane, int id, int id_header, LPCTSTR pattern, int filter_flags)
2986 {
2987         static const TCHAR sListBox[] = {'L','i','s','t','B','o','x','\0'};
2988
2989         static int s_init = 0;
2990         Entry* entry = pane->root;
2991
2992         pane->hwnd = CreateWindow(sListBox, sEmpty, WS_CHILD|WS_VISIBLE|WS_HSCROLL|WS_VSCROLL|
2993                                                                 LBS_DISABLENOSCROLL|LBS_NOINTEGRALHEIGHT|LBS_OWNERDRAWFIXED|LBS_NOTIFY,
2994                                                                 0, 0, 0, 0, parent, (HMENU)id, Globals.hInstance, 0);
2995
2996         SetWindowLongPtr(pane->hwnd, GWLP_USERDATA, (LPARAM)pane);
2997         g_orgTreeWndProc = (WNDPROC) SetWindowLongPtr(pane->hwnd, GWLP_WNDPROC, (LPARAM)TreeWndProc);
2998
2999         SendMessage(pane->hwnd, WM_SETFONT, (WPARAM)Globals.hfont, FALSE);
3000
3001         /* insert entries into listbox */
3002         if (entry)
3003                 insert_entries(pane, entry, pattern, filter_flags, -1);
3004
3005         /* calculate column widths */
3006         if (!s_init) {
3007                 s_init = 1;
3008                 init_output(pane->hwnd);
3009         }
3010
3011         calc_widths(pane, TRUE);
3012
3013 #ifndef _NO_EXTENSIONS
3014         pane->hwndHeader = create_header(parent, pane, id_header);
3015 #endif
3016 }
3017
3018
3019 static void InitChildWindow(ChildWnd* child)
3020 {
3021         create_tree_window(child->hwnd, &child->left, IDW_TREE_LEFT, IDW_HEADER_LEFT, NULL, TF_ALL);
3022         create_tree_window(child->hwnd, &child->right, IDW_TREE_RIGHT, IDW_HEADER_RIGHT, child->filter_pattern, child->filter_flags);
3023 }
3024
3025
3026 static void format_date(const FILETIME* ft, TCHAR* buffer, int visible_cols)
3027 {
3028         SYSTEMTIME systime;
3029         FILETIME lft;
3030         int len = 0;
3031
3032         *buffer = '\0';
3033
3034         if (!ft->dwLowDateTime && !ft->dwHighDateTime)
3035                 return;
3036
3037         if (!FileTimeToLocalFileTime(ft, &lft))
3038                 {err: lstrcpy(buffer,sQMarks); return;}
3039
3040         if (!FileTimeToSystemTime(&lft, &systime))
3041                 goto err;
3042
3043         if (visible_cols & COL_DATE) {
3044                 len = GetDateFormat(LOCALE_USER_DEFAULT, 0, &systime, 0, buffer, BUFFER_LEN);
3045                 if (!len)
3046                         goto err;
3047         }
3048
3049         if (visible_cols & COL_TIME) {
3050                 if (len)
3051                         buffer[len-1] = ' ';
3052
3053                 buffer[len++] = ' ';
3054
3055                 if (!GetTimeFormat(LOCALE_USER_DEFAULT, 0, &systime, 0, buffer+len, BUFFER_LEN-len))
3056                         buffer[len] = '\0';
3057         }
3058 }
3059
3060
3061 static void calc_width(Pane* pane, LPDRAWITEMSTRUCT dis, int col, LPCTSTR str)
3062 {
3063         RECT rt = {0, 0, 0, 0};
3064
3065         DrawText(dis->hDC, str, -1, &rt, DT_CALCRECT|DT_SINGLELINE|DT_NOPREFIX);
3066
3067         if (rt.right > pane->widths[col])
3068                 pane->widths[col] = rt.right;
3069 }
3070
3071 static void calc_tabbed_width(Pane* pane, LPDRAWITEMSTRUCT dis, int col, LPCTSTR str)
3072 {
3073         RECT rt = {0, 0, 0, 0};
3074
3075 /*      DRAWTEXTPARAMS dtp = {sizeof(DRAWTEXTPARAMS), 2};
3076         DrawTextEx(dis->hDC, (LPTSTR)str, -1, &rt, DT_CALCRECT|DT_SINGLELINE|DT_NOPREFIX|DT_EXPANDTABS|DT_TABSTOP, &dtp);*/
3077
3078         DrawText(dis->hDC, str, -1, &rt, DT_CALCRECT|DT_SINGLELINE|DT_EXPANDTABS|DT_TABSTOP|(2<<8));
3079         /*FIXME rt (0,0) ??? */
3080
3081         if (rt.right > pane->widths[col])
3082                 pane->widths[col] = rt.right;
3083 }
3084
3085
3086 static void output_text(Pane* pane, LPDRAWITEMSTRUCT dis, int col, LPCTSTR str, DWORD flags)
3087 {
3088         int x = dis->rcItem.left;
3089         RECT rt;
3090
3091         rt.left   = x+pane->positions[col]+Globals.spaceSize.cx;
3092         rt.top    = dis->rcItem.top;
3093         rt.right  = x+pane->positions[col+1]-Globals.spaceSize.cx;
3094         rt.bottom = dis->rcItem.bottom;
3095
3096         DrawText(dis->hDC, str, -1, &rt, DT_SINGLELINE|DT_NOPREFIX|flags);
3097 }
3098
3099 static void output_tabbed_text(Pane* pane, LPDRAWITEMSTRUCT dis, int col, LPCTSTR str)
3100 {
3101         int x = dis->rcItem.left;
3102         RECT rt;
3103
3104         rt.left   = x+pane->positions[col]+Globals.spaceSize.cx;
3105         rt.top    = dis->rcItem.top;
3106         rt.right  = x+pane->positions[col+1]-Globals.spaceSize.cx;
3107         rt.bottom = dis->rcItem.bottom;
3108
3109 /*      DRAWTEXTPARAMS dtp = {sizeof(DRAWTEXTPARAMS), 2};
3110         DrawTextEx(dis->hDC, (LPTSTR)str, -1, &rt, DT_SINGLELINE|DT_NOPREFIX|DT_EXPANDTABS|DT_TABSTOP, &dtp);*/
3111
3112         DrawText(dis->hDC, str, -1, &rt, DT_SINGLELINE|DT_EXPANDTABS|DT_TABSTOP|(2<<8));
3113 }
3114
3115 static void output_number(Pane* pane, LPDRAWITEMSTRUCT dis, int col, LPCTSTR str)
3116 {
3117         int x = dis->rcItem.left;
3118         RECT rt;
3119         LPCTSTR s = str;
3120         TCHAR b[128];
3121         LPTSTR d = b;
3122         int pos;
3123
3124         rt.left   = x+pane->positions[col]+Globals.spaceSize.cx;
3125         rt.top    = dis->rcItem.top;
3126         rt.right  = x+pane->positions[col+1]-Globals.spaceSize.cx;
3127         rt.bottom = dis->rcItem.bottom;
3128
3129         if (*s)
3130                 *d++ = *s++;
3131
3132         /* insert number separator characters */
3133         pos = lstrlen(s) % 3;
3134
3135         while(*s)
3136                 if (pos--)
3137                         *d++ = *s++;
3138                 else {
3139                         *d++ = Globals.num_sep;
3140                         pos = 3;
3141                 }
3142
3143         DrawText(dis->hDC, b, d-b, &rt, DT_RIGHT|DT_SINGLELINE|DT_NOPREFIX|DT_END_ELLIPSIS);
3144 }
3145
3146
3147 static BOOL is_exe_file(LPCTSTR ext)
3148 {
3149         static const TCHAR executable_extensions[][4] = {
3150                 {'C','O','M','\0'},
3151                 {'E','X','E','\0'},
3152                 {'B','A','T','\0'},
3153                 {'C','M','D','\0'},
3154 #ifndef _NO_EXTENSIONS
3155                 {'C','M','M','\0'},
3156                 {'B','T','M','\0'},
3157                 {'A','W','K','\0'},
3158 #endif /* _NO_EXTENSIONS */
3159                 {'\0'}
3160         };
3161
3162         TCHAR ext_buffer[_MAX_EXT];
3163         const TCHAR (*p)[4];
3164         LPCTSTR s;
3165         LPTSTR d;
3166
3167         for(s=ext+1,d=ext_buffer; (*d=tolower(*s)); s++)
3168                 d++;
3169
3170         for(p=executable_extensions; (*p)[0]; p++)
3171                 if (!lstrcmpi(ext_buffer, *p))
3172                         return TRUE;
3173
3174         return FALSE;
3175 }
3176
3177 static BOOL is_registered_type(LPCTSTR ext)
3178 {
3179         /* check if there exists a classname for this file extension in the registry */
3180         if (!RegQueryValue(HKEY_CLASSES_ROOT, ext, NULL, NULL))
3181                 return TRUE;
3182
3183         return FALSE;
3184 }
3185
3186 static enum FILE_TYPE get_file_type(LPCTSTR filename)
3187 {
3188         LPCTSTR ext = _tcsrchr(filename, '.');
3189         if (!ext)
3190                 ext = sEmpty;
3191
3192         if (is_exe_file(ext))
3193                 return FT_EXECUTABLE;
3194         else if (is_registered_type(ext))
3195                 return FT_DOCUMENT;
3196         else
3197                 return FT_OTHER;
3198 }
3199
3200
3201 static void draw_item(Pane* pane, LPDRAWITEMSTRUCT dis, Entry* entry, int calcWidthCol)
3202 {
3203         TCHAR buffer[BUFFER_LEN];
3204         DWORD attrs;
3205         int visible_cols = pane->visible_cols;
3206         COLORREF bkcolor, textcolor;
3207         RECT focusRect = dis->rcItem;
3208         HBRUSH hbrush;
3209         enum IMAGE img;
3210         int img_pos, cx;
3211         int col = 0;
3212
3213         if (entry) {
3214                 attrs = entry->data.dwFileAttributes;
3215
3216                 if (attrs & FILE_ATTRIBUTE_DIRECTORY) {
3217                         if (entry->data.cFileName[0] == '.' && entry->data.cFileName[1] == '.'
3218                                         && entry->data.cFileName[2] == '\0')
3219                                 img = IMG_FOLDER_UP;
3220 #ifndef _NO_EXTENSIONS
3221                         else if (entry->data.cFileName[0] == '.' && entry->data.cFileName[1] == '\0')
3222                                 img = IMG_FOLDER_CUR;
3223 #endif
3224                         else if (
3225 #ifdef _NO_EXTENSIONS
3226                                          entry->expanded ||
3227 #endif
3228                                          (pane->treePane && (dis->itemState&ODS_FOCUS)))
3229                                 img = IMG_OPEN_FOLDER;
3230                         else
3231                                 img = IMG_FOLDER;
3232                 } else {
3233                         switch(get_file_type(entry->data.cFileName)) {
3234                           case FT_EXECUTABLE:   img = IMG_EXECUTABLE;   break;
3235                           case FT_DOCUMENT:             img = IMG_DOCUMENT;             break;
3236                           default:                              img = IMG_FILE;
3237                         }
3238                 }
3239         } else {
3240                 attrs = 0;
3241                 img = IMG_NONE;
3242         }
3243
3244         if (pane->treePane) {
3245                 if (entry) {
3246                         img_pos = dis->rcItem.left + entry->level*(IMAGE_WIDTH+TREE_LINE_DX);
3247
3248                         if (calcWidthCol == -1) {
3249                                 int x;
3250                                 int y = dis->rcItem.top + IMAGE_HEIGHT/2;
3251                                 Entry* up;
3252                                 RECT rt_clip;
3253                                 HRGN hrgn_org = CreateRectRgn(0, 0, 0, 0);
3254                                 HRGN hrgn;
3255
3256                                 rt_clip.left   = dis->rcItem.left;
3257                                 rt_clip.top    = dis->rcItem.top;
3258                                 rt_clip.right  = dis->rcItem.left+pane->widths[col];
3259                                 rt_clip.bottom = dis->rcItem.bottom;
3260
3261                                 hrgn = CreateRectRgnIndirect(&rt_clip);
3262
3263                                 if (!GetClipRgn(dis->hDC, hrgn_org)) {
3264                                         DeleteObject(hrgn_org);
3265                                         hrgn_org = 0;
3266                                 }
3267
3268                                 /* HGDIOBJ holdPen = SelectObject(dis->hDC, GetStockObject(BLACK_PEN)); */
3269                                 ExtSelectClipRgn(dis->hDC, hrgn, RGN_AND);
3270                                 DeleteObject(hrgn);
3271
3272                                 if ((up=entry->up) != NULL) {
3273                                         MoveToEx(dis->hDC, img_pos-IMAGE_WIDTH/2, y, 0);
3274                                         LineTo(dis->hDC, img_pos-2, y);
3275
3276                                         x = img_pos - IMAGE_WIDTH/2;
3277
3278                                         do {
3279                                                 x -= IMAGE_WIDTH+TREE_LINE_DX;
3280
3281                                                 if (up->next
3282 #ifndef _LEFT_FILES
3283                                                         && (up->next->data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
3284 #endif
3285                                                         ) {
3286                                                         MoveToEx(dis->hDC, x, dis->rcItem.top, 0);
3287                                                         LineTo(dis->hDC, x, dis->rcItem.bottom);
3288                                                 }
3289                                         } while((up=up->up) != NULL);
3290                                 }
3291
3292                                 x = img_pos - IMAGE_WIDTH/2;
3293
3294                                 MoveToEx(dis->hDC, x, dis->rcItem.top, 0);
3295                                 LineTo(dis->hDC, x, y);
3296
3297                                 if (entry->next
3298 #ifndef _LEFT_FILES
3299                                         && (entry->next->data.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY)
3300 #endif
3301                                         )
3302                                         LineTo(dis->hDC, x, dis->rcItem.bottom);
3303
3304                                 SelectClipRgn(dis->hDC, hrgn_org);
3305                                 if (hrgn_org) DeleteObject(hrgn_org);
3306                                 /* SelectObject(dis->hDC, holdPen); */
3307                         } else if (calcWidthCol==col || calcWidthCol==COLUMNS) {
3308                                 int right = img_pos + IMAGE_WIDTH - TREE_LINE_DX;
3309
3310                                 if (right > pane->widths[col])
3311                                         pane->widths[col] = right;
3312                         }
3313                 } else  {
3314                         img_pos = dis->rcItem.left;
3315                 }
3316         } else {
3317                 img_pos = dis->rcItem.left;
3318
3319                 if (calcWidthCol==col || calcWidthCol==COLUMNS)
3320                         pane->widths[col] = IMAGE_WIDTH;
3321         }
3322
3323         if (calcWidthCol == -1) {
3324                 focusRect.left = img_pos -2;
3325
3326 #ifdef _NO_EXTENSIONS
3327                 if (pane->treePane && entry) {
3328                         RECT rt = {0};
3329
3330                         DrawText(dis->hDC, entry->data.cFileName, -1, &rt, DT_CALCRECT|DT_SINGLELINE|DT_NOPREFIX);
3331
3332                         focusRect.right = dis->rcItem.left+pane->positions[col+1]+TREE_LINE_DX + rt.right +2;
3333                 }
3334 #else
3335
3336                 if (attrs & FILE_ATTRIBUTE_COMPRESSED)
3337                         textcolor = COLOR_COMPRESSED;
3338                 else
3339 #endif /* _NO_EXTENSIONS */
3340                         textcolor = RGB(0,0,0);
3341
3342                 if (dis->itemState & ODS_FOCUS) {
3343                         textcolor = RGB(255,255,255);
3344                         bkcolor = COLOR_SELECTION;
3345                 } else {
3346                         bkcolor = RGB(255,255,255);
3347                 }
3348
3349                 hbrush = CreateSolidBrush(bkcolor);
3350                 FillRect(dis->hDC, &focusRect, hbrush);
3351                 DeleteObject(hbrush);
3352
3353                 SetBkMode(dis->hDC, TRANSPARENT);
3354                 SetTextColor(dis->hDC, textcolor);
3355
3356                 cx = pane->widths[col];
3357
3358                 if (cx && img!=IMG_NONE) {
3359                         if (cx > IMAGE_WIDTH)
3360                                 cx = IMAGE_WIDTH;
3361
3362 #ifdef _SHELL_FOLDERS
3363                         if (entry->hicon && entry->hicon!=(HICON)-1)
3364                                 DrawIconEx(dis->hDC, img_pos, dis->rcItem.top, entry->hicon, cx, GetSystemMetrics(SM_CYSMICON), 0, 0, DI_NORMAL);
3365                         else
3366 #endif
3367                                 ImageList_DrawEx(Globals.himl, img, dis->hDC,
3368                                                                  img_pos, dis->rcItem.top, cx,
3369                                                                  IMAGE_HEIGHT, bkcolor, CLR_DEFAULT, ILD_NORMAL);
3370                 }
3371         }
3372
3373         if (!entry)
3374                 return;
3375
3376 #ifdef _NO_EXTENSIONS
3377         if (img >= IMG_FOLDER_UP)
3378                 return;
3379 #endif
3380
3381         col++;
3382
3383         /* ouput file name */
3384         if (calcWidthCol == -1)
3385                 output_text(pane, dis, col, entry->data.cFileName, 0);
3386         else if (calcWidthCol==col || calcWidthCol==COLUMNS)
3387                 calc_width(pane, dis, col, entry->data.cFileName);
3388
3389         col++;
3390
3391 #ifdef _NO_EXTENSIONS
3392   if (!pane->treePane) {
3393 #endif
3394
3395         /* display file size */
3396         if (visible_cols & COL_SIZE) {
3397 #ifdef _NO_EXTENSIONS
3398                 if (!(attrs&FILE_ATTRIBUTE_DIRECTORY))
3399 #endif
3400                 {
3401                         ULONGLONG size;
3402
3403                         size = ((ULONGLONG)entry->data.nFileSizeHigh << 32) | entry->data.nFileSizeLow;
3404
3405                         _stprintf(buffer, sLongNumFmt, size);
3406
3407                         if (calcWidthCol == -1)
3408                                 output_number(pane, dis, col, buffer);
3409                         else if (calcWidthCol==col || calcWidthCol==COLUMNS)
3410                                 calc_width(pane, dis, col, buffer);/*TODO: not ever time enough */
3411                 }
3412
3413                 col++;
3414         }
3415
3416         /* display file date */
3417         if (visible_cols & (COL_DATE|COL_TIME)) {
3418 #ifndef _NO_EXTENSIONS
3419                 format_date(&entry->data.ftCreationTime, buffer, visible_cols);
3420                 if (calcWidthCol == -1)
3421                         output_text(pane, dis, col, buffer, 0);
3422                 else if (calcWidthCol==col || calcWidthCol==COLUMNS)
3423                         calc_width(pane, dis, col, buffer);
3424                 col++;
3425
3426                 format_date(&entry->data.ftLastAccessTime, buffer, visible_cols);
3427                 if (calcWidthCol == -1)
3428                         output_text(pane, dis, col, buffer, 0);
3429                 else if (calcWidthCol==col || calcWidthCol==COLUMNS)
3430                         calc_width(pane, dis, col, buffer);
3431                 col++;
3432 #endif /* _NO_EXTENSIONS */
3433
3434                 format_date(&entry->data.ftLastWriteTime, buffer, visible_cols);
3435                 if (calcWidthCol == -1)
3436                         output_text(pane, dis, col, buffer, 0);
3437                 else if (calcWidthCol==col || calcWidthCol==COLUMNS)
3438                         calc_width(pane, dis, col, buffer);
3439                 col++;
3440         }
3441
3442 #ifndef _NO_EXTENSIONS
3443         if (entry->bhfi_valid) {
3444             ULONGLONG index = ((ULONGLONG)entry->bhfi.nFileIndexHigh << 32) | entry->bhfi.nFileIndexLow;
3445
3446                 if (visible_cols & COL_INDEX) {
3447                         _stprintf(buffer, sLongHexFmt, index);
3448
3449                         if (calcWidthCol == -1)
3450                                 output_text(pane, dis, col, buffer, DT_RIGHT);
3451                         else if (calcWidthCol==col || calcWidthCol==COLUMNS)
3452                                 calc_width(pane, dis, col, buffer);
3453
3454                         col++;
3455                 }
3456
3457                 if (visible_cols & COL_LINKS) {
3458                         wsprintf(buffer, sNumFmt, entry->bhfi.nNumberOfLinks);
3459
3460                         if (calcWidthCol == -1)
3461                                 output_text(pane, dis, col, buffer, DT_CENTER);
3462                         else if (calcWidthCol==col || calcWidthCol==COLUMNS)
3463                                 calc_width(pane, dis, col, buffer);
3464
3465                         col++;
3466                 }
3467         } else
3468                 col += 2;
3469 #endif /* _NO_EXTENSIONS */
3470
3471         /* show file attributes */
3472         if (visible_cols & COL_ATTRIBUTES) {
3473 #ifdef _NO_EXTENSIONS
3474                 static const TCHAR s4Tabs[] = {' ','\t',' ','\t',' ','\t',' ','\t',' ','\0'};
3475                 lstrcpy(buffer, s4Tabs);
3476 #else
3477                 static const TCHAR s11Tabs[] = {' ','\t',' ','\t',' ','\t',' ','\t',' ','\t',' ','\t',' ','\t',' ','\t',' ','\t',' ','\t',' ','\t',' ','\0'};
3478                 lstrcpy(buffer, s11Tabs);
3479 #endif
3480
3481                 if (attrs & FILE_ATTRIBUTE_NORMAL)                                      buffer[ 0] = 'N';
3482                 else {
3483                         if (attrs & FILE_ATTRIBUTE_READONLY)                    buffer[ 2] = 'R';
3484                         if (attrs & FILE_ATTRIBUTE_HIDDEN)                              buffer[ 4] = 'H';
3485                         if (attrs & FILE_ATTRIBUTE_SYSTEM)                              buffer[ 6] = 'S';
3486                         if (attrs & FILE_ATTRIBUTE_ARCHIVE)                             buffer[ 8] = 'A';
3487                         if (attrs & FILE_ATTRIBUTE_COMPRESSED)                  buffer[10] = 'C';
3488 #ifndef _NO_EXTENSIONS
3489                         if (attrs & FILE_ATTRIBUTE_DIRECTORY)                   buffer[12] = 'D';
3490                         if (attrs & FILE_ATTRIBUTE_ENCRYPTED)                   buffer[14] = 'E';
3491                         if (attrs & FILE_ATTRIBUTE_TEMPORARY)                   buffer[16] = 'T';
3492                         if (attrs & FILE_ATTRIBUTE_SPARSE_FILE)                 buffer[18] = 'P';
3493                         if (attrs & FILE_ATTRIBUTE_REPARSE_POINT)               buffer[20] = 'Q';
3494                         if (attrs & FILE_ATTRIBUTE_OFFLINE)                             buffer[22] = 'O';
3495                         if (attrs & FILE_ATTRIBUTE_NOT_CONTENT_INDEXED) buffer[24] = 'X';
3496 #endif /* _NO_EXTENSIONS */
3497                 }
3498
3499                 if (calcWidthCol == -1)
3500                         output_tabbed_text(pane, dis, col, buffer);
3501                 else if (calcWidthCol==col || calcWidthCol==COLUMNS)
3502                         calc_tabbed_width(pane, dis, col, buffer);
3503
3504                 col++;
3505         }
3506
3507 /*TODO
3508         if (flags.security) {
3509                 static const TCHAR sSecTabs[] = {
3510                         ' ','\t',' ','\t',' ','\t',' ',
3511                         ' ','\t',' ',
3512                         ' ','\t',' ','\t',' ','\t',' ',
3513                         ' ','\t',' ',
3514                         ' ','\t',' ','\t',' ','\t',' ',
3515                         '\0'
3516                 };
3517
3518                 DWORD rights = get_access_mask();
3519
3520                 lstrcpy(buffer, sSecTabs);
3521
3522                 if (rights & FILE_READ_DATA)                    buffer[ 0] = 'R';
3523                 if (rights & FILE_WRITE_DATA)                   buffer[ 2] = 'W';
3524                 if (rights & FILE_APPEND_DATA)                  buffer[ 4] = 'A';
3525                 if (rights & FILE_READ_EA)                              {buffer[6] = 'entry'; buffer[ 7] = 'R';}
3526                 if (rights & FILE_WRITE_EA)                             {buffer[9] = 'entry'; buffer[10] = 'W';}
3527                 if (rights & FILE_EXECUTE)                              buffer[12] = 'X';
3528                 if (rights & FILE_DELETE_CHILD)                 buffer[14] = 'D';
3529                 if (rights & FILE_READ_ATTRIBUTES)              {buffer[16] = 'a'; buffer[17] = 'R';}
3530                 if (rights & FILE_WRITE_ATTRIBUTES)             {buffer[19] = 'a'; buffer[20] = 'W';}
3531                 if (rights & WRITE_DAC)                                 buffer[22] = 'C';
3532                 if (rights & WRITE_OWNER)                               buffer[24] = 'O';
3533                 if (rights & SYNCHRONIZE)                               buffer[26] = 'S';
3534
3535                 output_text(dis, col++, buffer, DT_LEFT, 3, psize);
3536         }
3537
3538         if (flags.description) {
3539                 get_description(buffer);
3540                 output_text(dis, col++, buffer, 0, psize);
3541         }
3542 */
3543
3544 #ifdef _NO_EXTENSIONS
3545   }
3546
3547         /* draw focus frame */
3548         if ((dis->itemState&ODS_FOCUS) && calcWidthCol==-1) {
3549                 /* Currently [04/2000] Wine neither behaves exactly the same */
3550                 /* way as WIN 95 nor like Windows NT... */
3551                 HGDIOBJ lastBrush;
3552                 HPEN lastPen;
3553                 HPEN hpen;
3554
3555                 if (!(GetVersion() & 0x80000000)) {     /* Windows NT? */
3556                         LOGBRUSH lb = {PS_SOLID, RGB(255,255,255)};
3557                         hpen = ExtCreatePen(PS_COSMETIC|PS_ALTERNATE, 1, &lb, 0, 0);
3558                 } else
3559                         hpen = CreatePen(PS_DOT, 0, RGB(255,255,255));
3560
3561                 lastPen = SelectPen(dis->hDC, hpen);
3562                 lastBrush = SelectObject(dis->hDC, GetStockObject(HOLLOW_BRUSH));
3563                 SetROP2(dis->hDC, R2_XORPEN);
3564                 Rectangle(dis->hDC, focusRect.left, focusRect.top, focusRect.right, focusRect.bottom);
3565                 SelectObject(dis->hDC, lastBrush);
3566                 SelectObject(dis->hDC, lastPen);
3567                 DeleteObject(hpen);
3568         }
3569 #endif /* _NO_EXTENSIONS */
3570 }
3571
3572
3573 #ifdef _NO_EXTENSIONS
3574
3575 static void draw_splitbar(HWND hwnd, int x)
3576 {
3577         RECT rt;
3578         HDC hdc = GetDC(hwnd);
3579
3580         GetClientRect(hwnd, &rt);
3581
3582         rt.left = x - SPLIT_WIDTH/2;
3583         rt.right = x + SPLIT_WIDTH/2+1;
3584
3585         InvertRect(hdc, &rt);
3586
3587         ReleaseDC(hwnd, hdc);
3588 }
3589
3590 #endif /* _NO_EXTENSIONS */
3591
3592
3593 #ifndef _NO_EXTENSIONS
3594
3595 static void set_header(Pane* pane)
3596 {
3597         HD_ITEM item;
3598         int scroll_pos = GetScrollPos(pane->hwnd, SB_HORZ);
3599         int i=0, x=0;
3600
3601         item.mask = HDI_WIDTH;
3602         item.cxy = 0;
3603
3604         for(; x+pane->widths[i]<scroll_pos && i<COLUMNS; i++) {
3605                 x += pane->widths[i];
3606                 SendMessage(pane->hwndHeader, HDM_SETITEM, i, (LPARAM) &item);
3607         }
3608
3609         if (i < COLUMNS) {
3610                 x += pane->widths[i];
3611                 item.cxy = x - scroll_pos;
3612                 SendMessage(pane->hwndHeader, HDM_SETITEM, i++, (LPARAM) &item);
3613
3614                 for(; i<COLUMNS; i++) {
3615                         item.cxy = pane->widths[i];
3616                         x += pane->widths[i];
3617                         SendMessage(pane->hwndHeader, HDM_SETITEM, i, (LPARAM) &item);
3618                 }
3619         }
3620 }
3621
3622 static LRESULT pane_notify(Pane* pane, NMHDR* pnmh)
3623 {
3624         switch(pnmh->code) {
3625                 case HDN_ITEMCHANGED: {
3626                         HD_NOTIFY* phdn = (HD_NOTIFY*) pnmh;
3627                         int idx = phdn->iItem;
3628                         int dx = phdn->pitem->cxy - pane->widths[idx];
3629                         int i;
3630
3631                         RECT clnt;
3632                         GetClientRect(pane->hwnd, &clnt);
3633
3634                         pane->widths[idx] += dx;
3635
3636                         for(i=idx; ++i<=COLUMNS; )
3637                                 pane->positions[i] += dx;
3638
3639                         {
3640                                 int scroll_pos = GetScrollPos(pane->hwnd, SB_HORZ);
3641                                 RECT rt_scr;
3642                                 RECT rt_clip;
3643
3644                                 rt_scr.left   = pane->positions[idx+1]-scroll_pos;
3645                                 rt_scr.top    = 0;
3646                                 rt_scr.right  = clnt.right;
3647                                 rt_scr.bottom = clnt.bottom;
3648
3649                                 rt_clip.left   = pane->positions[idx]-scroll_pos;
3650                                 rt_clip.top    = 0;
3651                                 rt_clip.right  = clnt.right;
3652                                 rt_clip.bottom = clnt.bottom;
3653
3654                                 if (rt_scr.left < 0) rt_scr.left = 0;
3655                                 if (rt_clip.left < 0) rt_clip.left = 0;
3656
3657                                 ScrollWindowEx(pane->hwnd, dx, 0, &rt_scr, &rt_clip, 0, 0, SW_INVALIDATE);
3658
3659                                 rt_clip.right = pane->positions[idx+1];
3660                                 RedrawWindow(pane->hwnd, &rt_clip, 0, RDW_INVALIDATE|RDW_UPDATENOW);
3661
3662                                 if (pnmh->code == HDN_ENDTRACK) {
3663                                         SendMessage(pane->hwnd, LB_SETHORIZONTALEXTENT, pane->positions[COLUMNS], 0);
3664
3665                                         if (GetScrollPos(pane->hwnd, SB_HORZ) != scroll_pos)
3666                                                 set_header(pane);
3667                                 }
3668                         }
3669
3670                         return FALSE;
3671                 }
3672
3673                 case HDN_DIVIDERDBLCLICK: {
3674                         HD_NOTIFY* phdn = (HD_NOTIFY*) pnmh;
3675                         HD_ITEM item;
3676
3677                         calc_single_width(pane, phdn->iItem);
3678                         item.mask = HDI_WIDTH;
3679                         item.cxy = pane->widths[phdn->iItem];
3680
3681                         SendMessage(pane->hwndHeader, HDM_SETITEM, phdn->iItem, (LPARAM) &item);
3682                         InvalidateRect(pane->hwnd, 0, TRUE);
3683                         break;}
3684         }
3685
3686         return 0;
3687 }
3688
3689 #endif /* _NO_EXTENSIONS */
3690
3691
3692 static void scan_entry(ChildWnd* child, Entry* entry, int idx, HWND hwnd)
3693 {
3694         TCHAR path[MAX_PATH];
3695         HCURSOR old_cursor = SetCursor(LoadCursor(0, IDC_WAIT));
3696
3697         /* delete sub entries in left pane */
3698         for(;;) {
3699                 LRESULT res = SendMessage(child->left.hwnd, LB_GETITEMDATA, idx+1, 0);
3700                 Entry* sub = (Entry*) res;
3701
3702                 if (res==LB_ERR || !sub || sub->level<=entry->level)
3703                         break;
3704
3705                 SendMessage(child->left.hwnd, LB_DELETESTRING, idx+1, 0);
3706         }
3707
3708         /* empty right pane */
3709         SendMessage(child->right.hwnd, LB_RESETCONTENT, 0, 0);
3710
3711         /* release memory */
3712         free_entries(entry);
3713
3714         /* read contents from disk */
3715 #ifdef _SHELL_FOLDERS
3716         if (entry->etype == ET_SHELL)
3717         {
3718                 read_directory(entry, NULL, child->sortOrder, hwnd);
3719         }
3720         else
3721 #endif
3722         {
3723                 get_path(entry, path);
3724                 read_directory(entry, path, child->sortOrder, hwnd);
3725         }
3726
3727         /* insert found entries in right pane */
3728         insert_entries(&child->right, entry->down, child->filter_pattern, child->filter_flags, -1);
3729         calc_widths(&child->right, FALSE);
3730 #ifndef _NO_EXTENSIONS
3731         set_header(&child->right);
3732 #endif
3733
3734         child->header_wdths_ok = FALSE;
3735
3736         SetCursor(old_cursor);
3737 }
3738
3739
3740 /* expand a directory entry */
3741
3742 static BOOL expand_entry(ChildWnd* child, Entry* dir)
3743 {
3744         int idx;
3745         Entry* p;
3746
3747         if (!dir || dir->expanded || !dir->down)
3748                 return FALSE;
3749
3750         p = dir->down;
3751
3752         if (p->data.cFileName[0]=='.' && p->data.cFileName[1]=='\0' && p->next) {
3753                 p = p->next;
3754
3755                 if (p->data.cFileName[0]=='.' && p->data.cFileName[1]=='.' &&
3756                                 p->data.cFileName[2]=='\0' && p->next)
3757                         p = p->next;
3758         }
3759
3760         /* no subdirectories ? */
3761         if (!(p->data.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY))
3762                 return FALSE;
3763
3764         idx = SendMessage(child->left.hwnd, LB_FINDSTRING, 0, (LPARAM)dir);
3765
3766         dir->expanded = TRUE;
3767
3768         /* insert entries in left pane */
3769         insert_entries(&child->left, p, NULL, TF_ALL, idx);
3770
3771         if (!child->header_wdths_ok) {
3772                 if (calc_widths(&child->left, FALSE)) {
3773 #ifndef _NO_EXTENSIONS
3774                         set_header(&child->left);
3775 #endif
3776
3777                         child->header_wdths_ok = TRUE;
3778                 }
3779         }
3780
3781         return TRUE;
3782 }
3783
3784
3785 static void collapse_entry(Pane* pane, Entry* dir)
3786 {
3787         int idx = SendMessage(pane->hwnd, LB_FINDSTRING, 0, (LPARAM)dir);
3788
3789         ShowWindow(pane->hwnd, SW_HIDE);
3790
3791         /* hide sub entries */
3792         for(;;) {
3793                 LRESULT res = SendMessage(pane->hwnd, LB_GETITEMDATA, idx+1, 0);
3794                 Entry* sub = (Entry*) res;
3795
3796                 if (res==LB_ERR || !sub || sub->level<=dir->level)
3797                         break;
3798
3799                 SendMessage(pane->hwnd, LB_DELETESTRING, idx+1, 0);
3800         }
3801
3802         dir->expanded = FALSE;
3803
3804         ShowWindow(pane->hwnd, SW_SHOW);
3805 }
3806
3807
3808 static void refresh_right_pane(ChildWnd* child)
3809 {
3810         SendMessage(child->right.hwnd, LB_RESETCONTENT, 0, 0);
3811         insert_entries(&child->right, child->right.root, child->filter_pattern, child->filter_flags, -1);
3812         calc_widths(&child->right, FALSE);
3813
3814 #ifndef _NO_EXTENSIONS
3815         set_header(&child->right);
3816 #endif
3817 }
3818
3819 static void set_curdir(ChildWnd* child, Entry* entry, int idx, HWND hwnd)
3820 {
3821         TCHAR path[MAX_PATH];
3822
3823         if (!entry)
3824                 return;
3825
3826         path[0] = '\0';
3827
3828         child->left.cur = entry;
3829
3830         child->right.root = entry->down? entry->down: entry;
3831         child->right.cur = entry;
3832
3833         if (!entry->scanned)
3834                 scan_entry(child, entry, idx, hwnd);
3835         else
3836                 refresh_right_pane(child);
3837
3838         get_path(entry, path);
3839         lstrcpy(child->path, path);
3840
3841         if (child->hwnd)        /* only change window title, if the window already exists */
3842                 SetWindowText(child->hwnd, path);
3843
3844         if (path[0])
3845                 if (SetCurrentDirectory(path))
3846                         set_space_status();
3847 }
3848
3849
3850 static void refresh_child(ChildWnd* child)
3851 {
3852         TCHAR path[MAX_PATH], drv[_MAX_DRIVE+1];
3853         Entry* entry;
3854         int idx;
3855
3856         get_path(child->left.cur, path);
3857         _tsplitpath(path, drv, NULL, NULL, NULL);
3858
3859         child->right.root = NULL;
3860
3861         scan_entry(child, &child->root.entry, 0, child->hwnd);
3862
3863 #ifdef _SHELL_FOLDERS
3864         if (child->root.entry.etype == ET_SHELL)
3865                 entry = read_tree(&child->root, NULL, get_path_pidl(path,child->hwnd), drv, child->sortOrder, child->hwnd);
3866         else
3867 #endif
3868                 entry = read_tree(&child->root, path, NULL, drv, child->sortOrder, child->hwnd);
3869
3870         if (!entry)
3871                 entry = &child->root.entry;
3872
3873         insert_entries(&child->left, child->root.entry.down, NULL, TF_ALL, 0);
3874
3875         set_curdir(child, entry, 0, child->hwnd);
3876
3877         idx = SendMessage(child->left.hwnd, LB_FINDSTRING, 0, (LPARAM)child->left.cur);
3878         SendMessage(child->left.hwnd, LB_SETCURSEL, idx, 0);
3879 }
3880
3881
3882 static void create_drive_bar(void)
3883 {
3884         TBBUTTON drivebarBtn = {0, 0, TBSTATE_ENABLED, BTNS_BUTTON, {0, 0}, 0, 0};
3885 #ifndef _NO_EXTENSIONS
3886         TCHAR b1[BUFFER_LEN];
3887 #endif
3888         int btn = 1;
3889         PTSTR p;
3890
3891         GetLogicalDriveStrings(BUFFER_LEN, Globals.drives);
3892
3893         Globals.hdrivebar = CreateToolbarEx(Globals.hMainWnd, WS_CHILD|WS_VISIBLE|CCS_NOMOVEY|TBSTYLE_LIST,
3894                                 IDW_DRIVEBAR, 2, Globals.hInstance, IDB_DRIVEBAR, &drivebarBtn,
3895                                 0, 16, 13, 16, 13, sizeof(TBBUTTON));
3896
3897 #ifndef _NO_EXTENSIONS
3898 #ifdef __WINE__
3899         /* insert unix file system button */
3900         b1[0] = '/';
3901         b1[1] = '\0';
3902         b1[2] = '\0';
3903         SendMessage(Globals.hdrivebar, TB_ADDSTRING, 0, (LPARAM)b1);
3904
3905         drivebarBtn.idCommand = ID_DRIVE_UNIX_FS;
3906         SendMessage(Globals.hdrivebar, TB_INSERTBUTTON, btn++, (LPARAM)&drivebarBtn);
3907         drivebarBtn.iString++;
3908 #endif
3909 #ifdef _SHELL_FOLDERS
3910         /* insert shell namespace button */
3911         load_string(b1, IDS_SHELL);
3912         b1[lstrlen(b1)+1] = '\0';
3913         SendMessage(Globals.hdrivebar, TB_ADDSTRING, 0, (LPARAM)b1);
3914
3915         drivebarBtn.idCommand = ID_DRIVE_SHELL_NS;
3916         SendMessage(Globals.hdrivebar, TB_INSERTBUTTON, btn++, (LPARAM)&drivebarBtn);
3917         drivebarBtn.iString++;
3918 #endif
3919
3920         /* register windows drive root strings */
3921         SendMessage(Globals.hdrivebar, TB_ADDSTRING, 0, (LPARAM)Globals.drives);
3922 #endif
3923
3924         drivebarBtn.idCommand = ID_DRIVE_FIRST;
3925
3926         for(p=Globals.drives; *p; ) {
3927 #ifdef _NO_EXTENSIONS
3928                 /* insert drive letter */
3929                 TCHAR b[3] = {tolower(*p)};
3930                 SendMessage(Globals.hdrivebar, TB_ADDSTRING, 0, (LPARAM)b);
3931 #endif
3932                 switch(GetDriveType(p)) {
3933                         case DRIVE_REMOVABLE:   drivebarBtn.iBitmap = 1;        break;
3934                         case DRIVE_CDROM:               drivebarBtn.iBitmap = 3;        break;
3935                         case DRIVE_REMOTE:              drivebarBtn.iBitmap = 4;        break;
3936                         case DRIVE_RAMDISK:             drivebarBtn.iBitmap = 5;        break;
3937                         default:/*DRIVE_FIXED*/ drivebarBtn.iBitmap = 2;
3938                 }
3939
3940                 SendMessage(Globals.hdrivebar, TB_INSERTBUTTON, btn++, (LPARAM)&drivebarBtn);
3941                 drivebarBtn.idCommand++;
3942                 drivebarBtn.iString++;
3943
3944                 while(*p++);
3945         }
3946 }
3947
3948 static void refresh_drives(void)
3949 {
3950         RECT rect;
3951
3952         /* destroy drive bar */
3953         DestroyWindow(Globals.hdrivebar);
3954         Globals.hdrivebar = 0;
3955
3956         /* re-create drive bar */
3957         create_drive_bar();
3958
3959         /* update window layout */
3960         GetClientRect(Globals.hMainWnd, &rect);
3961         SendMessage(Globals.hMainWnd, WM_SIZE, 0, MAKELONG(rect.right, rect.bottom));
3962 }
3963
3964
3965 static BOOL launch_file(HWND hwnd, LPCTSTR cmd, UINT nCmdShow)
3966 {
3967         HINSTANCE hinst = ShellExecute(hwnd, NULL/*operation*/, cmd, NULL/*parameters*/, NULL/*dir*/, nCmdShow);
3968
3969         if ((int)hinst <= 32) {
3970                 display_error(hwnd, GetLastError());
3971                 return FALSE;
3972         }
3973
3974         return TRUE;
3975 }
3976
3977
3978 static BOOL launch_entry(Entry* entry, HWND hwnd, UINT nCmdShow)
3979 {
3980         TCHAR cmd[MAX_PATH];
3981
3982 #ifdef _SHELL_FOLDERS
3983         if (entry->etype == ET_SHELL) {
3984                 BOOL ret = TRUE;
3985
3986                 SHELLEXECUTEINFO shexinfo;
3987
3988                 shexinfo.cbSize = sizeof(SHELLEXECUTEINFO);
3989                 shexinfo.fMask = SEE_MASK_IDLIST;
3990                 shexinfo.hwnd = hwnd;
3991                 shexinfo.lpVerb = NULL;
3992                 shexinfo.lpFile = NULL;
3993                 shexinfo.lpParameters = NULL;
3994                 shexinfo.lpDirectory = NULL;
3995                 shexinfo.nShow = nCmdShow;
3996                 shexinfo.lpIDList = get_to_absolute_pidl(entry, hwnd);
3997
3998                 if (!ShellExecuteEx(&shexinfo)) {
3999                         display_error(hwnd, GetLastError());
4000                         ret = FALSE;
4001                 }
4002
4003                 if (shexinfo.lpIDList != entry->pidl)
4004                         IMalloc_Free(Globals.iMalloc, shexinfo.lpIDList);
4005
4006                 return ret;
4007         }
4008 #endif
4009
4010         get_path(entry, cmd);
4011
4012          /* start program, open document... */
4013         return launch_file(hwnd, cmd, nCmdShow);
4014 }
4015
4016
4017 static void activate_entry(ChildWnd* child, Pane* pane, HWND hwnd)
4018 {
4019         Entry* entry = pane->cur;
4020
4021         if (!entry)
4022                 return;
4023
4024         if (entry->data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
4025                 int scanned_old = entry->scanned;
4026
4027                 if (!scanned_old)
4028                 {
4029                         int idx = SendMessage(child->left.hwnd, LB_GETCURSEL, 0, 0);
4030                         scan_entry(child, entry, idx, hwnd);
4031                 }
4032
4033 #ifndef _NO_EXTENSIONS
4034                 if (entry->data.cFileName[0]=='.' && entry->data.cFileName[1]=='\0')
4035                         return;
4036 #endif
4037
4038                 if (entry->data.cFileName[0]=='.' && entry->data.cFileName[1]=='.' && entry->data.cFileName[2]=='\0') {
4039                         entry = child->left.cur->up;
4040                         collapse_entry(&child->left, entry);
4041                         goto focus_entry;
4042                 } else if (entry->expanded)
4043                         collapse_entry(pane, child->left.cur);
4044                 else {
4045                         expand_entry(child, child->left.cur);
4046
4047                         if (!pane->treePane) focus_entry: {
4048                                 int idxstart = SendMessage(child->left.hwnd, LB_GETCURSEL, 0, 0);
4049                                 int idx = SendMessage(child->left.hwnd, LB_FINDSTRING, idxstart, (LPARAM)entry);
4050                                 SendMessage(child->left.hwnd, LB_SETCURSEL, idx, 0);
4051                                 set_curdir(child, entry, idx, hwnd);
4052                         }
4053                 }
4054
4055                 if (!scanned_old) {
4056                         calc_widths(pane, FALSE);
4057
4058 #ifndef _NO_EXTENSIONS
4059                         set_header(pane);
4060 #endif
4061                 }
4062         } else {
4063                 if (GetKeyState(VK_MENU) < 0)
4064                         show_properties_dlg(entry, child->hwnd);
4065                 else
4066                         launch_entry(entry, child->hwnd, SW_SHOWNORMAL);
4067         }
4068 }
4069
4070
4071 static BOOL pane_command(Pane* pane, UINT cmd)
4072 {
4073         switch(cmd) {
4074                 case ID_VIEW_NAME:
4075                         if (pane->visible_cols) {
4076                                 pane->visible_cols = 0;
4077                                 calc_widths(pane, TRUE);
4078 #ifndef _NO_EXTENSIONS
4079                                 set_header(pane);
4080 #endif
4081                                 InvalidateRect(pane->hwnd, 0, TRUE);
4082                                 CheckMenuItem(Globals.hMenuView, ID_VIEW_NAME, MF_BYCOMMAND|MF_CHECKED);
4083                                 CheckMenuItem(Globals.hMenuView, ID_VIEW_ALL_ATTRIBUTES, MF_BYCOMMAND);
4084                                 CheckMenuItem(Globals.hMenuView, ID_VIEW_SELECTED_ATTRIBUTES, MF_BYCOMMAND);
4085                         }
4086                         break;
4087
4088                 case ID_VIEW_ALL_ATTRIBUTES:
4089                         if (pane->visible_cols != COL_ALL) {
4090                                 pane->visible_cols = COL_ALL;
4091                                 calc_widths(pane, TRUE);
4092 #ifndef _NO_EXTENSIONS
4093                                 set_header(pane);
4094 #endif
4095                                 InvalidateRect(pane->hwnd, 0, TRUE);
4096                                 CheckMenuItem(Globals.hMenuView, ID_VIEW_NAME, MF_BYCOMMAND);
4097                                 CheckMenuItem(Globals.hMenuView, ID_VIEW_ALL_ATTRIBUTES, MF_BYCOMMAND|MF_CHECKED);
4098                                 CheckMenuItem(Globals.hMenuView, ID_VIEW_SELECTED_ATTRIBUTES, MF_BYCOMMAND);
4099                         }
4100                         break;
4101
4102 #ifndef _NO_EXTENSIONS
4103                 case ID_PREFERRED_SIZES: {
4104                         calc_widths(pane, TRUE);
4105                         set_header(pane);
4106                         InvalidateRect(pane->hwnd, 0, TRUE);
4107                         break;}
4108 #endif
4109
4110                         /* TODO: more command ids... */
4111
4112                 default:
4113                         return FALSE;
4114         }
4115
4116         return TRUE;
4117 }
4118
4119
4120 static void set_sort_order(ChildWnd* child, SORT_ORDER sortOrder)
4121 {
4122         if (child->sortOrder != sortOrder) {
4123                 child->sortOrder = sortOrder;
4124                 refresh_child(child);
4125         }
4126 }
4127
4128 static void update_view_menu(ChildWnd* child)
4129 {
4130         CheckMenuItem(Globals.hMenuView, ID_VIEW_SORT_NAME, child->sortOrder==SORT_NAME? MF_CHECKED: MF_UNCHECKED);
4131         CheckMenuItem(Globals.hMenuView, ID_VIEW_SORT_TYPE, child->sortOrder==SORT_EXT? MF_CHECKED: MF_UNCHECKED);
4132         CheckMenuItem(Globals.hMenuView, ID_VIEW_SORT_SIZE, child->sortOrder==SORT_SIZE? MF_CHECKED: MF_UNCHECKED);
4133         CheckMenuItem(Globals.hMenuView, ID_VIEW_SORT_DATE, child->sortOrder==SORT_DATE? MF_CHECKED: MF_UNCHECKED);
4134 }
4135
4136
4137 static BOOL is_directory(LPCTSTR target)
4138 {
4139         /*TODO correctly handle UNIX paths */
4140         DWORD target_attr = GetFileAttributes(target);
4141
4142         if (target_attr == INVALID_FILE_ATTRIBUTES)
4143                 return FALSE;
4144
4145         return target_attr&FILE_ATTRIBUTE_DIRECTORY? TRUE: FALSE;
4146 }
4147         
4148 static BOOL prompt_target(Pane* pane, LPTSTR source, LPTSTR target)
4149 {
4150         TCHAR path[MAX_PATH];
4151         int len;
4152
4153         get_path(pane->cur, path);
4154
4155         if (DialogBoxParam(Globals.hInstance, MAKEINTRESOURCE(IDD_SELECT_DESTINATION), pane->hwnd, DestinationDlgProc, (LPARAM)path) != IDOK)
4156                 return FALSE;
4157
4158         get_path(pane->cur, source);
4159
4160         /* convert relative targets to absolute paths */
4161         if (path[0]!='/' && path[1]!=':') {
4162                 get_path(pane->cur->up, target);
4163                 len = lstrlen(target);
4164
4165                 if (target[len-1]!='\\' && target[len-1]!='/')
4166                         target[len++] = '/';
4167
4168                 lstrcpy(target+len, path);
4169         } else
4170                 lstrcpy(target, path);
4171
4172         /* If the target already exists as directory, create a new target below this. */
4173         if (is_directory(path)) {
4174                 TCHAR fname[_MAX_FNAME], ext[_MAX_EXT];
4175                 static const TCHAR sAppend[] = {'%','s','/','%','s','%','s','\0'};
4176
4177                 _tsplitpath(source, NULL, NULL, fname, ext);
4178
4179                 wsprintf(target, sAppend, path, fname, ext);
4180         }
4181
4182         return TRUE;
4183 }
4184
4185
4186 static IContextMenu2* s_pctxmenu2 = NULL;
4187 static IContextMenu3* s_pctxmenu3 = NULL;
4188
4189 static void CtxMenu_reset(void)
4190 {
4191         s_pctxmenu2 = NULL;
4192         s_pctxmenu3 = NULL;
4193 }
4194
4195 static IContextMenu* CtxMenu_query_interfaces(IContextMenu* pcm1)
4196 {
4197         IContextMenu* pcm = NULL;
4198
4199         CtxMenu_reset();
4200
4201         if (IContextMenu_QueryInterface(pcm1, &IID_IContextMenu3, (void**)&pcm) == NOERROR)
4202                 s_pctxmenu3 = (LPCONTEXTMENU3)pcm;
4203         else if (IContextMenu_QueryInterface(pcm1, &IID_IContextMenu2, (void**)&pcm) == NOERROR)
4204                 s_pctxmenu2 = (LPCONTEXTMENU2)pcm;
4205
4206         if (pcm) {
4207                 IContextMenu_Release(pcm1);
4208                 return pcm;
4209         } else
4210                 return pcm1;
4211 }
4212
4213 static BOOL CtxMenu_HandleMenuMsg(UINT nmsg, WPARAM wparam, LPARAM lparam)
4214 {
4215         if (s_pctxmenu3) {
4216                 if (SUCCEEDED(IContextMenu3_HandleMenuMsg(s_pctxmenu3, nmsg, wparam, lparam)))
4217                         return TRUE;
4218         }
4219
4220         if (s_pctxmenu2)
4221                 if (SUCCEEDED(IContextMenu2_HandleMenuMsg(s_pctxmenu2, nmsg, wparam, lparam)))
4222                         return TRUE;
4223
4224         return FALSE;
4225 }
4226
4227
4228 static HRESULT ShellFolderContextMenu(IShellFolder* shell_folder, HWND hwndParent, int cidl, LPCITEMIDLIST* apidl, int x, int y)
4229 {
4230         IContextMenu* pcm;
4231         BOOL executed = FALSE;
4232
4233         HRESULT hr = IShellFolder_GetUIObjectOf(shell_folder, hwndParent, cidl, apidl, &IID_IContextMenu, NULL, (LPVOID*)&pcm);
4234 /*      HRESULT hr = CDefFolderMenu_Create2(dir?dir->_pidl:DesktopFolder(), hwndParent, 1, &pidl, shell_folder, NULL, 0, NULL, &pcm); */
4235
4236         if (SUCCEEDED(hr)) {
4237                 HMENU hmenu = CreatePopupMenu();
4238
4239                 pcm = CtxMenu_query_interfaces(pcm);
4240
4241                 if (hmenu) {
4242                         hr = IContextMenu_QueryContextMenu(pcm, hmenu, 0, FCIDM_SHVIEWFIRST, FCIDM_SHVIEWLAST, CMF_NORMAL);
4243
4244                         if (SUCCEEDED(hr)) {
4245                                 UINT idCmd = TrackPopupMenu(hmenu, TPM_LEFTALIGN|TPM_RETURNCMD|TPM_RIGHTBUTTON, x, y, 0, hwndParent, NULL);
4246
4247                                 CtxMenu_reset();
4248
4249                                 if (idCmd) {
4250                                   CMINVOKECOMMANDINFO cmi;
4251
4252                                   cmi.cbSize = sizeof(CMINVOKECOMMANDINFO);
4253                                   cmi.fMask = 0;
4254                                   cmi.hwnd = hwndParent;
4255                                   cmi.lpVerb = (LPCSTR)(INT_PTR)(idCmd - FCIDM_SHVIEWFIRST);
4256                                   cmi.lpParameters = NULL;
4257                                   cmi.lpDirectory = NULL;
4258                                   cmi.nShow = SW_SHOWNORMAL;
4259                                   cmi.dwHotKey = 0;
4260                                   cmi.hIcon = 0;
4261
4262                                   hr = IContextMenu_InvokeCommand(pcm, &cmi);
4263                                         executed = TRUE;
4264                                 }
4265                         } else
4266                                 CtxMenu_reset();
4267                 }
4268
4269                 IContextMenu_Release(pcm);
4270         }
4271
4272         return FAILED(hr)? hr: executed? S_OK: S_FALSE;
4273 }
4274
4275
4276 static LRESULT CALLBACK ChildWndProc(HWND hwnd, UINT nmsg, WPARAM wparam, LPARAM lparam)
4277 {
4278         ChildWnd* child = (ChildWnd*) GetWindowLongPtr(hwnd, GWLP_USERDATA);
4279         ASSERT(child);
4280
4281         switch(nmsg) {
4282                 case WM_DRAWITEM: {
4283                         LPDRAWITEMSTRUCT dis = (LPDRAWITEMSTRUCT)lparam;
4284                         Entry* entry = (Entry*) dis->itemData;
4285
4286                         if (dis->CtlID == IDW_TREE_LEFT)
4287                                 draw_item(&child->left, dis, entry, -1);
4288                         else if (dis->CtlID == IDW_TREE_RIGHT)
4289                                 draw_item(&child->right, dis, entry, -1);
4290                         else
4291                                 goto draw_menu_item;
4292
4293                         return TRUE;}
4294
4295                 case WM_CREATE:
4296                         InitChildWindow(child);
4297                         break;
4298
4299                 case WM_NCDESTROY:
4300                         free_child_window(child);
4301                         SetWindowLongPtr(hwnd, GWLP_USERDATA, 0);
4302                         break;
4303
4304                 case WM_PAINT: {
4305                         PAINTSTRUCT ps;
4306                         HBRUSH lastBrush;
4307                         RECT rt;
4308                         GetClientRect(hwnd, &rt);
4309                         BeginPaint(hwnd, &ps);
4310                         rt.left = child->split_pos-SPLIT_WIDTH/2;
4311                         rt.right = child->split_pos+SPLIT_WIDTH/2+1;
4312                         lastBrush = SelectObject(ps.hdc, GetStockObject(COLOR_SPLITBAR));
4313                         Rectangle(ps.hdc, rt.left, rt.top-1, rt.right, rt.bottom+1);
4314                         SelectObject(ps.hdc, lastBrush);
4315 #ifdef _NO_EXTENSIONS
4316                         rt.top = rt.bottom - GetSystemMetrics(SM_CYHSCROLL);
4317                         FillRect(ps.hdc, &rt, GetStockObject(BLACK_BRUSH));
4318 #endif
4319                         EndPaint(hwnd, &ps);
4320                         break;}
4321
4322                 case WM_SETCURSOR:
4323                         if (LOWORD(lparam) == HTCLIENT) {
4324                                 POINT pt;
4325                                 GetCursorPos(&pt);
4326                                 ScreenToClient(hwnd, &pt);
4327
4328                                 if (pt.x>=child->split_pos-SPLIT_WIDTH/2 && pt.x<child->split_pos+SPLIT_WIDTH/2+1) {
4329                                         SetCursor(LoadCursor(0, IDC_SIZEWE));
4330                                         return TRUE;
4331                                 }
4332                         }
4333                         goto def;
4334
4335                 case WM_LBUTTONDOWN: {
4336                         RECT rt;
4337                         int x = (short)LOWORD(lparam);
4338
4339                         GetClientRect(hwnd, &rt);
4340
4341                         if (x>=child->split_pos-SPLIT_WIDTH/2 && x<child->split_pos+SPLIT_WIDTH/2+1) {
4342                                 last_split = child->split_pos;
4343 #ifdef _NO_EXTENSIONS
4344                                 draw_splitbar(hwnd, last_split);
4345 #endif
4346                                 SetCapture(hwnd);
4347                         }
4348
4349                         break;}
4350
4351                 case WM_LBUTTONUP:
4352                         if (GetCapture() == hwnd) {
4353 #ifdef _NO_EXTENSIONS
4354                                 RECT rt;
4355                                 int x = (short)LOWORD(lparam);
4356                                 draw_splitbar(hwnd, last_split);
4357                                 last_split = -1;
4358                                 GetClientRect(hwnd, &rt);
4359                                 child->split_pos = x;
4360                                 resize_tree(child, rt.right, rt.bottom);
4361 #endif
4362                                 ReleaseCapture();
4363                         }
4364                         break;
4365
4366 #ifdef _NO_EXTENSIONS
4367                 case WM_CAPTURECHANGED:
4368                         if (GetCapture()==hwnd && last_split>=0)
4369                                 draw_splitbar(hwnd, last_split);
4370                         break;
4371 #endif
4372
4373                 case WM_KEYDOWN:
4374                         if (wparam == VK_ESCAPE)
4375                                 if (GetCapture() == hwnd) {
4376                                         RECT rt;
4377 #ifdef _NO_EXTENSIONS
4378                                         draw_splitbar(hwnd, last_split);
4379 #else
4380                                         child->split_pos = last_split;
4381 #endif
4382                                         GetClientRect(hwnd, &rt);
4383                                         resize_tree(child, rt.right, rt.bottom);
4384                                         last_split = -1;
4385                                         ReleaseCapture();
4386                                         SetCursor(LoadCursor(0, IDC_ARROW));
4387                                 }
4388                         break;
4389
4390                 case WM_MOUSEMOVE:
4391                         if (GetCapture() == hwnd) {
4392                                 RECT rt;
4393                                 int x = (short)LOWORD(lparam);
4394
4395 #ifdef _NO_EXTENSIONS
4396                                 HDC hdc = GetDC(hwnd);
4397                                 GetClientRect(hwnd, &rt);
4398
4399                                 rt.left = last_split-SPLIT_WIDTH/2;
4400                                 rt.right = last_split+SPLIT_WIDTH/2+1;
4401                                 InvertRect(hdc, &rt);
4402
4403                                 last_split = x;
4404                                 rt.left = x-SPLIT_WIDTH/2;
4405                                 rt.right = x+SPLIT_WIDTH/2+1;
4406                                 InvertRect(hdc, &rt);
4407
4408                                 ReleaseDC(hwnd, hdc);
4409 #else
4410                                 GetClientRect(hwnd, &rt);
4411
4412                                 if (x>=0 && x<rt.right) {
4413                                         child->split_pos = x;
4414                                         resize_tree(child, rt.right, rt.bottom);
4415                                         rt.left = x-SPLIT_WIDTH/2;
4416                                         rt.right = x+SPLIT_WIDTH/2+1;
4417                                         InvalidateRect(hwnd, &rt, FALSE);
4418                                         UpdateWindow(child->left.hwnd);
4419                                         UpdateWindow(hwnd);
4420                                         UpdateWindow(child->right.hwnd);
4421                                 }
4422 #endif
4423                         }
4424                         break;
4425
4426 #ifndef _NO_EXTENSIONS
4427                 case WM_GETMINMAXINFO:
4428                         DefMDIChildProc(hwnd, nmsg, wparam, lparam);
4429
4430                         {LPMINMAXINFO lpmmi = (LPMINMAXINFO)lparam;
4431
4432                         lpmmi->ptMaxTrackSize.x <<= 1;/*2*GetSystemMetrics(SM_CXSCREEN) / SM_CXVIRTUALSCREEN */
4433                         lpmmi->ptMaxTrackSize.y <<= 1;/*2*GetSystemMetrics(SM_CYSCREEN) / SM_CYVIRTUALSCREEN */
4434                         break;}
4435 #endif /* _NO_EXTENSIONS */
4436
4437                 case WM_SETFOCUS:
4438                         if (SetCurrentDirectory(child->path))
4439                                 set_space_status();
4440                         SetFocus(child->focus_pane? child->right.hwnd: child->left.hwnd);
4441                         break;
4442
4443                 case WM_DISPATCH_COMMAND: {
4444                         Pane* pane = GetFocus()==child->left.hwnd? &child->left: &child->right;
4445
4446                         switch(LOWORD(wparam)) {
4447                                 case ID_WINDOW_NEW: {
4448                                         ChildWnd* new_child = alloc_child_window(child->path, NULL, hwnd);
4449
4450                                         if (!create_child_window(new_child))
4451                                                 HeapFree(GetProcessHeap(), 0, new_child);
4452
4453                                         break;}
4454
4455                                 case ID_REFRESH:
4456                                         refresh_drives();
4457                                         refresh_child(child);
4458                                         break;
4459
4460                                 case ID_ACTIVATE:
4461                                         activate_entry(child, pane, hwnd);
4462                                         break;
4463
4464                                 case ID_FILE_MOVE: {
4465                                         TCHAR source[BUFFER_LEN], target[BUFFER_LEN];
4466
4467                                         if (prompt_target(pane, source, target)) {
4468                                                 SHFILEOPSTRUCT shfo = {hwnd, FO_MOVE, source, target};
4469
4470                                                 source[lstrlen(source)+1] = '\0';
4471                                                 target[lstrlen(target)+1] = '\0';
4472
4473                                                 if (!SHFileOperation(&shfo))
4474                                                         refresh_child(child);
4475                                         }
4476                                         break;}
4477
4478                                 case ID_FILE_COPY: {
4479                                         TCHAR source[BUFFER_LEN], target[BUFFER_LEN];
4480
4481                                         if (prompt_target(pane, source, target)) {
4482                                                 SHFILEOPSTRUCT shfo = {hwnd, FO_COPY, source, target};
4483
4484                                                 source[lstrlen(source)+1] = '\0';
4485                                                 target[lstrlen(target)+1] = '\0';
4486
4487                                                 if (!SHFileOperation(&shfo))
4488                                                         refresh_child(child);
4489                                         }
4490                                         break;}
4491
4492                                 case ID_FILE_DELETE: {
4493                                         TCHAR path[BUFFER_LEN];
4494                                         SHFILEOPSTRUCT shfo = {hwnd, FO_DELETE, path};
4495
4496                                         get_path(pane->cur, path);
4497
4498                                         path[lstrlen(path)+1] = '\0';
4499
4500                                         if (!SHFileOperation(&shfo))
4501                                                 refresh_child(child);
4502                                         break;}
4503
4504                                 case ID_VIEW_SORT_NAME:
4505                                         set_sort_order(child, SORT_NAME);
4506                                         break;
4507
4508                                 case ID_VIEW_SORT_TYPE:
4509                                         set_sort_order(child, SORT_EXT);
4510                                         break;
4511
4512                                 case ID_VIEW_SORT_SIZE:
4513                                         set_sort_order(child, SORT_SIZE);
4514                                         break;
4515
4516                                 case ID_VIEW_SORT_DATE:
4517                                         set_sort_order(child, SORT_DATE);
4518                                         break;
4519
4520                                 case ID_VIEW_FILTER: {
4521                                         struct FilterDialog dlg;
4522
4523                                         memset(&dlg, 0, sizeof(struct FilterDialog));
4524                                         lstrcpy(dlg.pattern, child->filter_pattern);
4525                                         dlg.flags = child->filter_flags;
4526
4527                                         if (DialogBoxParam(Globals.hInstance, MAKEINTRESOURCE(IDD_DIALOG_VIEW_TYPE), hwnd, FilterDialogDlgProc, (LPARAM)&dlg) == IDOK) {
4528                                                 lstrcpy(child->filter_pattern, dlg.pattern);
4529                                                 child->filter_flags = dlg.flags;
4530                                                 refresh_right_pane(child);
4531                                         }
4532                                         break;}
4533
4534                                 case ID_VIEW_SPLIT: {
4535                                         last_split = child->split_pos;
4536 #ifdef _NO_EXTENSIONS
4537                                         draw_splitbar(hwnd, last_split);
4538 #endif
4539                                         SetCapture(hwnd);
4540                                         break;}
4541
4542                                 case ID_EDIT_PROPERTIES:
4543                                         show_properties_dlg(pane->cur, child->hwnd);
4544                                         break;
4545
4546                                 default:
4547                                         return pane_command(pane, LOWORD(wparam));
4548                         }
4549
4550                         return TRUE;}
4551
4552                 case WM_COMMAND: {
4553                         Pane* pane = GetFocus()==child->left.hwnd? &child->left: &child->right;
4554
4555                         switch(HIWORD(wparam)) {
4556                                 case LBN_SELCHANGE: {
4557                                         int idx = SendMessage(pane->hwnd, LB_GETCURSEL, 0, 0);
4558                                         Entry* entry = (Entry*) SendMessage(pane->hwnd, LB_GETITEMDATA, idx, 0);
4559
4560                                         if (pane == &child->left)
4561                                                 set_curdir(child, entry, idx, hwnd);
4562                                         else
4563                                                 pane->cur = entry;
4564                                         break;}
4565
4566                                 case LBN_DBLCLK:
4567                                         activate_entry(child, pane, hwnd);
4568                                         break;
4569                         }
4570                         break;}
4571
4572 #ifndef _NO_EXTENSIONS
4573                 case WM_NOTIFY: {
4574                         NMHDR* pnmh = (NMHDR*) lparam;
4575                         return pane_notify(pnmh->idFrom==IDW_HEADER_LEFT? &child->left: &child->right, pnmh);}
4576 #endif
4577
4578 #ifdef _SHELL_FOLDERS
4579                 case WM_CONTEXTMENU: {
4580                         POINT pt, pt_clnt;
4581                         Pane* pane;
4582                         int idx;
4583
4584                          /* first select the current item in the listbox */
4585                         HWND hpanel = (HWND) wparam;
4586                         pt_clnt.x = pt.x = (short)LOWORD(lparam);
4587                         pt_clnt.y = pt.y = (short)HIWORD(lparam);
4588                         ScreenToClient(hpanel, &pt_clnt);
4589                         SendMessage(hpanel, WM_LBUTTONDOWN, 0, MAKELONG(pt_clnt.x, pt_clnt.y));
4590                         SendMessage(hpanel, WM_LBUTTONUP, 0, MAKELONG(pt_clnt.x, pt_clnt.y));
4591
4592                          /* now create the popup menu using shell namespace and IContextMenu */
4593                         pane = GetFocus()==child->left.hwnd? &child->left: &child->right;
4594                         idx = SendMessage(pane->hwnd, LB_GETCURSEL, 0, 0);
4595
4596                         if (idx != -1) {
4597                                 Entry* entry = (Entry*) SendMessage(pane->hwnd, LB_GETITEMDATA, idx, 0);
4598
4599                                 LPITEMIDLIST pidl_abs = get_to_absolute_pidl(entry, hwnd);
4600
4601                                 if (pidl_abs) {
4602                                         IShellFolder* parentFolder;
4603                                         LPCITEMIDLIST pidlLast;
4604
4605                                          /* get and use the parent folder to display correct context menu in all cases */
4606                                         if (SUCCEEDED(SHBindToParent(pidl_abs, &IID_IShellFolder, (LPVOID*)&parentFolder, &pidlLast))) {
4607                                                 if (ShellFolderContextMenu(parentFolder, hwnd, 1, &pidlLast, pt.x, pt.y) == S_OK)
4608                                                         refresh_child(child);
4609
4610                                                 IShellFolder_Release(parentFolder);
4611                                         }
4612
4613                                         IMalloc_Free(Globals.iMalloc, pidl_abs);
4614                                 }
4615                         }
4616                         break;}
4617 #endif
4618
4619                   case WM_MEASUREITEM:
4620                   draw_menu_item:
4621                         if (!wparam)    /* Is the message menu-related? */
4622                                 if (CtxMenu_HandleMenuMsg(nmsg, wparam, lparam))
4623                                         return TRUE;
4624
4625                         break;
4626
4627                   case WM_INITMENUPOPUP:
4628                         if (CtxMenu_HandleMenuMsg(nmsg, wparam, lparam))
4629                                 return 0;
4630
4631                         update_view_menu(child);
4632                         break;
4633
4634                   case WM_MENUCHAR:     /* only supported by IContextMenu3 */
4635                    if (s_pctxmenu3) {
4636                            LRESULT lResult = 0;
4637
4638                            IContextMenu3_HandleMenuMsg2(s_pctxmenu3, nmsg, wparam, lparam, &lResult);
4639
4640                            return lResult;
4641                    }
4642
4643                    break;
4644
4645                 case WM_SIZE:
4646                         if (wparam != SIZE_MINIMIZED)
4647                                 resize_tree(child, LOWORD(lparam), HIWORD(lparam));
4648                         /* fall through */
4649
4650                 default: def:
4651                         return DefMDIChildProc(hwnd, nmsg, wparam, lparam);
4652         }
4653
4654         return 0;
4655 }
4656
4657
4658 static LRESULT CALLBACK TreeWndProc(HWND hwnd, UINT nmsg, WPARAM wparam, LPARAM lparam)
4659 {
4660         ChildWnd* child = (ChildWnd*) GetWindowLongPtr(GetParent(hwnd), GWLP_USERDATA);
4661         Pane* pane = (Pane*) GetWindowLongPtr(hwnd, GWLP_USERDATA);
4662         ASSERT(child);
4663
4664         switch(nmsg) {
4665 #ifndef _NO_EXTENSIONS
4666                 case WM_HSCROLL:
4667                         set_header(pane);
4668                         break;
4669 #endif
4670
4671                 case WM_SETFOCUS:
4672                         child->focus_pane = pane==&child->right? 1: 0;
4673                         SendMessage(hwnd, LB_SETSEL, TRUE, 1);
4674                         /*TODO: check menu items */
4675                         break;
4676
4677                 case WM_KEYDOWN:
4678                         if (wparam == VK_TAB) {
4679                                 /*TODO: SetFocus(Globals.hdrivebar) */
4680                                 SetFocus(child->focus_pane? child->left.hwnd: child->right.hwnd);
4681                         }
4682         }
4683
4684         return CallWindowProc(g_orgTreeWndProc, hwnd, nmsg, wparam, lparam);
4685 }
4686
4687
4688 static void InitInstance(HINSTANCE hinstance)
4689 {
4690         static const TCHAR sFont[] = {'M','i','c','r','o','s','o','f','t',' ','S','a','n','s',' ','S','e','r','i','f','\0'};
4691
4692         WNDCLASSEX wcFrame;
4693         WNDCLASS wcChild;
4694         ATOM hChildClass;
4695         int col;
4696
4697         INITCOMMONCONTROLSEX icc = {
4698                 sizeof(INITCOMMONCONTROLSEX),
4699                 ICC_BAR_CLASSES
4700         };
4701
4702         HDC hdc = GetDC(0);
4703
4704         setlocale(LC_COLLATE, "");      /* set collating rules to local settings for compareName */
4705
4706         InitCommonControlsEx(&icc);
4707
4708
4709         /* register frame window class */
4710
4711         wcFrame.cbSize        = sizeof(WNDCLASSEX);
4712         wcFrame.style         = 0;
4713         wcFrame.lpfnWndProc   = FrameWndProc;
4714         wcFrame.cbClsExtra    = 0;
4715         wcFrame.cbWndExtra    = 0;
4716         wcFrame.hInstance     = hinstance;
4717         wcFrame.hIcon         = LoadIcon(hinstance, MAKEINTRESOURCE(IDI_WINEFILE));
4718         wcFrame.hCursor       = LoadCursor(0, IDC_ARROW);
4719         wcFrame.hbrBackground = 0;
4720         wcFrame.lpszMenuName  = 0;
4721         wcFrame.lpszClassName = sWINEFILEFRAME;
4722         wcFrame.hIconSm       = (HICON)LoadImage(hinstance,
4723                                                                                          MAKEINTRESOURCE(IDI_WINEFILE),
4724                                                                                          IMAGE_ICON,
4725                                                                                          GetSystemMetrics(SM_CXSMICON),
4726                                                                                          GetSystemMetrics(SM_CYSMICON),
4727                                                                                          LR_SHARED);
4728
4729         Globals.hframeClass = RegisterClassEx(&wcFrame);
4730
4731
4732         /* register tree windows class */
4733
4734         wcChild.style         = CS_CLASSDC|CS_DBLCLKS|CS_VREDRAW;
4735         wcChild.lpfnWndProc   = ChildWndProc;
4736         wcChild.cbClsExtra    = 0;
4737         wcChild.cbWndExtra    = 0;
4738         wcChild.hInstance     = hinstance;
4739         wcChild.hIcon         = 0;
4740         wcChild.hCursor       = LoadCursor(0, IDC_ARROW);
4741         wcChild.hbrBackground = 0;
4742         wcChild.lpszMenuName  = 0;
4743         wcChild.lpszClassName = sWINEFILETREE;
4744
4745         hChildClass = RegisterClass(&wcChild);
4746
4747
4748         Globals.haccel = LoadAccelerators(hinstance, MAKEINTRESOURCE(IDA_WINEFILE));
4749
4750         Globals.hfont = CreateFont(-MulDiv(8,GetDeviceCaps(hdc,LOGPIXELSY),72), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, sFont);
4751
4752         ReleaseDC(0, hdc);
4753
4754         Globals.hInstance = hinstance;
4755
4756 #ifdef _SHELL_FOLDERS
4757         CoInitialize(NULL);
4758         CoGetMalloc(MEMCTX_TASK, &Globals.iMalloc);
4759         SHGetDesktopFolder(&Globals.iDesktop);
4760 #ifdef __WINE__
4761         Globals.cfStrFName = RegisterClipboardFormatA(CFSTR_FILENAME);
4762 #else
4763         Globals.cfStrFName = RegisterClipboardFormat(CFSTR_FILENAME);
4764 #endif
4765 #endif
4766
4767         /* load column strings */
4768         col = 1;
4769
4770         load_string(g_pos_names[col++], IDS_COL_NAME);
4771         load_string(g_pos_names[col++], IDS_COL_SIZE);
4772         load_string(g_pos_names[col++], IDS_COL_CDATE);
4773 #ifndef _NO_EXTENSIONS
4774         load_string(g_pos_names[col++], IDS_COL_ADATE);
4775         load_string(g_pos_names[col++], IDS_COL_MDATE);
4776         load_string(g_pos_names[col++], IDS_COL_IDX);
4777         load_string(g_pos_names[col++], IDS_COL_LINKS);
4778 #endif
4779         load_string(g_pos_names[col++], IDS_COL_ATTR);
4780 #ifndef _NO_EXTENSIONS
4781         load_string(g_pos_names[col++], IDS_COL_SEC);
4782 #endif
4783 }
4784
4785
4786 static void show_frame(HWND hwndParent, int cmdshow, LPCTSTR path)
4787 {
4788         static const TCHAR sMDICLIENT[] = {'M','D','I','C','L','I','E','N','T','\0'};
4789
4790         TCHAR buffer[MAX_PATH], b1[BUFFER_LEN];
4791         ChildWnd* child;
4792         HMENU hMenuFrame, hMenuWindow;
4793         windowOptions opts;
4794
4795         CLIENTCREATESTRUCT ccs;
4796
4797         if (Globals.hMainWnd)
4798                 return;
4799
4800         opts = load_registry_settings();
4801         hMenuFrame = LoadMenu(Globals.hInstance, MAKEINTRESOURCE(IDM_WINEFILE));
4802         hMenuWindow = GetSubMenu(hMenuFrame, GetMenuItemCount(hMenuFrame)-2);
4803
4804         Globals.hMenuFrame = hMenuFrame;
4805         Globals.hMenuView = GetSubMenu(hMenuFrame, 3);
4806         Globals.hMenuOptions = GetSubMenu(hMenuFrame, 4);
4807
4808         ccs.hWindowMenu  = hMenuWindow;
4809         ccs.idFirstChild = IDW_FIRST_CHILD;
4810
4811
4812         /* create main window */
4813         Globals.hMainWnd = CreateWindowEx(0, (LPCTSTR)(int)Globals.hframeClass, RS(b1,IDS_WINE_FILE), WS_OVERLAPPEDWINDOW,
4814                                         opts.start_x, opts.start_y, opts.width, opts.height,
4815                                         hwndParent, Globals.hMenuFrame, Globals.hInstance, 0/*lpParam*/);
4816
4817
4818         Globals.hmdiclient = CreateWindowEx(0, sMDICLIENT, NULL,
4819                                         WS_CHILD|WS_CLIPCHILDREN|WS_VSCROLL|WS_HSCROLL|WS_VISIBLE|WS_BORDER,
4820                                         0, 0, 0, 0,
4821                                         Globals.hMainWnd, 0, Globals.hInstance, &ccs);
4822   
4823         CheckMenuItem(Globals.hMenuOptions, ID_VIEW_DRIVE_BAR, MF_BYCOMMAND|MF_CHECKED);
4824         CheckMenuItem(Globals.hMenuOptions, ID_VIEW_SAVESETTINGS, MF_BYCOMMAND);
4825
4826         create_drive_bar();
4827
4828         {
4829                 TBBUTTON toolbarBtns[] = {
4830                         {0, 0, 0, BTNS_SEP, {0, 0}, 0, 0},
4831                         {0, ID_WINDOW_NEW, TBSTATE_ENABLED, BTNS_BUTTON, {0, 0}, 0, 0},
4832                         {1, ID_WINDOW_CASCADE, TBSTATE_ENABLED, BTNS_BUTTON, {0, 0}, 0, 0},
4833                         {2, ID_WINDOW_TILE_HORZ, TBSTATE_ENABLED, BTNS_BUTTON, {0, 0}, 0, 0},
4834                         {3, ID_WINDOW_TILE_VERT, TBSTATE_ENABLED, BTNS_BUTTON, {0, 0}, 0, 0},
4835 /*TODO
4836                         {4, ID_... , TBSTATE_ENABLED, BTNS_BUTTON, {0, 0}, 0, 0},
4837                         {5, ID_... , TBSTATE_ENABLED, BTNS_BUTTON, {0, 0}, 0, 0},
4838 */              };
4839
4840                 Globals.htoolbar = CreateToolbarEx(Globals.hMainWnd, WS_CHILD|WS_VISIBLE,
4841                         IDW_TOOLBAR, 2, Globals.hInstance, IDB_TOOLBAR, toolbarBtns,
4842                         sizeof(toolbarBtns)/sizeof(TBBUTTON), 16, 15, 16, 15, sizeof(TBBUTTON));
4843                 CheckMenuItem(Globals.hMenuOptions, ID_VIEW_TOOL_BAR, MF_BYCOMMAND|MF_CHECKED);
4844         }
4845
4846         Globals.hstatusbar = CreateStatusWindow(WS_CHILD|WS_VISIBLE, 0, Globals.hMainWnd, IDW_STATUSBAR);
4847         CheckMenuItem(Globals.hMenuOptions, ID_VIEW_STATUSBAR, MF_BYCOMMAND|MF_CHECKED);
4848
4849 /* CreateStatusWindow does not accept WS_BORDER
4850         Globals.hstatusbar = CreateWindowEx(WS_EX_NOPARENTNOTIFY, STATUSCLASSNAME, 0,
4851                                         WS_CHILD|WS_VISIBLE|WS_CLIPSIBLINGS|WS_BORDER|CCS_NODIVIDER, 0,0,0,0,
4852                                         Globals.hMainWnd, (HMENU)IDW_STATUSBAR, hinstance, 0);*/
4853
4854         /*TODO: read paths from registry */
4855
4856         if (!path || !*path) {
4857                 GetCurrentDirectory(MAX_PATH, buffer);
4858                 path = buffer;
4859         }
4860
4861         ShowWindow(Globals.hMainWnd, cmdshow);
4862
4863 #if defined(_SHELL_FOLDERS) && !defined(__WINE__)
4864          /* Shell Namespace as default: */
4865         child = alloc_child_window(path, get_path_pidl(path,Globals.hMainWnd), Globals.hMainWnd);
4866 #else
4867         child = alloc_child_window(path, NULL, Globals.hMainWnd);
4868 #endif
4869
4870         child->pos.showCmd = SW_SHOWMAXIMIZED;
4871         child->pos.rcNormalPosition.left = 0;
4872         child->pos.rcNormalPosition.top = 0;
4873         child->pos.rcNormalPosition.right = 320;
4874         child->pos.rcNormalPosition.bottom = 280;
4875
4876         if (!create_child_window(child))
4877                 HeapFree(GetProcessHeap(), 0, child);
4878
4879         SetWindowPlacement(child->hwnd, &child->pos);
4880
4881         Globals.himl = ImageList_LoadBitmap(Globals.hInstance, MAKEINTRESOURCE(IDB_IMAGES), 16, 0, RGB(0,255,0));
4882
4883         Globals.prescan_node = FALSE;
4884
4885         UpdateWindow(Globals.hMainWnd);
4886
4887         if (path && path[0])
4888         {
4889                 int index,count;
4890                 TCHAR drv[_MAX_DRIVE+1], dir[_MAX_DIR], name[_MAX_FNAME], ext[_MAX_EXT];
4891                 TCHAR fullname[_MAX_FNAME+_MAX_EXT+1];
4892
4893                 memset(name,0,sizeof(name));
4894                 memset(name,0,sizeof(ext));
4895                 _tsplitpath(path, drv, dir, name, ext);
4896                 if (name[0])
4897                 {
4898                         count = SendMessage(child->right.hwnd, LB_GETCOUNT, 0, 0);
4899                         lstrcpy(fullname,name);
4900                         lstrcat(fullname,ext);
4901
4902                         for (index = 0; index < count; index ++)
4903                         {
4904                                 Entry* entry = (Entry*) SendMessage(child->right.hwnd, LB_GETITEMDATA, index, 0);
4905                                 if (lstrcmp(entry->data.cFileName,fullname)==0 ||
4906                                                 lstrcmp(entry->data.cAlternateFileName,fullname)==0)
4907                                 {
4908                                         SendMessage(child->right.hwnd, LB_SETCURSEL, index, 0);
4909                                         SetFocus(child->right.hwnd);
4910                                         break;
4911                                 }
4912                         }
4913                 }
4914         }
4915 }
4916
4917 static void ExitInstance(void)
4918 {
4919 #ifdef _SHELL_FOLDERS
4920         IShellFolder_Release(Globals.iDesktop);
4921         IMalloc_Release(Globals.iMalloc);
4922         CoUninitialize();
4923 #endif
4924
4925         DeleteObject(Globals.hfont);
4926         ImageList_Destroy(Globals.himl);
4927 }
4928
4929 #ifdef _NO_EXTENSIONS
4930
4931 /* search for already running win[e]files */
4932
4933 static int g_foundPrevInstance = 0;
4934
4935 static BOOL CALLBACK EnumWndProc(HWND hwnd, LPARAM lparam)
4936 {
4937         TCHAR cls[128];
4938
4939         GetClassName(hwnd, cls, 128);
4940
4941         if (!lstrcmp(cls, (LPCTSTR)lparam)) {
4942                 g_foundPrevInstance++;
4943                 return FALSE;
4944         }
4945
4946         return TRUE;
4947 }
4948
4949 /* search for window of given class name to allow only one running instance */
4950 static int find_window_class(LPCTSTR classname)
4951 {
4952         EnumWindows(EnumWndProc, (LPARAM)classname);
4953
4954         if (g_foundPrevInstance)
4955                 return 1;
4956
4957         return 0;
4958 }
4959
4960 #endif
4961
4962 static int winefile_main(HINSTANCE hinstance, int cmdshow, LPCTSTR path)
4963 {
4964         MSG msg;
4965   
4966         InitInstance(hinstance);
4967
4968         show_frame(0, cmdshow, path);
4969
4970         while(GetMessage(&msg, 0, 0, 0)) {
4971                 if (Globals.hmdiclient && TranslateMDISysAccel(Globals.hmdiclient, &msg))
4972                         continue;
4973
4974                 if (Globals.hMainWnd && TranslateAccelerator(Globals.hMainWnd, Globals.haccel, &msg))
4975                         continue;
4976
4977                 TranslateMessage(&msg);
4978                 DispatchMessage(&msg);
4979         }
4980
4981         ExitInstance();
4982
4983         return msg.wParam;
4984 }
4985
4986
4987 #if defined(UNICODE) && defined(_MSC_VER)
4988 int APIENTRY wWinMain(HINSTANCE hinstance, HINSTANCE previnstance, LPWSTR cmdline, int cmdshow)
4989 #else
4990 int APIENTRY WinMain(HINSTANCE hinstance, HINSTANCE previnstance, LPSTR cmdline, int cmdshow)
4991 #endif
4992 {
4993 #ifdef _NO_EXTENSIONS
4994         if (find_window_class(sWINEFILEFRAME))
4995                 return 1;
4996 #endif
4997
4998 #if defined(UNICODE) && !defined(_MSC_VER)
4999         { /* convert ANSI cmdline into WCS path string */
5000         TCHAR buffer[MAX_PATH];
5001         MultiByteToWideChar(CP_ACP, 0, cmdline, -1, buffer, MAX_PATH);
5002         winefile_main(hinstance, cmdshow, buffer);
5003         }
5004 #else
5005         winefile_main(hinstance, cmdshow, cmdline);
5006 #endif
5007
5008         return 0;
5009 }