commit-gnue
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[gnue] r7512 - trunk/gnue-forms/src/uidrivers/win32


From: btami
Subject: [gnue] r7512 - trunk/gnue-forms/src/uidrivers/win32
Date: Tue, 3 May 2005 06:29:49 -0500 (CDT)

Author: btami
Date: 2005-05-03 06:29:47 -0500 (Tue, 03 May 2005)
New Revision: 7512

Modified:
   trunk/gnue-forms/src/uidrivers/win32/UILoginHandler.py
   trunk/gnue-forms/src/uidrivers/win32/dialogs.py
Log:
new InputDialog class and reworked UILoginHandler using it

Modified: trunk/gnue-forms/src/uidrivers/win32/UILoginHandler.py
===================================================================
--- trunk/gnue-forms/src/uidrivers/win32/UILoginHandler.py      2005-05-03 
08:32:55 UTC (rev 7511)
+++ trunk/gnue-forms/src/uidrivers/win32/UILoginHandler.py      2005-05-03 
11:29:47 UTC (rev 7512)
@@ -25,277 +25,56 @@
 # NOTES:
 #
 
-import win32api, win32gui, win32con, commctrl
-import os, struct
+import os
 
 from gnue.common.datasources import GLoginHandler
 from gnue.common.apps import GConfig, errors
-from gnue.forms.uidrivers.win32.common import getNextId, centerWindow
+from gnue.forms.uidrivers.win32.dialog import InputDialog
 
-g_registeredClass = 0
-
 # Shortcut
 images_dir = GConfig.getInstalledBase('forms_images','common_images') + '/'
 
-BUTTON = 0x0080
-EDIT = 0x0081
-STATIC = 0x0082
 
-#####################################################################
-##
-## Login Support
-##
-## Everything below this point is in support of the win32 drivers
-## UILoginHandler
-##  
-#####################################################################
-
-#
-# UILoginHandler
-#
 class UILoginHandler(GLoginHandler.LoginHandler):
-  def __init__(self):
-    win32gui.InitCommonControls()
-    self.hinst = win32api.GetModuleHandle(None)
-
-    _font = win32gui.GetStockObject(win32con.SYSTEM_FONT)
-    fn = win32gui.GetObject(_font)
-    #print fn.lfHeight, fn.lfWidth,fn.lfCharSet,fn.lfPitchAndFamily
-    self.charWidth,self.charHeight = fn.lfWidth, fn.lfHeight
-
   def getLogin(self, loginData, errortext=None):#"Invalid username/password"):
-    if 1: # TODO: This is left here to prevent me from having to unindent this 
code
-          # TODO: Since the UI stuff is currently being gutted I'm not wasting 
the time
-          # TODO: to do the right thingData.Items()
-      self._loginData = loginData
-      self._errortext = errortext
+    (connection, description, fields) = loginData
       
-      if len(loginData[1]):
-        loginMesg = _('Login required for\n"%s"') % (loginData[1])
-      else:
-        loginMesg = _('Login required for %s') % (loginData[0])
+    if len(description):
+      loginMesg = _('Login required for\n"%s"') % (description)
+    else:
+      loginMesg = _('Login required for %s') % (connection)
 
-      if os.path.isabs(gConfigForms('loginBMP')):
-        imageFile = gConfigForms('loginBMP')
-      else:
-        imageFile = images_dir+gConfigForms('loginBMP')
+    if os.path.isabs(gConfigForms('loginBMP')):
+      imageFile = gConfigForms('loginBMP')
+    else:
+      imageFile = images_dir+gConfigForms('loginBMP')
 
-      if not imageFile[-3:].upper() == 'BMP':
-        raise errors.AdminError, \
-            _("The win32 forms driver supports only BMP format logo files!")
+    if not imageFile[-3:].upper() == 'BMP':
+      raise errors.AdminError, \
+        _("The win32 forms driver supports only BMP format logo files!")
 
