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