/[winpt]/trunk/Src/wptW32API.cpp
ViewVC logotype

Diff of /trunk/Src/wptW32API.cpp

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 175 by twoaday, Tue Feb 7 08:58:04 2006 UTC revision 328 by twoaday, Fri Sep 25 16:07:38 2009 UTC
# Line 1  Line 1 
1  /* wptW32API.cpp - Common W32 API functions  /* wptW32API.cpp - Common W32 API functions
2   *      Copyright (C) 2001, 2002, 2003, 2005 Timo Schulz   *      Copyright (C) 2001-2003, 2005-2006, 2009 Timo Schulz
3   *   *
4   * This file is part of WinPT.   * This file is part of WinPT.
5   *   *
# Line 12  Line 12 
12   * but WITHOUT ANY WARRANTY; without even the implied warranty of   * but WITHOUT ANY WARRANTY; without even the implied warranty of
13   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14   * GNU General Public License for more details.   * GNU General Public License for more details.
  *  
  * You should have received a copy of the GNU General Public License  
  * along with WinPT; if not, write to the Free Software Foundation,  
  * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA  
15   */   */
   
16  #ifdef HAVE_CONFIG_H  #ifdef HAVE_CONFIG_H
17  #include <config.h>  #include <config.h>
18  #endif  #endif
# Line 35  Line 30 
30  #include "wptW32API.h"  #include "wptW32API.h"
31  #include "wptErrors.h"  #include "wptErrors.h"
32  #include "wptVersion.h"  #include "wptVersion.h"
33    #include "wptUTF8.h"
34  #include "wptTypes.h"  #include "wptTypes.h"
35    #include "StringBuffer.h"
36    
37    
38  extern "C" void _SHFree (void *p);  extern "C" void _SHFree (void *p);
39    
40    
41    /* Insert a new item into the menu @hm at position @pos. */
42    void
43    insert_menu_item (HMENU hm, int pos, UINT m_id, const char *text)
44    {
45        MENUITEMINFO mi;
46    
47        memset (&mi, 0, sizeof mi);
48        mi.cbSize = sizeof mi;
49        mi.fType = MF_STRING;
50        mi.dwTypeData = (char *)text;
51        mi.cch = strlen (text);
52        mi.wID = m_id;
53        mi.fMask = MIIM_ID|MIIM_DATA| MIIM_TYPE;
54        InsertMenuItem (hm, pos, FALSE, &mi);
55    }
56    
57    
58  static void  static void
59  set_menu_text_ext (HMENU menu, int by_pos, int m_uid, const char *text)  set_menu_text_ext (HMENU menu, int by_pos, int m_uid, const char *text)
60  {  {
# Line 108  enum { Line 122  enum {
122     id can be either FILE_OPEN or FILE_SAVE.     id can be either FILE_OPEN or FILE_SAVE.
123     The return value is the file name or NULL if cancel was chosen. */     The return value is the file name or NULL if cancel was chosen. */
124  const char *  const char *
125  get_filename_dlg (HWND hwnd, int id, const char * title,  get_filename_dlg (HWND hwnd, int id, const char *title,
126                    const char * filter, const char * name)                    const char *filter, const char *name)
127  {  {
128      static char file[512] = "";      static char file[2*MAX_PATH+1] = "";
129        char _filter[512];
130        char workdir[MAX_PATH+1];
131        char *sel_file = NULL;
132      OPENFILENAME open;      OPENFILENAME open;
133            
134      if (name && strlen (name) < (sizeof (file)-1))      if (name && strlen (name) < (DIM (file)-1))
135          strcpy (file, name);          strcpy (file, name);
136      else      else
137          memset (file, 0, sizeof (file));          memset (file, 0, sizeof (file));
138      if (!filter)      if (!filter) {      
139          filter = "All Files (*.*)\0*.*\0\0";          strcpy (_filter, _("All Files (*.*)"));
140      /* XXX: problem with gettext because of the 'artificial'          memcpy (_filter+strlen (_filter)+1, "*.*\0\0", 5);
141              double string termination!. */          filter = _filter;
142        }
143    
144        GetCurrentDirectory (MAX_PATH, workdir);
145      memset (&open, 0, sizeof (open));      memset (&open, 0, sizeof (open));
146      open.lStructSize = sizeof (OPENFILENAME);      open.lStructSize = sizeof (OPENFILENAME);
147      open.hInstance = glob_hinst;      open.hInstance = glob_hinst;
# Line 129  get_filename_dlg (HWND hwnd, int id, con Line 149  get_filename_dlg (HWND hwnd, int id, con
149      open.lpstrFilter = filter;      open.lpstrFilter = filter;
150      open.hwndOwner = hwnd;      open.hwndOwner = hwnd;
151      open.lpstrFile = file;      open.lpstrFile = file;
152      open.nMaxFile = sizeof (file) - 1;      open.nMaxFile = DIM (file) - 1;
153      if (id == CDLG_FILE_OPEN)      if (id == CDLG_FILE_OPEN)
154          open.Flags = OFN_FILEMUSTEXIST|OFN_PATHMUSTEXIST;          open.Flags = OFN_FILEMUSTEXIST|OFN_PATHMUSTEXIST;
155      else      else
156          open.Flags = OFN_OVERWRITEPROMPT;          open.Flags = OFN_OVERWRITEPROMPT;
157    
158      if (id == CDLG_FILE_OPEN && GetOpenFileName (&open))      if (id == CDLG_FILE_OPEN && GetOpenFileName (&open))
159          return open.lpstrFile;          sel_file = open.lpstrFile;
160      else if (id == CDLG_FILE_SAVE && GetSaveFileName (&open))      else if (id == CDLG_FILE_SAVE && GetSaveFileName (&open))
161          return open.lpstrFile;          sel_file = open.lpstrFile;
162        SetCurrentDirectory (workdir);
163            
164      return NULL;      return sel_file;
165  }  }
166    
167  const char*  const char*
# Line 163  get_fileopen_dlg (HWND hwnd, const char Line 184  get_fileopen_dlg (HWND hwnd, const char
184  const char*  const char*
185  get_folder_dlg (HWND hwnd, const char *title, const char *name)  get_folder_dlg (HWND hwnd, const char *title, const char *name)
186  {  {
187      static char folder[MAX_PATH+1] = "";      static char folder[2*MAX_PATH+1] = "";
188      BROWSEINFO bi;      BROWSEINFO bi;
189      ITEMIDLIST *il;      ITEMIDLIST *il;
190    
# Line 176  get_folder_dlg (HWND hwnd, const char *t Line 197  get_folder_dlg (HWND hwnd, const char *t
197      else      else
198          memset (folder, 0, sizeof (folder));          memset (folder, 0, sizeof (folder));
199      il = SHBrowseForFolder (&bi);      il = SHBrowseForFolder (&bi);
200      if (il) {      if (il != NULL) {
201          SHGetPathFromIDList (il, folder);          SHGetPathFromIDList (il, folder);
202          _SHFree (il);          _SHFree (il);
203          return folder;          return folder;
# Line 238  set_clip_text (HWND hwnd, const char *te Line 259  set_clip_text (HWND hwnd, const char *te
259          BUG (NULL);          BUG (NULL);
260      p = (char *) GlobalLock (clipmem);      p = (char *) GlobalLock (clipmem);
261      if (p == NULL) {      if (p == NULL) {
262          rc = WPTERR_GENERAL;;          CloseClipboard ();
263          goto leave;              GlobalFree (clipmem);
264            return WPTERR_GENERAL;
265      }      }
266      memcpy (p, text, nbytes);      memcpy (p, text, nbytes);
267      p[nbytes] = '\0';      p[nbytes] = '\0';
268            
     GlobalUnlock (clipmem);  
269      SetClipboardData (CF_TEXT, clipmem);      SetClipboardData (CF_TEXT, clipmem);
270            GlobalUnlock (clipmem);
 leave:  
271      CloseClipboard ();      CloseClipboard ();
272        GlobalFree (clipmem);
273        
274      return rc;      return rc;
275  } /* set_clip_text */  }
276    
277    
278  /* Append or prepend some text to the clipboard contents.  /* Append or prepend some text to the clipboard contents.
# Line 258  leave: Line 280  leave:
280  int  int
281  set_clip_text2 (HWND hwnd, const char *text, int nbytes, int as_footer)  set_clip_text2 (HWND hwnd, const char *text, int nbytes, int as_footer)
282  {  {
283        const char *fmt;
284      char *p, *new_text;      char *p, *new_text;
285    
286      p = get_clip_text (hwnd);      p = get_clip_text (hwnd);
287      if (!p)      if (!p)
288          return WPTERR_CLIP_GET;          return WPTERR_CLIP_GET;
289      new_text = new char [strlen (p)+strlen (text)+8];      if (as_footer == 0)
290            fmt = "%s\r\n%s\r\n\r\n";
291        else
292            fmt = "%s\n%s\n\n";
293        new_text = new char [strlen (p)+strlen (text)+strlen (fmt)+2];
294      if (!new_text)      if (!new_text)
295          BUG (0);          BUG (0);
296      if (as_footer == 0)      if (as_footer == 0)
297          sprintf (new_text, "%s\r\n%s\r\n\r\n", text, p);          sprintf (new_text, fmt, text, p);
298      else      else
299          sprintf (new_text, "%s\n%s\n\n", p, text);          sprintf (new_text, fmt, p, text);
300      set_clip_text (hwnd, new_text, strlen (new_text)+1);      set_clip_text (hwnd, new_text, strlen (new_text)+1);
301      free_if_alloc (p);      free_if_alloc (p);
302      free_if_alloc (new_text);      free_if_alloc (new_text);
# Line 286  make_filename (const char *path, const c Line 313  make_filename (const char *path, const c
313      char *p;      char *p;
314      size_t size = 0;      size_t size = 0;
315    
316      if( path && *path )      if (path && *path)
317          size += strlen( path );          size += strlen (path);
318      if( file && *file )      if (file && *file)
319          size += strlen( file );          size += strlen (file);
320      if( ext && *ext )      if (ext && *ext)
321          size += strlen( ext );          size += strlen (ext);
322      p = new char[size + 4];      p = new char[size + 4];
323      memset( p, 0, size );      if (!p)
324      if( path ) {          BUG (0);
325          strcat( p, path );      memset (p, 0, size);
326          if( path[strlen( path ) -1] != '\\' )      if (path) {
327              strcat( p, "\\" );          strcat (p, path);
328      }          if (path[strlen (path) -1] != '\\')
329      if( file )              strcat (p, "\\");
330          strcat( p, file );      }
331      if( ext ) {      if (file != NULL)
332          strcat( p, "." );          strcat (p, file);
333          strcat( p, ext );      if (ext != NULL) {
334            strcat (p, ".");
335            strcat (p, ext);
336      }      }
337      return p;      return p;
338  }  }
339    
340    
341  /* Generate a file name from a special dirctory. */  /* Generates a file name from a special dirctory. */
342  char*  char*
343  make_special_filename (int folder, const char *file, const char *ext)  make_special_filename (int folder, const char *file, const char *ext)
344  {  {
345      BOOL ec;      BOOL ec;
346      char path[MAX_PATH], *p;      char path[MAX_PATH+1], *p;
347      size_t n=0;      size_t n=0;
348    
349      /* MSDN: buf must be at least MAX_PATH=256 bytes */      /* MSDN: buf must be at least MAX_PATH=256 bytes */
# Line 413  msg_box (HWND hwnd, const char *text, co Line 442  msg_box (HWND hwnd, const char *text, co
442  }  }
443    
444    
 /* Safe strdup version (C++ version). */  
 char*  
 m_strdup (const char *str)  
 {  
     char *p = new char[strlen (str) + 1];  
     if (!p)  
         BUG (NULL);  
     strcpy (p, str);  
     return p;  
 }  
   
   
445  /* Center the hwndChild relative to parent.  /* Center the hwndChild relative to parent.
446     The style param allows to specificy additional styles (like topmost). */     The style param allows to specificy additional styles (like topmost). */
447  void  void
# Line 470  center_window2 (HWND hwndChild, HWND par Line 487  center_window2 (HWND hwndChild, HWND par
487    
488  /* Center the given hwndChild window with no special style. */  /* Center the given hwndChild window with no special style. */
489  void  void
490  center_window (HWND hwndChild, HWND hwndParent)  center_window (HWND child, HWND parent)
491  {  {
492      center_window2 (hwndChild, hwndParent, NULL);      center_window2 (child, parent, NULL);
493  }  }
494    
495    
# Line 480  center_window (HWND hwndChild, HWND hwnd Line 497  center_window (HWND hwndChild, HWND hwnd
497     Format: MAJOR.MINOR.PATCH1.PATCH2     Format: MAJOR.MINOR.PATCH1.PATCH2
498     Return value: 0 on success. */     Return value: 0 on success. */
499  int  int
500  get_file_version (const char *fname, WORD *major, WORD *minor,  get_file_version (const char *fname,
501                    WORD *patch1, WORD *patch2)                    WORD *major, WORD *minor, WORD *patch1, WORD *patch2)
502  {  {
503      VS_FIXEDFILEINFO *inf = {0};      VS_FIXEDFILEINFO *inf;
504      char file[MAX_PATH+1] = {0};      char file[MAX_PATH+1] = {0};
505      LPVOID buf, data;      LPVOID buf, data;
506      DWORD arg;      DWORD arg;
# Line 494  get_file_version (const char *fname, WOR Line 511  get_file_version (const char *fname, WOR
511      size = GetFileVersionInfoSize (file, &arg);      size = GetFileVersionInfoSize (file, &arg);
512      if (!size)      if (!size)
513          return -1;          return -1;
514      buf = (LPVOID)new CHAR[size];      buf = (LPVOID)new char[size];
515      if (!buf)      if (!buf)
516          BUG (NULL);          BUG (NULL);
517      GetFileVersionInfo (file, 0, size, buf);      GetFileVersionInfo (file, 0, size, buf);
518    
519      qlen=0;      qlen=0;
520      VerQueryValue (buf, "\\", &data, &qlen);      VerQueryValue (buf, (char*)"\\", &data, &qlen);
521      if (!qlen) {      if (!qlen) {
522          delete [] (char*)buf;          delete [](char*)buf;
523          return -1;          return -1;
524      }      }
525      inf = (VS_FIXEDFILEINFO*)data;      inf = (VS_FIXEDFILEINFO*)data;
# Line 516  get_file_version (const char *fname, WOR Line 533  get_file_version (const char *fname, WOR
533      if (patch2)      if (patch2)
534          *patch2 = LOWORD (inf->dwProductVersionLS);          *patch2 = LOWORD (inf->dwProductVersionLS);
535    
536      delete [] (char*)buf;      delete [](char*)buf;
537      return 0;      return 0;
538  }  }
539    
540    
541  /* Return date in a format which complies with the  /* Return date in a format which complies with the
542     system locale settings. */     locale user settings. */
543  const char*  const char*
544  get_locale_date (long tm_t, char *buf, DWORD buflen)  get_locale_date (long tm_t, char *buf, DWORD buflen)
545  {  {
546      SYSTEMTIME st;      SYSTEMTIME st;
547      struct tm *ptm;      struct tm *ptm;
548    
549      ptm = localtime (&tm_t);        ptm = localtime (&tm_t);
550      st.wYear = (WORD)ptm->tm_year;      memset (&st, 0, sizeof (st));
551      st.wMonth = (WORD)ptm->tm_mon;      st.wYear = (WORD)ptm->tm_year+1900;
552        st.wMonth = (WORD)ptm->tm_mon+1;
553      st.wDay = (WORD)ptm->tm_mday;      st.wDay = (WORD)ptm->tm_mday;
     st.wYear += 1900;  
     st.wMonth += 1;  
554      if (!GetDateFormat (LOCALE_USER_DEFAULT, DATE_SHORTDATE, &st,      if (!GetDateFormat (LOCALE_USER_DEFAULT, DATE_SHORTDATE, &st,
555                          NULL, buf, buflen))                          NULL, buf, buflen))
556          return NULL;          return NULL;
557      return buf;      return buf;
558  }  }
559    
560    /* Return the time in a format which complies with the locale user
561       settings. */
562    const char*
563    get_locale_time (long tm_t, char *buf, DWORD buflen)
564    {
565        SYSTEMTIME st;
566        struct tm *ptm;
567    
568        ptm = localtime (&tm_t);
569        memset (&st, 0, sizeof (st));
570        st.wMinute = (WORD)ptm->tm_min;
571        st.wHour = (WORD)ptm->tm_hour;
572        st.wSecond = (WORD)ptm->tm_sec;
573    
574        if (!GetTimeFormat (LOCALE_USER_DEFAULT, TIME_FORCE24HOURFORMAT, &st,
575                            NULL, buf, buflen))
576            return NULL;
577        return buf;
578    }
579    
580    
581    /* Return a combination of date+time which complies to the
582       local user settings. */
583    const char*
584    get_locale_timedate (long tm_t, char *buf, DWORD buflen)
585    {
586        DWORD nleft = buflen;
587    
588        if (!get_locale_date (tm_t, buf, buflen))
589            return NULL;
590        nleft -= strlen (buf)+1;
591        if (nleft < 1)
592            return NULL;
593        strcat (buf, " ");
594        nleft--;
595        if (!get_locale_time (tm_t, buf+strlen (buf), nleft))
596            return NULL;
597        return buf;
598    }
599    
600    
601  /* Generate a temporary file name by using the users  /* Generate a temporary file name by using the users
602     temp path and optionally a name @name provided by the caller.     temp path and optionally a name @name provided by the caller.
# Line 550  get_temp_name (char *buf, DWORD buflen, Line 606  get_temp_name (char *buf, DWORD buflen,
606  {  {
607      char tmp[32];      char tmp[32];
608    
609        
610      if (!name) {      if (!name) {
611          sprintf (tmp, "%08lX", GetTickCount ());          _snprintf (tmp, DIM (tmp)-1, "%08lX", GetTickCount ());
612          name = tmp;          name = tmp;
613      }      }
614    
615      if (!GetTempPath (buflen - strlen (name) -2, buf)) {      if (!GetTempPath (buflen - strlen (name) -2, buf)) {
616          log_debug ("GetTempPath() failed ec=%d\n", (int)GetLastError ());          log_debug ("GetTempPath() failed ec=%d\n", (int)GetLastError ());
617          return -1;          return -1;
618      }      }
619    
620      strcat (buf, name);      strcat (buf, name);
621      return 0;      return 0;
622  }  }
623    
624    
625  struct reminder_hd_s {  void
626      int msecs;  ListBox_AddString_utf8 (HWND lb, const char *txt)
627      HWND dlg;  {
628      HANDLE hd;      char *utf8_txt;
629  };  
630        utf8_txt = utf8_to_native (txt);
631        SendMessage (lb, LB_ADDSTRING, 0, (LPARAM)(LPCSTR)(utf8_txt));
632        safe_free (utf8_txt);
633    }
634    
635    
636  static DWORD CALLBACK  void
637  foreground_reminder_thread (void *c)  ComboBox_AddString_utf8 (HWND cb, const char *txt)
638  {  {
639      struct reminder_hd_s *ctx = (struct reminder_hd_s *)c;      char *utf8_txt;
640      Sleep (ctx->msecs);  
641      SetForegroundWindow (ctx->dlg);      utf8_txt = utf8_to_native (txt);
642      CloseHandle (ctx->hd);      SendMessage ((cb), CB_ADDSTRING, 0, (LPARAM)(LPCSTR)(utf8_txt));
643      delete ctx;      safe_free (utf8_txt);
     ExitThread (0);  
     return 0;  
644  }  }
645    
646  /* Try to force the window @dlg to the foreground.  
647     On NT5 or later this will not work if the user  /* GetDlgItemText replacement with UTF8 support. */
648     is working in another window (console for example). */  int
649  void  GetDlgItemText_utf8 (HWND dlg, int id, char **r_txt)
650  force_foreground_window (HWND dlg, int msecs)  {
651        int len = GetWindowTextLength (GetDlgItem (dlg, id));
652        char *txt;
653    
654        *r_txt = NULL;
655        if (len < 1)
656            return 0;
657        txt = new char[len+2];
658        if (!txt)
659            BUG (NULL);
660        GetDlgItemText (dlg, id, txt, len+1);
661        *r_txt = native_to_utf8 (txt);
662        free_if_alloc (txt);
663        return len;
664    }
665    
666    int
667    html_help_show (int map_id)
668  {  {
669      struct reminder_hd_s *hd;      STARTUPINFO si;
670      DWORD tid;      PROCESS_INFORMATION pi;
671        SECURITY_ATTRIBUTES sec_attr;
672        char path[2*MAX_PATH+1];
673        
674        memset (&sec_attr, 0, sizeof (sec_attr));
675        memset (&si, 0, sizeof (si));
676        si.cb = sizeof (STARTUPINFO);
677        memset (&pi, 0, sizeof (pi));
678        //hh.exe -mapid 40 "winpt.$lang.chm"
679        
680        _snprintf (path, 2*MAX_PATH, "hh.exe -mapid %d winpt.%s.chm",
681                   map_id, gettext_get_langid ());
682        CreateProcess (NULL, path, &sec_attr, &sec_attr,
683                       FALSE, 0, NULL, NULL, &si, &pi);
684        CloseHandle (pi.hProcess);
685        CloseHandle (pi.hThread);
686        return 0;
687    }
688                      
689      
690    /* Return TRUE if the current user has admin privileges. */
691    BOOL
692    user_is_admin (void)
693    {
694        SID_IDENTIFIER_AUTHORITY SystemSidAuthority = SECURITY_NT_AUTHORITY;
695        HANDLE hd;
696        TOKEN_GROUPS  *ptg = NULL;
697        DWORD ngtoken;
698        DWORD i;
699        BOOL admin = FALSE;
700        PSID psid = 0;
701    
702        if (GetVersion () & 0x80000000) /* Win9X */
703            return TRUE;
704    
705        if (!OpenThreadToken (GetCurrentThread (), TOKEN_QUERY, FALSE, &hd) &&
706            !OpenProcessToken (GetCurrentProcess (), TOKEN_QUERY, &hd))
707            return FALSE;
708        
709        if (!GetTokenInformation (hd, TokenGroups, NULL, 0, &ngtoken) &&
710            GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
711            ptg = (TOKEN_GROUPS*)GlobalAlloc (GPTR, ngtoken);
712            if (!ptg)
713                return FALSE;
714    
715            if (!GetTokenInformation (hd, TokenGroups,
716                                      ptg, ngtoken, &ngtoken)) {
717                GlobalFree (ptg);
718                return FALSE;
719            }
720            AllocateAndInitializeSid (&SystemSidAuthority,
721                                      2, SECURITY_BUILTIN_DOMAIN_RID,
722                                      DOMAIN_ALIAS_RID_ADMINS,
723                                      0, 0, 0, 0, 0, 0,
724                                      &psid);
725            for (i = 0; i < ptg->GroupCount; i++) {
726                if (EqualSid (ptg->Groups[i].Sid, psid)) {
727                    admin = TRUE;
728                    break;
729                }
730            }
731            FreeSid (psid);
732            GlobalFree (ptg);
733        }
734    
735      hd = new reminder_hd_s;      CloseHandle (hd);
736      hd->dlg = dlg;      return admin;
     hd->msecs = msecs;  
     hd->hd = CreateThread (NULL, 0, foreground_reminder_thread,  
                            hd, NULL, &tid);  
737  }  }

Legend:
Removed from v.175  
changed lines
  Added in v.328

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26