-      self._bmp = win32gui.LoadImage(0, imageFile, win32con.IMAGE_BITMAP, 
-                                          0, 0, win32con.LR_LOADFROMFILE | 
win32con.LR_DEFAULTSIZE)
+    title = _("GNU Enterprise: Login to %s") % connection
+
+    dlgFields = []
+    dlgFields.append(("", imageFile, "image", None, None, []))
+    dlgFields.append((loginMesg, '_msg', "label", None, None, []))
 
-      message_map = {
-            win32con.WM_COMMAND: self.OnCommand,
-            win32con.WM_INITDIALOG: self.OnInitDialog,
-            win32con.WM_CLOSE: self.OnClose,
-            }
-      dlgClassName = self._RegisterWndClass()
+    for prompt in fields:
+      if prompt[2]:
+        dlgFields.append((prompt[1], "%s" % prompt[0], "password", None, None, 
[]))
+      else:
+        dlgFields.append((prompt[1], "%s" % prompt[0], "string", None, None, 
[]))
 
-      style = win32con.WS_POPUP | win32con.WS_VISIBLE | win32con.WS_CAPTION | \
-                win32con.DS_SETFONT | win32con.WS_SYSMENU
-
-      cs = win32con.WS_CHILD | win32con.WS_VISIBLE
-      title = _("GNU Enterprise: Login to %s") % loginData[0]
-
-      dlg = [ [title, (0, 0, 0, 0), style, None, (8, "MS Sans Serif"), None, 
dlgClassName], ]
-
-      self.ID_BITMAP = getNextId()
-      dlg.append([STATIC, "", self.ID_BITMAP, \
-                       (0, 0, 0, 0), \
-                       cs | win32con.SS_BITMAP]) # , win32con.SS_BLACKFRAME
-
-      self.ID_MESG = getNextId()
-      dlg.append([STATIC, loginMesg, self.ID_MESG, \
-                       (0, 0, 100, 
(self.charHeight-4)*(loginMesg.count('\n')+1)), \
-                       cs | win32con.SS_CENTER])
-
-      self.textctrlList = []
-      self.labelList = []
-
-      for prompt in loginData[2]:
-        ID = getNextId()
-        dlg.append([STATIC, '%s:' % prompt[1], ID, \
-                         (0, 0, (self.charWidth-2)*len(prompt[1]), 
self.charHeight-4), \
-                         cs | win32con.SS_LEFT])
-        self.labelList.append(ID)
-
-        s = cs | win32con.WS_TABSTOP | win32con.WS_BORDER
-        ID = getNextId()
-        if prompt[2]:
-          dlg.append([EDIT, None, ID, (0, 0, 100, self.charHeight-4), \
-                          s | win32con.ES_PASSWORD])
-        else:
-          dlg.append([EDIT, None, ID, (0, 0, 100, self.charHeight-4), s])
-        self.textctrlList.append(ID)
-
-      if self._errortext:
-        self.ID_ERROR = getNextId()
-        dlg.append([STATIC, str(self._errortext), self.ID_ERROR, \
-                        (0, 0, 210, 
(self.charHeight-4)*(self._errortext.count('\n')+2)), \
-                        cs | win32con.SS_CENTER])
-        #errorField.SetForegroundColour(wxColour(223,0,0))
-
-      # Buttons
-      login = _('Login')
-      cancel = _('Cancel')
-      buttonWidth = max(50, (self.charWidth-2)*len(login), 
(self.charWidth-2)*len(cancel))
-      s = cs | win32con.WS_TABSTOP
-      self.ID_LOGIN = getNextId()
-      dlg.append([BUTTON, login, self.ID_LOGIN, \
-                      (0, 0, buttonWidth, self.charHeight-2), \
-                      s | win32con.BS_DEFPUSHBUTTON]) \
-
-      s = s | win32con.BS_PUSHBUTTON
-      self.ID_CANCEL = getNextId()
-      dlg.append([BUTTON, cancel, self.ID_CANCEL, \
-                      (0, 0, buttonWidth, self.charHeight-2), \
-                      s])
-
-    # If user cancels, this will be set to 0
-    self._completed = 0
-    self._rv = {}
-    win32gui.DialogBoxIndirect(self.hinst, dlg, 0, message_map)
-
-    if not self._completed:
+    if errortext:
+      dlgFields.append((str(errortext), "_warn", "warning", None, None, []))
+
+    dlg = InputDialog(title, dlgFields)
+    
+    result = {}
+    if not dlg.DoModal():
       raise GLoginHandler.UserCanceledLogin
