def _processInternalLink(self, queryString): # Note that all arguments are string if queryString.startswith("app://"): obj = self.Application elif queryString.startswith("form://"): obj = self.Form else: raise ValueError, _( "Internal link must resolve to Form or Application.") queryString = queryString[queryString.index("//") + 2:] try: meth, args = queryString.split("?") qsargs = args.split("&") except ValueError: meth = queryString qsargs = [] args = [] kwargs = {} for qsarg in qsargs: try: name, value = qsarg.split("=", 1) kwargs[name] = value except ValueError: args.append(qsarg) getattr(obj, meth)(*args, **kwargs)
def createBody(self): self.Caption = _("This is the first page") lbl = dabo.ui.dLabel(self, Caption=_( """Are you getting excited yet??? I know that I am!!""")) self.Sizer.append(lbl, alignment="center")
def onChangeCaption(self, evt): nd = self.activeNode self.activeNode = None txt = dabo.ui.getString(_("New Caption"), _("Adding Child Node"), defaultValue=nd.Caption) if txt is not None: nd.Caption = txt
def onNewProfile(self, evt): base = _("New Profile") i = 1 while True: default = "%s %s" % (base, i) if default in self.ddProfile.Choices: i += 1 else: break name = dabo.ui.getString(_("Please enter a name for the profile"), defaultValue=default) if name is not None: # Defualt to the current DbType currDbType = self.ctlDbType.Value self.dbDefaults[name] = { "DbType": currDbType, "Name": "", "Host": "", "Database": "", "User": "", "Password": "", "Port": "" } ddProfile = self.ddProfile ddProfile.Choices = self.dbDefaults.keys() ddProfile.Value = name self.ctlDbType.Value = "MySQL" self.ctlPort.Value = "3306" self.ctlDbType.setFocus()
def addControls(self): hs = dabo.ui.dSizer("h") hs.append(dabo.ui.dButton(self, Caption=_("Preview"), RegID="butPreview"), alignment="right", border=self.SizerBorder) hs.append(dabo.ui.dButton(self, Caption=_("Print"), RegID="butPrint"), alignment="right", border=self.SizerBorder) self.Sizer.append(hs, alignment="bottom", border=self.SizerBorder)
def afterInit(self): sz = dui.dGridSizer(VGap=5, HGap=8, MaxCols=2) lbl = dui.dLabel(self, Caption=_("HGap")) ctl = dui.dSpinner(self, DataField="HGap") sz.append(lbl, halign="right") sz.append(ctl) lbl = dui.dLabel(self, Caption=_("VGap")) ctl = dui.dSpinner(self, DataField="VGap") sz.append(lbl, halign="right") sz.append(ctl) lbl = dui.dLabel(self, Caption=_("Rows")) ctl = dui.dSpinner(self, DataField="Rows") sz.append(lbl, halign="right") sz.append(ctl) lbl = dui.dLabel(self, Caption=_("Columns")) ctl = dui.dSpinner(self, DataField="Columns") sz.append(lbl, halign="right") sz.append(ctl) lbl = dui.dLabel(self, Caption=_("MaxDimension")) ctl = dui.dDropdownList(self, DataField="MaxDimension", Choices=["C", "R"], Value="C") sz.append(lbl, halign="right") sz.append(ctl) self.Sizer = dui.dSizer("v") self.Sizer.append1x(sz, border=20, borderSides=("left", "right", "bottom")) self.Sizer.appendSpacer(20)
def _setCustomDate(self): days = dabo.ui.getInt(message=_("Day shift:"), caption=_("Reschedule day"), Min=-365, Max=365) if days: self.dayInterval(days)
def loadUI(uiType): """Load the given UI into the global namespace.""" retVal = False currType = getUIType() mods = {"wx" : "dabo.ui.uiwx", "tk" : "dabo.ui.uitk"} if uiType.lower() in ("wx", "wxpython", "uiwx"): typ = "wx" elif uiType.lower() in ("tk", "tkinter", "uitk"): typ = "tk" else: raise ValueError("Unknown UI type '%s' passed to loadUI()" % uiType) if currType is None: try: exec("from %s import *" % mods[typ], globals()) retVal = True except Exception as e: retVal = False # Record the actual problem print(_("ui.loadUI failed: %s") % e) traceback.print_exc() else: if currType == typ: # No problem; just a redundant call pass else: dabo.log.info(_("Cannot change the uiType to '%(typ)s', because UI '%(currType)s' is already loaded.") % locals()) return retVal
class DlgInfoMessage(dabo.ui.dStandardButtonDialog): def initProperties(self): self.AutoSize = True self.ShowCaption = False self.ShowCloseButton = False def addControls(self): vs = self.Sizer = dabo.ui.dSizer("v", DefaultBorder=10) vs.append1x(LblMessage(self, RegID="lblMessage", Caption=self.Message)) vs.append(dabo.ui.dCheckBox(self, Caption=_("Show this message in the future?"), Value=self.DefaultShowInFuture, RegID="chkShowInFuture", FontSize=9)) def _getDefaultShowInFuture(self): return getattr(self, "_defaultShowInFuture", True) def _setDefaultShowInFuture(self, val): self._defaultShowInFuture = bool(val) def _getMessage(self): return getattr(self, "_message", "") def _setMessage(self, val): self._message = val DefaultShowInFuture = property(_getDefaultShowInFuture, _setDefaultShowInFuture, None, _("Specifies whether the 'show in future' checkbox is checked by default.")) Message = property(_getMessage, _setMessage, None, _("Specifies the message to display."))
def save(self, dataSource=None): """Ask the bizobj to commit its changes to the backend.""" self.dataSourceParameter = dataSource bizobj = self.getBizobj(dataSource) if bizobj is None: # Running in preview or some other non-live mode return self.activeControlValid() err = self.beforeSave() if err: self.notifyUser(err) return False try: if self.SaveAllRows: bizobj.saveAll(saveTheChildren=self.SaveChildren) else: bizobj.save(saveTheChildren=self.SaveChildren) self.setStatusText( _("Changes to %s saved.") % (self.SaveAllRows and "all records" or "current record", )) except dException.ConnectionLostException, e: msg = self._connectionLostMsg(ustr(e)) self.notifyUser(msg, title=_("Data Connection Lost"), severe=True, exception=e) sys.exit()
def cancel(self, dataSource=None, ignoreNoRecords=None): """ Ask the bizobj to cancel its changes. This will revert back to the state of the records when they were last requeried or saved. """ self.dataSourceParameter = dataSource bizobj = self.getBizobj(dataSource) if bizobj is None: # Running in preview or some other non-live mode return self.activeControlValid() if ignoreNoRecords is None: ignoreNoRecords = True err = self.beforeCancel() if err: self.notifyUser(err) return try: if self.SaveAllRows: bizobj.cancelAll(ignoreNoRecords=ignoreNoRecords, cancelTheChildren=self.CancelChildren) else: bizobj.cancel(ignoreNoRecords=ignoreNoRecords, cancelTheChildren=self.CancelChildren) self.update() self.setStatusText( _("Changes to %s canceled.") % (self.SaveAllRows and "all records" or "current record", )) except dException.NoRecordsException, e: dabo.log.error(_("Cancel failed; no records to cancel."))
def beforeAppendOnEnter(self): txt = self._textToAppend.strip().lower() if txt == "dabo": print _("Attempted to add Dabo to the list!!!") return False elif txt.find("nixon") > -1: self._textToAppend = "Tricky Dick"
def onOutputRightDown(self, evt): pop = dabo.ui.dMenu() pop.append(_("Clear"), OnHit=self.onClearOutput) if self.edtOut.SelectionLength: pop.append(_("Copy"), OnHit=self.Application.onEditCopy) self.showContextMenu(pop) evt.stop()
def onRunDesign(self, evt): # First, make sure that it's been saved try: fname = self.onSaveDesign(None, useTmp=True) except IOError as e: dabo.ui.info(_("Cannot write file"), title=_("Write Error")) if not fname or not os.path.isfile(fname): # Nothing was saved return pth = os.path.split(os.path.abspath(fname))[0] # Set the app's HomeDirectory to the location of the cdxml file. self.Application.HomeDirectory = pth if pth not in sys.path: sys.path.append(pth) if self._formMode: frm = dui.createForm(fname) else: frm = dui.dForm(None) obj = frm.addObject(fname) if frm.Sizer: frm.Sizer.append1x(obj) frm.Caption = _("Test form for: %s") % os.path.split(fname)[1] frm.layout() frm.TempForm = True frm.Visible = True if isinstance(frm, dlgs.Wizard): frm.start() if isinstance(frm, dabo.ui.dDialog): def __dlgRelease(evt): evt.EventObject.release() frm.bindEvent(dEvents.Close, __dlgRelease)
def getCurrentRecordText(self, dataSource=None, grid=None): """Get the text to describe which record is current.""" self.dataSourceParameter = dataSource if dataSource is None and grid is not None: # This is being called by a regular grid not tied to a bizobj rowCount = grid.RowCount rowNumber = grid.CurrentRow + 1 else: bizobj = self.getBizobj(dataSource) if bizobj is None: try: # Some situations, such as form preview mode, will # store these directly, since they lack bizobjs rowCount = self.rowCount rowNumber = self.rowNumber + 1 except AttributeError: return "" else: rowCount = bizobj.RowCount if rowCount > 0: rowNumber = bizobj.RowNumber + 1 else: rowNumber = 1 if rowCount < 1: return _("No records") return _("Record %(rowNumber)s/%(rowCount)s") % locals()
def addControls(self): self.Caption = _("HotKey Editor") self._alt = False self._changed = None self._ctrl = False self._keyChar = "" self._keyCode = -1 self._keyText = "" self._shift = False self._originalKeyString = None sz = self.Sizer sz.append(dabo.ui.dLabel( self, Caption=_("Press the desired key combination")), border=10, halign="center") sz.append(dabo.ui.dLabel( self, Caption=_("Press Ctrl-Delete to clear the key")), border=10, halign="center") sz.appendSpacer(10) bsz = dabo.ui.dBorderSizer(self, "v") self.hkLabel = dabo.ui.dLabel(self, Caption=" " * 80, FontSize=16, FontBold=True) bsz.append1x(self.hkLabel, halign="center", border=10) sz.append(bsz, halign="center") # Pass key events from the OK/Cancel buttons up to the form self.CancelButton.bindEvent(dEvents.KeyUp, self.onKeyUp) self.OKButton.bindEvent(dEvents.KeyUp, self.onKeyUp)
def onAddSibling(self, evt): nd = self.activeNode self.activeNode = None txt = dabo.ui.getString(_("New Node Caption?"), _("Adding Sibling Node")) if txt is not None: nd.parent.appendChild(txt)
def _persist(self, att, val): """Writes the value of the particular att to the database with the proper key.""" # Make sure that we have a valid key baseKey = self._getKey() if not baseKey: if not self._persistAll: dabo.log.error(_("No base key set; preference will not be persisted.")) return else: key = att else: key = "%s.%s" % (baseKey, att) crs = self._cursor try: typ = self._typeDict[type(val)] except KeyError: dabo.log.error(_("BAD TYPE: %s") % type(val)) typ = "?" # Convert it to a string that can be properly converted back val = self._encodeType(val, typ) sql = "update daboprefs set ctype = ?, cvalue = ? where ckey = ? " prm = (typ, val, key) crs.execute(sql, prm) # Use the dbapi-level 'rowcount' attribute to get the number # of affected rows. if not crs.rowcount: sql = "insert into daboprefs (ckey, ctype, cvalue) values (?, ?, ?)" prm = (key, typ, val) crs.execute(sql, prm) self._cursor.commitTransaction()
def deleteAll(self, dataSource=None, message=None): """Ask the primary bizobj to delete all records from the recordset.""" self.dataSourceParameter = dataSource bizobj = self.getBizobj(dataSource) if bizobj is None: # Running in preview or some other non-live mode return self.activeControlValid() err = self.beforeDeleteAll() if err: self.notifyUser(err) return if not message: message = _("This will delete all records in the recordset, and cannot " "be canceled.\n\n Are you sure you want to do this?") if dabo.ui.areYouSure(message, defaultNo=True): try: bizobj.deleteAll() # Notify listeners that the row number changed: self.raiseEvent(dEvents.RowNumChanged) except dException.ConnectionLostException, e: msg = self._connectionLostMsg(ustr(e)) self.notifyUser(msg, title=_("Data Connection Lost"), severe=True, exception=e) sys.exit() except dException.dException, e: dabo.log.error(_("Delete All failed with response: %s") % e) self.notifyUser(ustr(e), title=_("Deletion Not Allowed"), severe=True, exception=e)
def onNewProfile(self, evt): base = _("New Profile") i = 1 while True: default = "%s %s" % (base, i) if default in self.ddProfile.Choices: i += 1 else: break name = dabo.ui.getString(_("Please enter a name for the profile"), defaultValue=default) if name is not None: # Defualt to the current DbType currDbType = self.ctlDbType.Value self.dbDefaults[name] = { "DbType" : currDbType, "Name" : "", "Host" : "", "Database" : "", "User" : "", "Password" : "", "Port" : "" } ddProfile = self.ddProfile ddProfile.Choices = self.dbDefaults.keys() ddProfile.Value = name self.ctlDbType.Value = "MySQL" self.ctlPort.Value = "3306" self.ctlDbType.setFocus()
def onAddSibling(self, evt): nd = self.activeNode self.activeNode = None txt = dui.getString(_("New Node Caption?"), _("Adding Sibling Node")) if txt is not None: nd.parent.appendChild(txt) self.Controller.updateLayout()
def onCheckSyntax(self, evt): ed = self.editor txt = ed.Value lns = txt.strip().splitlines() # Add an extra blank line to get around the trailing comment bug lns.append("") compText = "\n".join(lns) try: compile(compText, "", "exec") dabo.ui.exclaim(_("No syntax errors found!"), _("Compilation Succeeded")) except SyntaxError, e: errMsg = "%s" % e try: msg, num = self._syntaxLinePat.findall(errMsg)[0] except (ValueError, IndexError): msg = errMsg num = None if num is not None: num = int(num) disp = _("Error: %(msg)s\nLine: %(num)s") % locals() ed.LineNumber = num - 3 ed.showCurrentLine() ed.hiliteLine(num - 1) else: disp = msg dabo.ui.stop(disp, _("Compilation Failed"))
def _persist(self, att, val): """Writes the value of the particular att to the database with the proper key.""" # Make sure that we have a valid key baseKey = self._getKey() if not baseKey: if not self._persistAll: dabo.log.error( _("No base key set; preference will not be persisted.")) return else: key = att else: key = "%s.%s" % (baseKey, att) crs = self._cursor try: typ = self._typeDict[type(val)] except KeyError: dabo.log.error(_("BAD TYPE: %s") % type(val)) typ = "?" # Convert it to a string that can be properly converted back val = self._encodeType(val, typ) sql = "update daboprefs set ctype = ?, cvalue = ? where ckey = ? " prm = (typ, val, key) crs.execute(sql, prm) # Use the dbapi-level 'rowcount' attribute to get the number # of affected rows. if not crs.rowcount: sql = "insert into daboprefs (ckey, ctype, cvalue) values (?, ?, ?)" prm = (key, typ, val) crs.execute(sql, prm) self._cursor.commitTransaction()
def showPage(self): if self.PageCount == 0: return if self._blankPage: self.pagePanel.Sizer.remove(self._blankPage) self._blankPage.release() for idx in range(self.PageCount): page = self._pages[idx] self.pagePanel.Sizer.remove(page) if idx == self._currentPage: page.Visible = True # Need this to keep the pages resizing correctly. page.Size = self.pagePanel.Size # Helps the pages look better under Windows if self.setPageColor: page.BackColor = self.BackColor self.pagePanel.Sizer.append(page, 1, "x") self.btnBack.Enabled = (idx > 0) cap = _("Next >") if idx == (self.PageCount - 1): cap = _("Finish") self.btnNext.Caption = cap if page.Picture is not None: self.wizardIcon.Picture = page.Picture else: self.wizardIcon.Picture = self.Picture else: page.Visible = False self.layout()
def afterInit(self): self.Sizer = dabo.ui.dSizer("v") sz = dabo.ui.dGridSizer(MaxCols=2, HGap=7, VGap=12) self.Sizer.append(sz, "x", border=30, valign="middle") # Plain textbox lbl = dabo.ui.dLabel(self, Caption=_("Plain TextBox")) txt = dabo.ui.dTextBox(self, Name=_("PlainTextBox"), Value=_("Test it out and see")) txt.SelectionStart = 0 sz.append(lbl, halign="right") sz.append(txt, "x") txt.bindEvent(dEvents.GotFocus, self.onTextGotFocus) txt.bindEvent(dEvents.LostFocus, self.onTextLostFocus) txt.bindEvent(dEvents.Destroy, self.onTextDestroy) txt.bindEvent(dEvents.KeyChar, self.onTextKeyChar) txt.bindEvent(dEvents.Hit, self.onTextHit) # Password textbox lbl = dabo.ui.dLabel(self, Caption=_("Password")) txt = dabo.ui.dTextBox(self, Name=_("Password TextBox"), PasswordEntry=True) sz.append(lbl, halign="right") sz.append(txt, "x") txt.bindEvent(dEvents.GotFocus, self.onTextGotFocus) txt.bindEvent(dEvents.LostFocus, self.onTextLostFocus) txt.bindEvent(dEvents.Destroy, self.onTextDestroy) txt.bindEvent(dEvents.KeyChar, self.onTextKeyChar) txt.bindEvent(dEvents.Hit, self.onTextHit) # Let the textbox column grow sz.setColExpand(True, 1) self.layout()
def addControls(self): self.useStandard = True self.Caption = _("Select a Picture") sz = self.Sizer sz.appendSpacer(20) sz.DefaultSpacing = 10 sz.DefaultBorder = 20 sz.DefaultBorderLeft = sz.DefaultBorderRight = True btn = dabo.ui.dButton(self, Caption=_("Select your own image...")) btn.bindEvent(dEvents.Hit, self.onSelectOwn) sz.append(btn, halign="center") sz.append(dabo.ui.dLine(self), border=25, borderSides=("left", "right")) sz.append(dabo.ui.dLabel(self, Caption="- or -"), halign="center") lbl = dabo.ui.dLabel(self, Caption=_("Select a standard image:")) dd = dabo.ui.dDropdownList(self, RegID="ddIcons", Choices=defIcons, OnHit=self.updImage) hsz = dabo.ui.dSizer("h") hsz.append(lbl) hsz.appendSpacer(5) hsz.append(dd) sz.append(hsz, halign="center", border=16) hsz = dabo.ui.dSizer("h") img = dabo.ui.dImage(self, Picture="", Size=(64, 64), RegID="img") bsz = dabo.ui.dBorderSizer(self) bsz.append(img, border=8, halign="center", valign="middle") hsz.append(bsz) hsz.appendSpacer(16) btn = dabo.ui.dButton(self, Caption=_("Select"), OnHit=self.onSelect) hsz.append(btn, valign="middle") sz.append(hsz, halign="center") sz.append(dabo.ui.dLine(self), border=25, borderSides=("left", "right")) btn = dabo.ui.dButton(self, Caption=_("Cancel"), OnHit=self.onCancel) sz.append(btn, halign="right", border=20, borderSides=("right",)) sz.appendSpacer(25) self._selected = False
def addControls(self): sz = self.Sizer sz.appendSpacer(25) lbl = dabo.ui.dLabel(self, FontBold=True, ForeColor="darkred", WordWrap=True, Alignment="center", Caption=_("The label below has WordWrap=True. " + \ "Use the slider to resize the label to see it in action.")) lbl.FontSize += 1 sz.append(lbl, "x", border=40, borderSides=("Left", "Right")) sld = self.slider = dabo.ui.dSlider(self, Value=100, Continuous=False) sld.bindEvent(dEvents.Hit, self.onSlider) sld.bindEvent(dEvents.Resize, self.onSlider) sz.append(sld, "x", border=10) txt = getGettyAddr() lbl = self.gettyLabel = dabo.ui.dLabel(self, Caption=txt, WordWrap=True) sz.append(lbl, 1, border=10) self.Caption = _("WordWrap Demo") self.Width = 640 self.Height = 480 self.layout()
def onSetAutoCompleteLength(self, evt): ed = self.CurrentEditor curr = ed.AutoAutoCompleteMinLen import dabo newlen = dabo.ui.getInt(_("Number of characters?"), _("Set AutoComplete Trigger"), curr) if newlen: ed.AutoAutoCompleteMinLen = newlen
def insert(self, index, obj, layout="normal", proportion=0, alignment=None, halign="left", valign="top", border=None, borderSides=None): """Inserts the passed object into the sizer layout at the specified position.""" if obj in self.ChildSizers: raise ValueError, _("Adding the same sizer twice is not allowed.") if isinstance(layout, int): # proportion was passed first layout, proportion = proportion, layout # in case layout wasn't specified if isinstance(layout, int): layout = "normal" if isinstance(obj, (int, tuple)): # obj is a spacer ret = self.addSpacer(obj, pos=index, proportion=proportion) else: # obj is the window to add to the sizer _wxFlags = self._getWxFlags(alignment, halign, valign, borderSides, layout) if border is None: border = self.DefaultBorder # If there are objects in this sizer already, add the default spacer addSpacer = ( len(self.GetChildren()) > 0) ret = szItem = self.Insert(index, obj, proportion=proportion, flag=_wxFlags, border=border, userData=self) if addSpacer: self.addDefaultSpacer(index) obj._controllingSizer = self obj._controllingSizerItem = szItem if ret.IsSizer(): obj._parent = self._parent return ret
def setupSaveCancelButtons(self): vs = self.Sizer hs = dabo.ui.dSizer("h") hs.append(dabo.ui.dButton(self, Caption=_("Save Changes"), DefaultButton=True, OnHit=self.onSave)) hs.appendSpacer((3,0)) hs.append(dabo.ui.dButton(self, Caption=_("Cancel Changes"), CancelButton=True, OnHit=self.onCancel)) vs.append(hs, alignment="right")
def onCheckSyntax(self, evt): ed = self.editor txt = ed.Value lns = txt.strip().splitlines() # Add an extra blank line to get around the trailing comment bug lns.append("") compText = "\n".join(lns) try: compile(compText, "", "exec") dabo.ui.exclaim(_("No syntax errors found!"), _("Compilation Succeeded")) except SyntaxError as e: errMsg = "%s" % e try: msg, num = self._syntaxLinePat.findall(errMsg)[0] except (ValueError, IndexError): msg = errMsg num = None if num is not None: num = int(num) disp = _("Error: %(msg)s\nLine: %(num)s") % locals() ed.LineNumber = num-3 ed.showCurrentLine() ed.hiliteLine(num-1) else: disp = msg dabo.ui.stop(disp, _("Compilation Failed"))
def _setHotKey(self, evt): dlg = HotKeyEditor(self) itm = self._selectedItem origKey = itm.hotkey dlg.setKey(origKey) dlg.show() if dlg.Accepted: hk = dlg.KeyText change = (hk != origKey) dupeItem = None if change: dupeItem = self._hotKeyMap.get(hk) if dupeItem and (dupeItem is not itm): msg = _("This key combination is assigned to the menu command '%s'. " + "Do you wish to re-assign it to the command '%s'?") % (cleanMenuCaption(dupeItem.Caption, "&_"), cleanMenuCaption(itm.Caption, "&_")) change = dabo.ui.areYouSure(msg, title=_("Duplicate Keystroke"), defaultNo=True, cancelButton=False) if change: if dupeItem: # Un-assign that hotkey dupeItem.HotKey = None # Clear it from the tree nd = self.menuKeyAssignmentTree.nodeForObject(dupeItem) if nd: nd.hotkey = None if origKey: self._hotKeyMap.pop(origKey) if hk: # Set the internal key map. self._hotKeyMap[hk] = itm.Object self.txtMenuCurrentHotKey.Value = itm.hotkey = itm.Object.HotKey = hk itm.pref.setValue("hotkey", hk) dlg.release() self.pgMenuKeys.update()
def customCanGetValueAs(self, row, col, typ): ret = True if col == 0: ret = typ in ("str", "string", "unicode", "u") else: if not self.Controller.Selection: return type(None) pd = self.getPropDictForRow(row) if not isinstance(pd, dict): if pd is not None: print _("BAD PROP DICT:"), pd, type(pd), _("ROW="), row else: if pd["type"] == "multi": # This is a catch-all setting for props such as 'Value' that # can have any number of types. ret = True else: typtyp = { "str": str, "unicode": str, "bool": bool, "int": int, "long": int, "szinfo": str, "double": float }[typ] ret = pd["type"] == typtyp return ret
def onLeavePage(self, direction): if direction == "forward": # Make sure that there are values entered appdir = self.txtDir.Value appname = self.txtAppName.Value if not appdir or not appname: dabo.ui.stop(_("Please enter both a name for your app and a location."), _("Missing Information")) return False directory = os.path.join(appdir, appname) if not os.path.exists(directory): msg = _("The target directory %s does not exist. Do you want to create it now?") % directory if dabo.ui.areYouSure(msg, _("Create Directory?"), cancelButton=False): os.makedirs(directory) else: return False else: if not os.path.isdir(directory): dabo.ui.stop(_("The target of '%s' is a pre-existing file, not a directory. " "Please pick a different directory name.") % directory) return False self.Form.outputDirectory = directory app.setUserSetting("defaultLocation", appdir) self.Form.usePKUI = self.chkPKUI.Value self.Form.useUnknown = self.chkUnknown.Value self.Form.sortFieldsAlpha = self.chkSortFieldsAlpha.Value app.setUserSetting("UsePKUI", self.chkPKUI.Value ) app.setUserSetting("UseUnknown", self.chkUnknown.Value ) app.setUserSetting("SortFieldsAlpha", self.chkSortFieldsAlpha.Value ) return True
def save(self, dataSource=None): """Ask the bizobj to commit its changes to the backend.""" self.dataSourceParameter = dataSource bizobj = self.getBizobj(dataSource) if bizobj is None: # Running in preview or some other non-live mode return self.activeControlValid() err = self.beforeSave() if err: self.notifyUser(err) return False try: if self.SaveAllRows: bizobj.saveAll(saveTheChildren=self.SaveChildren) else: bizobj.save(saveTheChildren=self.SaveChildren) self.setStatusText(_("Changes to %s saved.") % ( self.SaveAllRows and "all records" or "current record",)) except dException.ConnectionLostException, e: msg = self._connectionLostMsg(ustr(e)) self.notifyUser(msg, title=_("Data Connection Lost"), severe=True, exception=e) sys.exit()
def customCanGetValueAs(self, row, col, typ): ret = True if col == 0: ret = typ in ("str", "string", "unicode", "u") else: if not self.Controller.Selection: return type(None) pd = self.getPropDictForRow(row) if not isinstance(pd, dict): if pd is not None: print(_("BAD PROP DICT:"), pd, type(pd), _("ROW="), row) else: if pd["type"] == "multi": # This is a catch-all setting for props such as 'Value' that # can have any number of types. ret = True else: typtyp = { "str": str, "unicode": str, "bool": bool, "int": int, "long": int, "szinfo": str, "double": float, }[typ] ret = pd["type"] == typtyp return ret
def getCurrentRecordText(self, dataSource=None, grid=None): """Get the text to describe which record is current.""" self.dataSourceParameter = dataSource if dataSource is None and grid is not None: # This is being called by a regular grid not tied to a bizobj rowCount = grid.RowCount rowNumber = grid.CurrentRow + 1 else: bizobj = self.getBizobj(dataSource) if bizobj is None: try: # Some situations, such as form preview mode, will # store these directly, since they lack bizobjs rowCount = self.rowCount rowNumber = self.rowNumber + 1 except AttributeError: rowCount = 1 rowNumber = 1 else: rowCount = bizobj.RowCount if rowCount > 0: rowNumber = bizobj.RowNumber + 1 else: rowNumber = 1 if rowCount < 1: return _("No records") return _("Record %(rowNumber)s/%(rowCount)s") % locals()
def cancel(self, dataSource=None, ignoreNoRecords=None): """ Ask the bizobj to cancel its changes. This will revert back to the state of the records when they were last requeried or saved. """ self.dataSourceParameter = dataSource bizobj = self.getBizobj(dataSource) if bizobj is None: # Running in preview or some other non-live mode return self.activeControlValid() if ignoreNoRecords is None: ignoreNoRecords = True err = self.beforeCancel() if err: self.notifyUser(err) return try: if self.SaveAllRows: bizobj.cancelAll(ignoreNoRecords=ignoreNoRecords, cancelTheChildren=self.CancelChildren) else: bizobj.cancel(ignoreNoRecords=ignoreNoRecords, cancelTheChildren=self.CancelChildren) self.update() self.setStatusText(_("Changes to %s canceled.") % ( self.SaveAllRows and "all records" or "current record",)) except dException.NoRecordsException, e: dabo.log.error(_("Cancel failed; no records to cancel."))
def createBody(self): self.Caption = _("This is the third page") lbl = dabo.ui.dLabel(self, Caption=_( """You should only see this if you did not check the box on Page Two. """)) self.Sizer.append(lbl, alignment="center")
def onContextMenu(self, evt): pop = dabo.ui.dMenu() pop.append(_("Create Base Menu"), OnHit=self.onCreateBaseMenu, Help="BASE") pop.append(_("Add Menu"), OnHit=self.onAddMenu) self.showContextMenu(pop)
def onConfigGrid(self, evt): try: grid = self.PageFrame.Pages[1].BrowseGrid ds = grid.DataSet except: dabo.ui.info(_("Sorry, there are no records in the grid, please requery first.")) return #cols cols = [col.Caption for col in grid.Columns] #keys keys = [col.DataField for col in grid.Columns] class GridColumnsDialog(dabo.ui.dOkCancelDialog): def initProperties(self): self.selectedColumns = None def addControls(self): self.addObject(dabo.ui.dLabel, RegID="label", Caption=_("You can customize grid appearence by selecting\nthe columns you wish to see bellow:"), WordWrap=True) self.addObject(dabo.ui.dCheckList, RegID="columns", Height=150, ValueMode="Key", Choices=cols, Keys=keys) for col in grid.Columns: if col.Visible: self.columns.setSelection(col.ColumnIndex) self.Sizer.DefaultBorder = 5 self.Sizer.DefaultBorderAll = True self.Sizer.append(self.label, border=5) self.Sizer.append1x(self.columns) def runOK(self): self.selectedColumns = self.columns.Value def runCancel(self): self.selectedColumns = None d = GridColumnsDialog(self, Caption=_("Select Columns")) d.show() #the user has canceled, just return if d.selectedColumns == None: return for col in grid.Columns: if col.DataField in d.selectedColumns: col.Visible = True else: col.Visible = False #release the window d.release()
def createBody(self): self.Caption = _("Sample") self.HorizontalScroll = False self.lastStyle = "" self.lastFldList = [] self.controls = {} self.controlSizer = None self.samplePanel = None self.sampleWidth = None self.editText = None self.grid = None self._outsideBorder = 0 self._betweenSpacing = 0 self._columnSpacing = 0 self._labelAlignment = "Left" self._labels = [] self._layoutControls = [] self._controlSizer = None self._useColons = False self._useTitleCase = False lbl = dabo.ui.dLabel(self, Caption=_("Double-click a caption to edit"), FontSize=8, FontItalic=True) self.Sizer.append(lbl, halign="center") self.rClickLbl = dabo.ui.dLabel( self, Caption=_("Right-click a control to change its type"), FontSize=8, FontItalic=True) self.Sizer.append(self.rClickLbl, halign="center", border=3, borderSides="top") self.samplePanel = dabo.ui.dScrollPanel(self, BackColor="papayawhip") itm = self.Sizer.append1x(self.samplePanel, border=3, borderSides="top") self.samplePanel.Sizer = LayoutSizer("v") # Define an editable label class class EditLabel(dabo.ui.dLabel): def afterInit(self): self.origCap = self.Caption # The label will be on the sample panel, which is on the page # that contains the actual event code. self.bindEvent(dEvents.MouseLeftDoubleClick, self.Parent.Parent.onLblEdit) # Store the original caption for later reference dabo.ui.callAfter(self._storeCaption) def _storeCaption(self, cap=None): if cap is None: cap = self.Caption # Save the Caption as an editing reference self.origCap = self.Caption #Save the classdef for future use self.editLabelClass = EditLabel
def createBody(self): self.Caption = _("This is the fifth (and last) page") lbl = dabo.ui.dLabel(self, Caption=_( """This is the last page. Note that the 'Next' button now reads 'Finish'. Click that to exit, or click 'Back' to play some more. """)) self.Sizer.append(lbl, alignment="center")
def addEditPages(self, ds): """Called when it is time to add the edit page(s).""" biz = self.getBizobj() if biz: caption = _("Edit") + " " + biz.Caption else: caption = _("Edit") self.addEditPage(ds, caption)
def createMenu(self): mb = self.MenuBar fm = mb.getMenu("base_file") fm.prepend(_("Open Connection File..."), HotKey="Ctrl+O", OnHit=self.onOpenFile, ItemID="file_open", help=_("Open an existing connection file"))
class PlotMarkers(_TraceMixin, plot.PolyMarker): def __init__(self, *args, **kwargs): self._fillStyle = "solid" plot.PolyMarker.__init__(self, *args, **kwargs) #Property getters and setters def _getFillStyle(self): return self._fillStyle def _setFillStyle(self, val): if val in ['solid', 'empty']: self.attributes['style'] = dict(solid=wx.SOLID, empty=wx.TRANSPARENT)[val] self._fillStyle = val else: raise ValueError("LineStyle must be either 'solid' or 'empty'") def _getMarkerShape(self): return self.attributes['marker'] def _setMarkerShape(self, val): if val in [ 'circle', 'dot', 'square', 'triangle', 'triangle_down', 'cross', 'plus' ]: self.attributes['marker'] = val else: raise ValueError( "MarkerShape must be either 'circle', 'dot', 'square', 'triangle', 'triangle_down', 'cross', or 'plus'" ) def _getMarkerSize(self): return self.attributes['size'] def _setMarkerSize(self, val): self.attributes['size'] = int(val) #Property definitions FillStyle = property( _getFillStyle, _setFillStyle, None, _("The fill style for the marker (default='solid') ('solid' or 'empty')" )) MarkerShape = property( _getMarkerShape, _setMarkerShape, None, _("""The style for the marker (default='circle) (str) The marker style can be any of the following: - 'circle' - 'dot' - 'square' - 'triangle' - 'triangle_down' - 'cross' - 'plus'""")) MarkerSize = property(_getMarkerSize, _setMarkerSize, None, _("The size of the marker (default=2) (int)"))
def onLeavePage(self, direction): if direction == "forward": if len(self.Form.tableDict) > 0: if not dabo.ui.areYouSure( _("Overwrite the current table information?")): return True # Set the wizard's connect info based on the user input: ci = self.Form.connectInfo dbType = self.ctlDbType.Value try: ci.DbType = dbType except ValueError: dabo.ui.stop( _("The database type '%s' is invalid. " + "Please reenter and try again.") % dbType) self.ctlDbType.setFocus() return False embedded = dbType in self.embeddedDbTypes ci.Database = self.ctlDatabase.Value ci.Name = self.ctlName.Value if not embedded: ci.Host = self.ctlHost.Value ci.User = self.ctlUser.Value ci.Password = ci.encrypt(self.ctlPassword.Value) try: ci.Port = int(self.ctlPort.Value) except ValueError: ci.Port = None # Try to get a connection: busy = dabo.ui.busyInfo(_("Connecting to database...")) try: conn = dabo.db.dConnection(ci) cursor = self.Form.cursor = conn.getDaboCursor( ci.getDictCursorClass()) cursor.BackendObject = ci.getBackendObject() tables = cursor.getTables() except Exception, e: busy = None traceback.print_exc() dabo.ui.stop( _("Could not connect to the database server. " + "Please check your parameters and try again.")) return False busy = None self.Form.tableDict = {} tableOrder = 0 for table in tables: # Firebird databases have system tables with '$' in the name if table.find("$") > -1: continue tableDict = {} tableDict["name"] = table tableDict["order"] = tableOrder self.Form.tableDict[table] = tableDict tableOrder += 1
def onShellRight(self, evt): pop = dabo.ui.dMenu() if self.SplitState: pmpt = _("Unsplit") else: pmpt = _("Split") pop.append(pmpt, OnHit=self.onSplitContext) self.showContextMenu(pop) evt.StopPropagation()
def requery(self, dataSource=None): """Ask the bizobj to requery.""" self.dataSourceParameter = dataSource ret = False bizobj = self.getBizobj(dataSource) if bizobj is None: # Running in preview or some other non-live mode return oldRowNumber = bizobj.RowNumber self.activeControlValid() err = self.beforeRequery() if err: self.notifyUser(err) return if not self.confirmChanges(bizobjs=bizobj): # A False from confirmChanges means "don't proceed" return ## A user-initiated requery should expire the cache on child bizobjs too: bizobj.expireCache() try: self.StatusText = _("Please wait... requerying dataset...") # busy = dabo.ui.busyInfo(_("Please wait... requerying dataset...")) self.stopWatch.Start() # response = dProgressDialog.displayAfterWait(self, 2, bizobj.requery) response = bizobj.requery() self.stopWatch.Pause() elapsed = round(self.stopWatch.Time() / 1000.0, 3) # del busy self.update() newRowNumber = bizobj.RowNumber if newRowNumber != oldRowNumber: # Notify listeners that the row number changed: self.raiseEvent(dEvents.RowNumChanged, newRowNumber=newRowNumber, oldRowNumber=oldRowNumber, bizobj=bizobj) # We made it through without errors ret = True rc = bizobj.RowCount plcnt = bizobj.RowCount == 1 and " " or "s " plelap = elapsed == 1 and "." or "s." self.StatusText = (_( "%(rc)s record%(plcnt)sselected in %(elapsed)s second%(plelap)s" ) % locals()) except dException.MissingPKException, e: self.notifyUser(ustr(e), title=_("Requery Failed"), severe=True, exception=e) self.StatusText = ""
def createBody(self): self.Caption = _("This is the second page") lbl = dabo.ui.dLabel(self, Caption=_( """This will demonstrate condtional skipping of pages. If the checkbox below is checked, clicking 'Next' will move to Page 4 instead of Page 3.""")) self.chk = dabo.ui.dCheckBox(self, Caption="Skip?") self.Sizer.append(lbl, alignment="center") self.Sizer.appendSpacer(10) self.Sizer.append(self.chk, alignment="center")