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