-
-    return self._rv
-
-
-  def _RegisterWndClass(self):
-        className = "GNUe login"
-        global g_registeredClass
-        if not g_registeredClass:
-            message_map = {}
-            wc = win32gui.WNDCLASS()
-            wc.SetDialogProc() # Make it a dialog class.
-            self.hinst = wc.hInstance = win32api.GetModuleHandle(None)
-            wc.lpszClassName = className
-            wc.style = win32con.CS_VREDRAW | win32con.CS_HREDRAW
-            wc.hCursor = win32gui.LoadCursor( 0, win32con.IDC_ARROW )
-            wc.hIcon = win32gui.LoadIcon(0, win32con.IDI_APPLICATION)
-            wc.hbrBackground = win32con.COLOR_WINDOW
-            wc.lpfnWndProc = message_map # could also specify a wndproc.
-            wc.cbWndExtra = win32con.DLGWINDOWEXTRA + struct.calcsize("Pi")
-            classAtom = win32gui.RegisterClass(wc)
-            g_registeredClass = 1
-        return className
-
-
-  def OnInitDialog(self, hwnd, msg, wparam, lparam):
-    self.hwnd = hwnd
-
-    bmCtrl = win32gui.GetDlgItem(self.hwnd, self.ID_BITMAP)
-    win32gui.SendMessage(bmCtrl, win32con.STM_SETIMAGE, win32con.IMAGE_BITMAP, 
self._bmp)
-
-    dlgWidth = max(self.Width(self.ID_BITMAP), self.Width(self.ID_MESG)+20)
-    dlgHeight = self.Height(self.ID_BITMAP) + self.Height(self.ID_MESG) + 95
-
-    xSpacing = 0
-    ySpacing = 0
-    fieldLabelWidth = 0
-
-    for i in range(len(self.textctrlList)):
-      t =self.textctrlList[i]
-      s = self.labelList[i]
-
-      fieldLabelWidth = max(fieldLabelWidth, \
-                      self.Width(s) + self.Width(t) + 10)
-
-      dlgWidth = max(dlgWidth, \
-                      self.Width(s) + self.Width(t) + 20)
-
-      xSpacing = max(xSpacing, self.Width(s))
-      ySpacing = max(ySpacing, self.Height(s))
-      ySpacing = max(ySpacing, self.Height(t))
-
-    dlgWidth = max(dlgWidth, self.Width(self.ID_LOGIN) +
-                        self.Width(self.ID_CANCEL) + 6) + 20
-
-    dlgHeight += max(self.Height(self.ID_LOGIN),
-                   self.Height(self.ID_CANCEL)) -6
-
-    if self._errortext:
-      dlgWidth = max(dlgWidth, self.Width(self.ID_ERROR)+10)
-      dlgHeight += self.Height(self.ID_ERROR) + 10
-
-    firstY = self.Height(self.ID_BITMAP) + self.Height(self.ID_MESG) + 40
-    lastY = firstY
-    xSpacing += 3 # Add whitespace between widgets
-    ySpacing += 6 # Add whitespace between widgets
-    xPos = dlgWidth/2 - fieldLabelWidth/2
-
-    self.SetPosition(self.ID_BITMAP,
-                (dlgWidth - self.Width(self.ID_BITMAP))/2,
-                12)
-
-    self.SetPosition(self.ID_MESG,
-                (dlgWidth - self.Width(self.ID_MESG))/2,
-                30 + self.Height(self.ID_BITMAP))
-
-    # Move the fields and labels into position
-    for i in range(len(self.textctrlList)):
-      dlgHeight = dlgHeight + ySpacing
-      self.SetPosition(self.labelList[i], xPos, lastY)
-      self.SetPosition(self.textctrlList[i], xPos + xSpacing, lastY)
-      lastY = lastY + ySpacing
-
-    if self._errortext:
-      self.SetPosition(self.ID_ERROR,
-              dlgWidth/2 - self.Width(self.ID_ERROR)/2,
-              lastY+3)
-
-    self.SetPosition(self.ID_CANCEL,
-                dlgWidth - 20 - self.Width(self.ID_CANCEL),
-                dlgHeight - 35 - max(self.Height(self.ID_LOGIN),
-                                            self.Height(self.ID_CANCEL)))
-    self.SetPosition(self.ID_LOGIN,
-                dlgWidth - 26 - self.Width(self.ID_CANCEL) - \
-                self.Width(self.ID_LOGIN),
-                dlgHeight - 35 - max(self.Height(self.ID_LOGIN),
-                                            self.Height(self.ID_CANCEL)))
-
-    # resize the dialog
-    win32gui.SetWindowPos(hwnd, 0,
-                              0, 0,
-                              dlgWidth, dlgHeight+8,
-                              win32con.SWP_NOACTIVATE | win32con.SWP_NOZORDER)
-    # center the dialog
-    centerWindow(self.hwnd)
-
-  def OnClose(self, hwnd, msg, wparam, lparam):
-        win32gui.EndDialog(hwnd, 0)
-
-
-  def OnCommand(self, hwnd, msg, wparam, lparam):
-        id = win32api.LOWORD(wparam)
-        if id == self.ID_LOGIN:
-          for i in range(0, len(self._loginData[2])):
-            dlgItem = win32gui.GetDlgItem(self.hwnd, self.textctrlList[i])
-            self._rv[self._loginData[2][i][0]] = 
win32gui.GetWindowText(dlgItem)
-          self._completed = 1
-          win32gui.EndDialog(hwnd, 0)
-        elif id == self.ID_CANCEL:
-          self._completed = 0
-          win32gui.EndDialog(hwnd, 0)
-
-
-  def Width(self, id):
-    item = win32gui.GetDlgItem(self.hwnd, id)
-    l,t,r,b = win32gui.GetWindowRect(item)
-    return r-l
-
-  def Height(self, id):
-    item = win32gui.GetDlgItem(self.hwnd, id)
-    l,t,r,b = win32gui.GetWindowRect(item)
-    return b-t
-
-  def SetPosition(self, id, x, y):
-    win32gui.SetWindowPos(win32gui.GetDlgItem(self.hwnd, id),
-                              0,
-                              x, y,
-                              self.Width(id), self.Height(id),
-                              win32con.SWP_NOACTIVATE | win32con.SWP_NOZORDER)
+    else:
+      for prompt in fields:
+        result[prompt[0]] = dlg.inputData[prompt[0]]
+    return result
+    
\ No newline at end of file

