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