Modified: trunk/gnue-forms/src/uidrivers/win32/dialogs.py
===================================================================
--- trunk/gnue-forms/src/uidrivers/win32/dialogs.py     2005-05-03 08:32:55 UTC 
(rev 7511)
+++ trunk/gnue-forms/src/uidrivers/win32/dialogs.py     2005-05-03 11:29:47 UTC 
(rev 7512)
@@ -20,16 +20,370 @@
 # - Suite 330, Boston, MA 02111-1307, USA.
 #
 # $Id$
-
-import win32ui
-import win32con
-import win32gui
+
+import os
+import struct
 import textwrap
-
+
+import win32ui
+import win32api
+import win32gui
+import win32con
+import commctrl
 from pywin.mfc import dialog
-
+
+from gnue.common.apps import i18n, errors
+from gnue.forms.uidrivers.win32.common import getNextId, centerWindow
 from gnue.forms import VERSION
+
+# =============================================================================
+# Exceptions
+# =============================================================================
 
+class InvalidFieldTypeError (errors.ApplicationError):
+  def __init__ (self, fieldtype):
+    msg = u_("%s is not a valid type for an input field") % fieldtype
+    errors.ApplicationError.__init__ (self, msg)
+
+g_registeredClass = 0
+
+BUTTON = 0x0080
+EDIT = 0x0081
+STATIC = 0x0082
+LISTBOX = 0x0084
+DROPDOWN = 0x0085
+
+
+class InputDialog:
+  """
+  Dialog class prompting the user for a given number of fields. These field
+  definitions are specified as follows:
+
+  A field definition is a tuple having these elements:
+  - fieldlabel: This text will be used as label in the left column
+  - fieldname: This is the key in the result-dictionary to contain the value
+      entered by the user
+  - fieldtype: Currently these types are supported:
+      - label: The contents of 'fieldlabel' as static text
+      - warning: The contents of 'fieldlabel' as static text, formatted as
+          warning
+      - string: A text entry control
+      - password: A text entry control with obscured characters
+      - dropdown: Foreach element given in 'elements' a separate ComboBox
+          control will be created, where each one has it's own dictionary of
+          allowed values. If a value is selected in one control, all others are
+          synchronized to represent the same key-value.
+  - default: Default value to use
+  - masterfield: Used for 'dropdowns'. This item specifies another field
+      definition acting as master field. If this master field is changed, the
+      allowedValues of this dropdown will be changed accordingly. If a
+      masterfield is specified the 'allowedValues' dictionaries are built like
+      {master1: {key: value, key: value, ...}, master2: {key: value, ...}}
+  - elements: sequence of input element tuples (label, allowedValues). This is
+      used for dropdowns only. 'label' will be used as ToolTip for the control
+      and 'allowedValues' gives a dictionary with all valid keys to be selected
+      in the dropdown.
+
+  @return: If closed by 'Ok' the result is a dictionary with all values entered
+    by the user, where the "fieldname"s will be used as keys. If the user has
+    not selected a value from a dropdown (i.e. it has no values to select)
+    there will be no such key in the result dictionary. If the dialog is
+    canceled ('Cancel'-Button) the result will be None.
+  """
+  _FIELDTYPES = ['label', 'warning', 'string', 'password', 'dropdown', 'image']
+  _NO_LABELS  = ['label', 'warning', 'image']
+  
+  def __init__ (self, title, fields, cancel = True):
+    """
+    Create a new input dialog
+
+    @param title: Dialog title
+    @param fields: sequence of field definition tuples
+    @param cancel: If True add a Cancel button to the dialog
+    """
+    win32gui.InitCommonControls()
+    self.hinst = win32api.GetModuleHandle(None)
+
+    self.message_map = {
+            win32con.WM_COMMAND: self.OnCommand,
+            win32con.WM_INITDIALOG: self.OnInitDialog,
+            win32con.WM_CLOSE: self.OnClose,
+            }
+
+    dlgClassName = self._RegisterWndClass()
+
+    style = win32con.WS_POPUP | win32con.WS_VISIBLE | win32con.WS_CAPTION | \
+            win32con.DS_SETFONT | win32con.WS_SYSMENU | win32con.DS_MODALFRAME
+
+    self.template = [ [title, (0, 0, 0, 0), style, None, \
+                      (8, "MS Sans Serif"), None, dlgClassName], ]
+    
+    self.fields = fields
+    self.inputData  = {}
+    self.controlsName = {}
+    self.__controls  = []
+    self.__labels    = []
+    self.__texts     = []
+    self.__inputs    = []
+    self.__warnings  = []
+    self.__images    = {}
+    self.__dropdowns = {}
+
+    # Now build and add all controls
+    for field in fields:
+      fieldtype = field[2]
+      if not fieldtype in self._FIELDTYPES:
+        raise InvalidFieldTypeError, fieldtype
+      else:
+        self.AddControl(field)
+
+    self.template.append ([BUTTON, _("Ok"), win32con.IDOK, (0, 0, 56, 15),
+        win32con.WS_CHILD | win32con.WS_VISIBLE | \
+        win32con.WS_TABSTOP | win32con.BS_DEFPUSHBUTTON])
+    if cancel:
+      self.template.append ([BUTTON, _("Cancel"), win32con.IDCANCEL, (0, 0, 
56, 15),
+        win32con.WS_CHILD | win32con.WS_VISIBLE | \
+        win32con.WS_TABSTOP | win32con.BS_PUSHBUTTON])
+
+
+  def AddControl(self, field):
+    label, name, ftype, default, master, elements = field
+    cs = win32con.WS_CHILD | win32con.WS_VISIBLE
+
+    position = (0, 0, 0, 0)
+    if ftype == 'label' or ftype == 'warning':
+      ID = getNextId()
+      s = cs | win32con.SS_CENTER #| win32con.WS_BORDER
+      self.template.append([STATIC, label, ID, position, s])
+      self.__texts.append (ID)
+      if ftype == 'warning':
+        self.__warnings.append (ID)
+
+    elif ftype == 'string' or ftype == 'password':
+      ID = getNextId()
+      s = cs | win32con.SS_LEFT #| win32con.WS_BORDER
+      self.template.append([STATIC, label, ID, position, s])
+      self.__labels.append (ID)
+      self.__controls.append (ID)
+      self.controlsName [ID] = name
+      
+      ID = getNextId()
+      s = cs | win32con.WS_TABSTOP | win32con.WS_BORDER
+      if ftype == 'password':
+        s = s | win32con.ES_PASSWORD
+      self.template.append([EDIT, default, ID, position, s])
+      self.__inputs.append (ID)
+
+    elif ftype == 'image':
+      ID = getNextId()
+      s = cs | win32con.SS_BITMAP
+      self.template.append([STATIC, None, ID, position, s])
+      imageFile = name
+      bmp = win32gui.LoadImage(0, imageFile, win32con.IMAGE_BITMAP, \
+                               0, 0, win32con.LR_LOADFROMFILE | 
win32con.LR_DEFAULTSIZE)
+      self.__images[ID] = bmp
+
+    elif ftype == 'button':
+      ID = getNextId()
+      s = cs | win32con.WS_TABSTOP | win32con.BS_PUSHBUTTON
+      self.template.append([BUTTON, label, ID, position, s])
+
+    elif ftype == 'dropdown':
+      ID = getNextId()
+      s = cs | win32con.SS_LEFT #| win32con.WS_BORDER
+      self.template.append([STATIC, label, ID, position, s])
+      self.__labels.append (ID)
+      self.__controls.append (ID)
+      self.controlsName [ID] = name
+      
+      ID = getNextId()
+      s = cs | win32con.WS_TABSTOP | win32con.CBS_DROPDOWNLIST
+      self.template.append([DROPDOWN, default, ID, position, s])
+      self.__inputs.append (ID)
+      self.__dropdowns[ID] = (default, master, elements)
+
+    self.__controls.append (ID)
+    self.controlsName [ID] = name
+
+  def DoModal(self):
+    return win32gui.DialogBoxIndirect(self.hinst, self.template, 0, 
self.message_map)
+
+
+  def OnInitDialog(self, hwnd, msg, wparam, lparam):
+    self.hwnd = hwnd
+
+    # Create a LOGFONT structure for the current font in use
+    hFont   = win32gui.GetObject (win32gui.SendMessage (hwnd, 
win32con.WM_GETFONT, 0, 0))
+    newFont = win32ui.CreateFont ( \
+        {'name'            : hFont.lfFaceName,
+         'height'          : hFont.lfHeight,
+         'width'           : hFont.lfWidth,
+         'charset'         : hFont.lfCharSet,
+         'weight'          : hFont.lfWeight,
+         'italic'          : hFont.lfItalic,
+         'underline'       : hFont.lfUnderline,
+         'pitch and family': hFont.lfPitchAndFamily})
+
+    # Use this font in the device context of the dialog
+    PyCWnd = win32ui.CreateWindowFromHandle(hwnd)
+    self.dc = PyCWnd.GetDC ()
+    of = self.dc.SelectObject (newFont)
+
+    for ID in self.__images.keys():
+      bmCtrl = win32gui.GetDlgItem(hwnd, ID)
+      win32gui.SendMessage(bmCtrl, win32con.STM_SETIMAGE, 
win32con.IMAGE_BITMAP, \
+                           self.__images[ID])
+
+    self.__maxLabelWidth = 0
+    for label in self.__labels:
+      self.__maxLabelWidth = max(self.__maxLabelWidth, self.Width(label))
+
+    self.dlgWidth = 0
+    for control in self.__controls:
+      if control in self.__inputs:
+        self.dlgWidth = max(self.dlgWidth, self.__maxLabelWidth + 
self.Width(control))
+      else:
+        if control not in self.__warnings:
+          self.dlgWidth = max(self.dlgWidth, self.Width(control))
+    
+    border = 10
+    ypos = border
+    for control in self.__controls:
+      if (control in self.__images.keys()) or (control in self.__texts):
+        if control in self.__warnings:
+          dlgItem = win32gui.GetDlgItem(hwnd, control)
+          text = win32gui.GetWindowText(dlgItem)
+          newText = self.wrapText(text, self.dlgWidth)
+          win32gui.SetDlgItemText(hwnd, control, newText)
+          
+        self.SetPosition(control, (self.dlgWidth-self.Width(control))/2 + 
border + 8 , ypos)
+        ypos += self.Height(control) + 5
+      elif control in self.__labels:
+        self.SetPosition(control, border, ypos)
+      else:
+        self.SetPosition(control, border + self.__maxLabelWidth + 10, ypos)
+        ypos += self.Height(control) + 3
+
+      if control in self.__dropdowns.keys():
+        bm = win32gui.GetDlgItem(hwnd, control)
+        default, master, elements = self.__dropdowns[control]
+
+        for key in elements[0][1].keys():
+          try:
+            win32gui.SendMessage(bm, win32con.CB_ADDSTRING, 0, 
elements[0][1][key])
+          except:
+            print 'TODO'
+            
+        win32gui.SendMessage(bm, win32con.CB_SELECTSTRING, -1, default)
+
+    self.SetPosition(win32con.IDCANCEL, self.dlgWidth + 2*border\
+                     - self.Width(win32con.IDCANCEL), ypos + 15)
+    self.SetPosition(win32con.IDOK, self.dlgWidth + 2*border \
+                     - self.Width(win32con.IDCANCEL) \
+                     - self.Width(win32con.IDOK) -4, ypos + 15)
+    ypos += self.Height(win32con.IDOK) + border
+    
+    # resize the dialog
+    win32gui.SetWindowPos(hwnd, 0,
+                              0, 0,
+                              self.dlgWidth + 2*border + 16, ypos + 45,
+                              win32con.SWP_NOACTIVATE | win32con.SWP_NOZORDER)
+    # center the dialog
+    centerWindow(hwnd)
+
+
+  def OnClose(self, hwnd, msg, wparam, lparam):
+    win32gui.EndDialog(hwnd, 0)
+
+
+  def OnCommand(self, hwnd, msg, wparam, lparam):
+    id = win32api.LOWORD(wparam)
+    if id == win32con.IDOK:
+      for control in self.__controls:
+        dlgItem = win32gui.GetDlgItem(self.hwnd, control)
+        self.inputData [self.controlsName [control]] = 
win32gui.GetWindowText(dlgItem)
+      win32gui.EndDialog(hwnd, 1)
+    elif id == win32con.IDCANCEL:
+      self.inputData = None
+      win32gui.EndDialog(hwnd, 0)
+
+
+  def _RegisterWndClass(self):
+    className = "GNUe dialog"
+    global g_registeredClass
+    if not g_registeredClass:
+      message_map = {}
+      wc = win32gui.WNDCLASS()
+      wc.SetDialogProc() # Make it a dialog class.
+      self.hinst = wc.hInstance = win32api.GetModuleHandle(None)
+      wc.lpszClassName = className
+      wc.style = win32con.CS_VREDRAW | win32con.CS_HREDRAW
+      wc.hCursor = win32gui.LoadCursor( 0, win32con.IDC_ARROW )
+      wc.hIcon = win32gui.LoadIcon(0, win32con.IDI_APPLICATION)
+      wc.hbrBackground = win32con.COLOR_WINDOW
+      wc.lpfnWndProc = message_map # could also specify a wndproc.
+      wc.cbWndExtra = win32con.DLGWINDOWEXTRA + struct.calcsize("Pi")
+      classAtom = win32gui.RegisterClass(wc)
+      g_registeredClass = 1
+    return className
+
+  def Width(self, id):
+    item = win32gui.GetDlgItem(self.hwnd, id)
+    if (id in self.__labels) or (id in self.__texts):
+      text = win32gui.GetWindowText(item)
+      if '\n' in text:
+        w = max ([self.dc.GetTextExtent(t) [0] for t in text.split ('\n')])
+      else:
+        w, h = self.dc.GetTextExtent(text)
+      return w
+    elif id in self.__inputs:
+      w, h = self.dc.GetTextExtent('W'*12)
+      return w
+    else:
+      l,t,r,b = win32gui.GetWindowRect(item)
+      return r-l
+
+  def Height(self, id):
+    item = win32gui.GetDlgItem(self.hwnd, id)
+    if (id in self.__labels) or (id in self.__texts):
+      text = win32gui.GetWindowText(item)
+      if '\n' in text:
+        h = sum ([self.dc.GetTextExtent(t) [1] for t in text.split ('\n')])
+      else:
+        w, h = self.dc.GetTextExtent(text)
+      return h
+    elif id in self.__inputs:
+      w, h = self.dc.GetTextExtent('W')
+      return h + 5
+    else:
+      l,t,r,b = win32gui.GetWindowRect(item)
+      return b-t
+
+  def SetPosition(self, id, x, y):
+    item = win32gui.GetDlgItem(self.hwnd, id)
+    win32gui.SetWindowPos(item, 0,
+                          x, y,
+                          self.Width(id), self.Height(id),
+                          win32con.SWP_NOACTIVATE | win32con.SWP_NOZORDER)
+    l,t,r,b = win32gui.GetWindowRect(item)
+
+  def wrapText(self, text, width):
+    textSoFar = ""
+    thisLine = ""
+    for part in text.split('\n'):
+      for word in part.split():
+        if self.dc.GetTextExtent(thisLine + word)[0] > width:
+          textSoFar += thisLine + " \n"
+          thisLine = word + " "
+        else:
+          thisLine += word + " "
+
+      textSoFar += thisLine + " \n"
+      thisLine = ""
+
+    return textSoFar
+
+
 # =============================================================================
 # About Box
 # =============================================================================
@@ -214,3 +568,37 @@
   #desc = "Hey boyz, that thingy is quite complicated"
   x = AboutBox ('Foobar', '1.0', '0.5.2', 'Frodo', desc)
   x.DoModal ()
+ 
+   # 
---------------------------------------------------------------------------
+
+  cname = {'c1': 'demoa', 'c2': 'demob'}
+  ckey  = {'c1': 'ck-A', 'c2': 'ck-B'}
+
+  wija = {'c1': {'04': '2004', '05': '2005'},
+          'c2': {'24': '2024', '25': '2025', '26': '2026'}}
+
+  codes = {'24': {'241': 'c-24-1', '242': 'c-24-2'},
+           '25': {'251': 'c-25-1'}}
+
+  fields = [('Foo!', 'c:/gnue.bmp', 'image',
+             None, None, []),
+            ('Username', '_username', 'string', 'frodo', None, \
+              [('Name of the user', None)]),
+            ('Password', '_password', 'password', 'foo', None, [('yeah',1)]),
+            ('Foobar', '_foobar', 'dropdown', 'frob', None, \
+                [('single', {'trash': 'Da Trash', 'frob': 'Frob'})]),
+            ('Multi', '_multi', 'dropdown', '100', None, \
+                [('name', {'50': 'A 50', '100': 'B 100', '9': 'C 9'}),
+                ('sepp', {'50': 'se 50', '100': 'se 100', '9': 'se 9'})]),
+            ('Noe', '_depp', 'label', 'furz', None, []),
+            ('Das ist jetzt ein Fehler', None, 'warning', None, None, []),
+            ('Firma', 'company', 'dropdown', 'c1', None,
+                [('Name', cname), ('Code', ckey)]),
+            ('Wirtschaftsjahr', 'wija', 'dropdown', '05', 'company',
+                [('Jahr', wija)]),
+            ('Codes', 'codes', 'dropdown', None, 'wija',
+                [('Code', codes)])]
+            
+  dialog = InputDialog('Foobar', fields)
+  dialog.DoModal()
+  print dialog.inputData





reply via email to

[Prev in Thread] Current Thread [Next in Thread]