示例#1
0
 def ClearPresets(self):
     dlg = wx.MessageDialog(
         self,
         _('This will delete all manually defined presets. Continue?'),
         _('Warning'), wx.YES_NO)
     ID = dlg.ShowModal()
     if ID == wx.ID_YES:
         #~ for lowername in self.presetDict.keys():
         #~ value = self.overrideDict.get(lowername)
         #~ if value is None:
         #~ value = self.filterDict[lowername]
         #~ name, args, ftype = value
         #~ newName = name+' '
         #~ adjustedName = name+' '
         #~ if lowername in self.overrideDict:
         #~ adjustedName += '*'
         #~ newName += '*'
         #~ if lowername in self.presetDict:
         #~ adjustedName += '~'
         #~ if newName != adjustedName:
         #~ for index in xrange(self.notebook.GetPageCount()):
         #~ panel = self.notebook.GetPage(index)
         #~ if panel.functiontype == ftype:
         #~ listbox = panel.listbox
         #~ foundindex = listbox.FindString(adjustedName)
         #~ if foundindex != wx.NOT_FOUND:
         #~ listbox.SetString(foundindex, newName)
         #~ break
         self.presetDict = {}
         self.RefreshListNames()
     dlg.Destroy()
示例#2
0
 def fieldInfo(self):
     return (
         ('label', _('Slider label:')),
         ('min', _('Min value:')),
         ('max', _('Max value:')),
         ('val', _('Initial value:')),
     )
示例#3
0
 def __init__(self, parent, labels, initialValueText=''):
     wx.Dialog.__init__(self, None, wx.ID_ANY, _('Define user slider'))
     self.parent = parent
     # Entry fields
     gridSizer = wx.FlexGridSizer(cols=2, hgap=10, vgap=5)
     gridSizer.AddGrowableCol(1)
     self.ctrlDict = {}
     for eachKey, eachLabel in self.fieldInfo():
         textCtrl = wx.TextCtrl(self,
                                validator=UserSliderValidator(
                                    self.ctrlDict, labels))
         staticText = wx.StaticText(self, wx.ID_ANY, eachLabel)
         gridSizer.Add(staticText, 0,
                       wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
         gridSizer.Add(textCtrl, 0, wx.EXPAND)
         self.ctrlDict[eachKey] = textCtrl
     if initialValueText:
         self.ctrlDict['val'].SetValue(initialValueText)
     # Standard buttons
     okay = wx.Button(self, wx.ID_OK, _('OK'))
     okay.SetDefault()
     cancel = wx.Button(self, wx.ID_CANCEL, _('Cancel'))
     btns = wx.StdDialogButtonSizer()
     btns.AddButton(okay)
     btns.AddButton(cancel)
     btns.Realize()
     # Set the sizer
     sizer = wx.BoxSizer(wx.VERTICAL)
     sizer.Add(gridSizer, 0, wx.EXPAND | wx.ALL, 20)
     sizer.Add(btns, 0, wx.EXPAND | wx.ALL, 5)
     self.SetSizer(sizer)
     sizer.Fit(self)
示例#4
0
 def fieldInfo(self):
     return (
         ('label', _('Slider label:')),
         ('min', _('Min value:')),
         ('max', _('Max value:')),
         ('val', _('Initial value:')),
     )
示例#5
0
 def __init__(self, parent, labels, initialValueText=''):
     wx.Dialog.__init__(self, None, wx.ID_ANY, _('Define user slider'))
     self.parent = parent
     # Entry fields
     gridSizer = wx.FlexGridSizer(cols=2, hgap=10, vgap=5)
     gridSizer.AddGrowableCol(1)
     self.ctrlDict = {}
     for eachKey, eachLabel in self.fieldInfo():
         textCtrl = wx.TextCtrl(self, validator=UserSliderValidator(self.ctrlDict, labels))
         staticText = wx.StaticText(self, wx.ID_ANY, eachLabel)
         gridSizer.Add(staticText, 0, wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL)
         gridSizer.Add(textCtrl, 0, wx.EXPAND)
         self.ctrlDict[eachKey] = textCtrl
     if initialValueText:
         self.ctrlDict['val'].SetValue(initialValueText)
     # Standard buttons
     okay  = wx.Button(self, wx.ID_OK, _('OK'))
     okay.SetDefault()
     cancel = wx.Button(self, wx.ID_CANCEL, _('Cancel'))
     btns = wx.StdDialogButtonSizer()
     btns.AddButton(okay)
     btns.AddButton(cancel)
     btns.Realize()
     # Set the sizer
     sizer = wx.BoxSizer(wx.VERTICAL)
     sizer.Add(gridSizer, 0, wx.EXPAND|wx.ALL, 20)
     sizer.Add(btns, 0, wx.EXPAND|wx.ALL, 5)
     self.SetSizer(sizer)
     sizer.Fit(self)
示例#6
0
 def BindShortcuts(self):
     menuInfo = (
         (_('Insert frame #'), self.idInsertFrame),
         (_('Save script'), wx.ID_SAVE),
         (_('Toggle scrap window'), self.idToggleScrapWindow),
     )
     menu = self.contextMenu
     counter = 0
     accList = []
     for itemName, shortcut, id in self.parent.options['shortcuts']:
         for label, id in menuInfo:
             if itemName.endswith(label):
                 counter += 1
                 accel = wx.GetAccelFromString('\t' + shortcut)
                 if accel and accel.IsOk():
                     accList.append(
                         (accel.GetFlags(), accel.GetKeyCode(), id))
                 menuItem = menu.FindItemById(id)
                 label = '%s\t%s' % (menuItem.GetItemLabelText(), shortcut)
                 menuItem.SetItemLabel(label)
                 break
         if counter == len(menuInfo):
             break
     accTable = wx.AcceleratorTable(accList)
     self.textCtrl.SetAcceleratorTable(accTable)
示例#7
0
 def OnSave(self, event):
     filefilter = (_('Text document') + ' (*.txt)|*.txt|' + _('All files') +
                   ' (*.*)|*.*')
     initialdir = self.parent.GetProposedPath(only='dir')
     dlg = wx.FileDialog(self, _('Save scrap text'), initialdir, '',
                         filefilter, wx.SAVE | wx.OVERWRITE_PROMPT)
     ID = dlg.ShowModal()
     if ID == wx.ID_OK:
         filename = dlg.GetPath()
         self.textCtrl.SaveFile(filename)
         self.parent.options['recentdir'] = os.path.dirname(filename)
     dlg.Destroy()
示例#8
0
 def OnSave(self, event):
     filefilter = (_('Text document') + ' (*.txt)|*.txt|' +
                   _('All files') + ' (*.*)|*.*')
     initialdir = self.parent.GetProposedPath(only='dir')
     dlg = wx.FileDialog(self,_('Save scrap text'),
         initialdir, '', filefilter, wx.SAVE | wx.OVERWRITE_PROMPT)
     ID = dlg.ShowModal()
     if ID == wx.ID_OK:
         filename = dlg.GetPath()
         self.textCtrl.SaveFile(filename)
         self.parent.options['recentdir'] = os.path.dirname(filename)
     dlg.Destroy()
示例#9
0
 def ExportCustomizations(self):
     if len(self.overrideDict) == 0:
         wx.MessageBox(_('No customizations to export!'), _('Error'), style=wx.OK|wx.ICON_ERROR)
         return
     title = _('Save filter customizations')
     initial_dir = self.GetParent().programdir
     filefilter = _('Customization file') + ' (*.txt)|*.txt|' + _('All files') + ' (*.*)|*.*'
     dlg = wx.FileDialog(self, title, initial_dir, '', filefilter, wx.SAVE|wx.OVERWRITE_PROMPT)
     ID = dlg.ShowModal()
     if ID == wx.ID_OK:
         filename = dlg.GetPath()
         self.ExportFilterData(self.overrideDict, filename)
     dlg.Destroy()
示例#10
0
 def OnButtonOK(self, event):
     self.dlgDataDict = {}
     # Build the dictionnary from the checked filters
     for i, name in enumerate(self.names):
         if self.checkListBox.IsChecked(i):
             calltip = self.calltipDict.get(name, '')
             preset = self.presetDict.get(name, '')
             docpath = self.docpathDict.get(name, '')
             ftype = self.functiontypeDict.get(name, '')
             self.dlgDataDict[name] = (calltip, preset, docpath, ftype)
     if not self.dlgDataDict:
         wx.MessageBox(_('You must select at least one filter!'), _('Warning'))
         return
     event.Skip()
示例#11
0
 def OnFilterInfoDialogButtonOK(event):
     newName = textCtrl0.GetValue()
     enteredName = dlg.enteredName
     if enteredName is None:
         lowername = newName.lower()
         if lowername in self.overrideDict or lowername in self.filterDict:
             wx.MessageBox(_('Filter name already exists!'),
                           _('Error'),
                           style=wx.OK | wx.ICON_ERROR)
             textCtrl0.SetFocus()
             return
         if not newName or newName[0].isdigit() or re.findall(
                 '\W', newName):
             wx.MessageBox(_('Invalid filter name!'),
                           _('Error'),
                           style=wx.OK | wx.ICON_ERROR)
             textCtrl0.SetFocus()
             return
     elif newName.lower() != enteredName.lower():
         wx.MessageBox(_('Renaming not allowed!'),
                       _('Error'),
                       style=wx.OK | wx.ICON_ERROR)
         textCtrl0.SetFocus()
         return
     if dlg.typeBox.GetCurrentSelection() == 2 and newName.count(
             '_') == 0:
         wx.MessageBox(_(
             'You must use dllname_function naming format for plugins!'
         ),
                       _('Error'),
                       style=wx.OK | wx.ICON_ERROR)
         textCtrl0.SetFocus()
         return
     event.Skip()
示例#12
0
 def OnButtonOK(self, event):
     self.dlgDataDict = {}
     # Build the dictionnary from the checked filters
     for i, name in enumerate(self.names):
         if self.checkListBox.IsChecked(i):
             calltip = self.calltipDict.get(name, '')
             preset = self.presetDict.get(name, '')
             docpath = self.docpathDict.get(name, '')
             ftype = self.functiontypeDict.get(name, '')
             self.dlgDataDict[name] = (calltip, preset, docpath, ftype)
     if not self.dlgDataDict:
         wx.MessageBox(_('You must select at least one filter!'),
                       _('Warning'))
         return
     event.Skip()
示例#13
0
 def OnContextMenu(self, event):
     win = event.GetEventObject()
     pos = win.ScreenToClient(event.GetPosition())
     try:
         win.PopupMenu(win.contextMenu, pos)
     except AttributeError:
         print>>sys.stderr, _('Error: no contextMenu variable defined for window')
示例#14
0
 def __init__(self, parent, title=_('Scrap Window'), pos=wx.DefaultPosition, size=(250,250)):
     style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER
     wx.Dialog.__init__(self, parent, wx.ID_ANY, title, pos, size, style=style)
     self.parent = parent
     # Create the stc control
     self.textCtrl = self.createTextCtrl()
     self.Style()
     self.textCtrl.nInserted = 0
     # Define keyboard shortcuts
     #~ self.BindShortcuts()
     # Add the text from the previous session
     txt, anchor, pos = self.parent.options['scraptext']
     self.textCtrl.SetText(txt)
     self.textCtrl.SetAnchor(anchor)
     self.textCtrl.SetCurrentPos(pos)
     self.textCtrl.EnsureCaretVisible()
     self.textCtrl.EmptyUndoBuffer()
     # Set the width for the horizontal scrollbar
     maxWidth = 50
     if wx.VERSION > (2, 9):
         self.textCtrl.SetScrollWidth(maxWidth)
         self.textCtrl.SetScrollWidthTracking(True)
     else:
         for line in txt.split('\n'):
             width = self.textCtrl.TextWidth(stc.STC_STYLE_DEFAULT, line)
             if width > maxWidth:
                 maxWidth = width
         self.textCtrl.SetScrollWidth(maxWidth)
     # Event binding
     self.Bind(wx.EVT_CLOSE, self.OnClose)
     # Misc
     sizer = wx.BoxSizer()
     sizer.Add(self.textCtrl, 1, wx.EXPAND)
     self.SetSizerAndFit(sizer)
     self.neverShown = True
示例#15
0
 def ClearPresets(self):
     dlg = wx.MessageDialog(self, _('This will delete all manually defined presets. Continue?'), _('Warning'), wx.YES_NO)
     ID = dlg.ShowModal()
     if ID == wx.ID_YES:
         #~ for lowername in self.presetDict.keys():
             #~ value = self.overrideDict.get(lowername)
             #~ if value is None:
                 #~ value = self.filterDict[lowername]
             #~ name, args, ftype = value
             #~ newName = name+' '
             #~ adjustedName = name+' '
             #~ if lowername in self.overrideDict:
                 #~ adjustedName += '*'
                 #~ newName += '*'
             #~ if lowername in self.presetDict:
                 #~ adjustedName += '~'
             #~ if newName != adjustedName:
                 #~ for index in xrange(self.notebook.GetPageCount()):
                     #~ panel = self.notebook.GetPage(index)
                     #~ if panel.functiontype == ftype:
                         #~ listbox = panel.listbox
                         #~ foundindex = listbox.FindString(adjustedName)
                         #~ if foundindex != wx.NOT_FOUND:
                             #~ listbox.SetString(foundindex, newName)
                         #~ break
         self.presetDict = {}
         self.RefreshListNames()
     dlg.Destroy()
示例#16
0
 def ClearCustomizations(self):
     dlg = wx.MessageDialog(self, _('This will delete all filter customizations. Continue?'), _('Warning'), wx.YES_NO)
     ID = dlg.ShowModal()
     if ID == wx.ID_YES:
         #~ for lowername, (name, args, ftype) in self.overrideDict.items():
             #~ originalName = self.filterDict.get(lowername, [name])[0]
             #~ newName = originalName+' '
             #~ adjustedName = name+' '
             #~ if lowername in self.overrideDict:
                 #~ adjustedName += '*'
             #~ if lowername in self.presetDict:
                 #~ adjustedName += '~'
                 #~ newName += '~'
             #~ if newName != adjustedName:
                 #~ for index in xrange(self.notebook.GetPageCount()):
                     #~ panel = self.notebook.GetPage(index)
                     #~ if panel.functiontype == ftype:
                         #~ listbox = panel.listbox
                         #~ foundindex = listbox.FindString(adjustedName)
                         #~ if foundindex != wx.NOT_FOUND:
                             #~ listbox.SetString(foundindex, newName)
                         #~ break
         for lowername, (name, args, ftype) in self.overrideDict.iteritems():
             if ftype == 2 and lowername not in self.filterDict:
                 shortname = self.parent.GetPluginFunctionShortName(lowername)
                 if len(self.shortnamesDict[shortname]) == 1:
                     del self.shortnamesDict[shortname]
                 else:
                     self.shortnamesDict[shortname].remove(lowername)
         self.overrideDict = {}
         self.RefreshListNames()
     dlg.Destroy()
示例#17
0
 def __init__(self, parent, filterDict, overrideDict, avsfilterdict,
                    presetDict, removedSet, pluginDict, shortnamesDict,
                    installed_plugins_filternames,
                    installed_avsi_filternames, functionName=None,
                    functionArgs=None, CreateDefaultPreset=None,
                    ExportFilterData=None, nag=True):
     wx.Dialog.__init__(
         self, parent, wx.ID_ANY,
         _('Add or override AviSynth functions in the database'),
         size=(500, 300), style=wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER
     )
     self.parent = parent
     self.filterDict = filterDict.copy()
     self.overrideDict = overrideDict.copy()
     self.avsfilterdict = avsfilterdict.copy()
     self.presetDict = presetDict.copy()
     self.removedSet = removedSet.copy()
     self.pluginDict = pluginDict.copy()
     self.shortnamesDict = shortnamesDict.copy()
     self.installed_plugins_filternames = installed_plugins_filternames
     self.installed_avsi_filternames = installed_avsi_filternames
     self.CreateDefaultPreset = CreateDefaultPreset
     self.ExportFilterData = ExportFilterData
     self.nag = nag
     self.CreateWindowElements()
     self.CreateFilterInfoDialog()
     if functionName is not None:
         wx.FutureCall(100, self.HighlightFunction, functionName, functionArgs)
示例#18
0
 def OnContextMenu(self, event):
     win = event.GetEventObject()
     pos = win.ScreenToClient(event.GetPosition())
     try:
         win.PopupMenu(win.contextMenu, pos)
     except AttributeError:
         print >> sys.stderr, _(
             'Error: no contextMenu variable defined for window')
示例#19
0
 def ExportCustomizations(self):
     if len(self.overrideDict) == 0:
         wx.MessageBox(_('No customizations to export!'),
                       _('Error'),
                       style=wx.OK | wx.ICON_ERROR)
         return
     title = _('Save filter customizations')
     initial_dir = self.GetParent().programdir
     filefilter = _('Customization file') + ' (*.txt)|*.txt|' + _(
         'All files') + ' (*.*)|*.*'
     dlg = wx.FileDialog(self, title, initial_dir, '', filefilter,
                         wx.SAVE | wx.OVERWRITE_PROMPT)
     ID = dlg.ShowModal()
     if ID == wx.ID_OK:
         filename = dlg.GetPath()
         self.ExportFilterData(self.overrideDict, filename)
     dlg.Destroy()
示例#20
0
 def ShowWarning(self, textCtrl, message):
     color = textCtrl.GetBackgroundColour()
     textCtrl.SetBackgroundColour('pink')
     textCtrl.Refresh()
     wx.MessageBox(message, _('Error'), style=wx.OK|wx.ICON_ERROR)
     textCtrl.SetBackgroundColour(color)
     textCtrl.SetSelection(-1,-1)
     textCtrl.SetFocus()
     textCtrl.Refresh()
示例#21
0
 def ShowWarning(self, textCtrl, message):
     color = textCtrl.GetBackgroundColour()
     textCtrl.SetBackgroundColour('pink')
     textCtrl.Refresh()
     wx.MessageBox(message, _('Error'), style=wx.OK | wx.ICON_ERROR)
     textCtrl.SetBackgroundColour(color)
     textCtrl.SetSelection(-1, -1)
     textCtrl.SetFocus()
     textCtrl.Refresh()
示例#22
0
 def DeleteFunction(self):
     panel = self.notebook.GetCurrentPage()
     listbox = panel.listbox
     index = listbox.GetSelection()
     if index == wx.NOT_FOUND:
         return
     complete_string = listbox.GetString(index)
     name = complete_string.split()[0]
     lowername = name.lower()
     added_by_user = lowername not in self.filterDict
     modified = lowername != complete_string.rstrip().lower()
     if not added_by_user and not modified:
         return
     delete = not self.nag
     if self.nag:
         if added_by_user:
             message = _('Do you really want to delete this custom filter?')
         else:
             message = _('Do you really want to reset this filter?')
         dlg = wx.MessageDialog(self, message, _('Warning'), wx.YES_NO)
         ID = dlg.ShowModal()
         if ID == wx.ID_YES:
             delete = True
         dlg.Destroy()
     if delete:
         if lowername in self.overrideDict:
             del self.overrideDict[lowername]
         if lowername in self.presetDict:
             del self.presetDict[lowername]
         if added_by_user:
             if panel.functiontype == 2:
                 del self.pluginDict[lowername]
                 shortname = self.parent.GetPluginFunctionShortName(
                     lowername)
                 if len(self.shortnamesDict[shortname]) == 1:
                     del self.shortnamesDict[shortname]
                 else:
                     self.shortnamesDict[shortname].remove(lowername)
             if lowername in self.removedSet:
                 self.removedSet.remove(lowername)
             listbox.Delete(index)
         else:
             listbox.SetString(index, name)
示例#23
0
 def DeleteFunction(self):
     panel = self.notebook.GetCurrentPage()
     listbox = panel.listbox
     index = listbox.GetSelection()
     if index == wx.NOT_FOUND:
         return
     complete_string = listbox.GetString(index)
     name = complete_string.split()[0]
     lowername = name.lower()
     added_by_user = lowername not in self.filterDict
     modified = lowername != complete_string.rstrip().lower()
     if not added_by_user and not modified:
         return
     delete = not self.nag
     if self.nag:
         if added_by_user:
             message = _('Do you really want to delete this custom filter?')
         else:
             message = _('Do you really want to reset this filter?')
         dlg = wx.MessageDialog(self, message, _('Warning'), wx.YES_NO)
         ID = dlg.ShowModal()
         if ID == wx.ID_YES:
             delete = True
         dlg.Destroy()
     if delete:
         if lowername in self.overrideDict:
             del self.overrideDict[lowername]
         if lowername in self.presetDict:
             del self.presetDict[lowername]
         if added_by_user:
             if panel.functiontype == 2:
                 del self.pluginDict[lowername]
                 shortname = self.parent.GetPluginFunctionShortName(lowername)
                 if len(self.shortnamesDict[shortname]) == 1:
                     del self.shortnamesDict[shortname]
                 else:
                     self.shortnamesDict[shortname].remove(lowername)
             if lowername in self.removedSet:
                 self.removedSet.remove(lowername)
             listbox.Delete(index)
         else:
             listbox.SetString(index, name)
示例#24
0
 def OnArgsEditSliders(event):
     name = textCtrl0.GetValue()
     dlg2 = AvsFilterAutoSliderInfo(dlg,
                                    self.GetParent(),
                                    name,
                                    textCtrl2.GetValue(),
                                    title=_('Slider information'))
     ID = dlg2.ShowModal()
     if ID == wx.ID_OK:
         textCtrl2.SetValue(dlg2.GetNewFilterInfo())
     dlg2.Destroy()
示例#25
0
    def ImportFromFiles(self, wiki=False):
        filenames, filterInfo, unrecognized = [], [], []
        if wiki:
            filenames = (self.GetParent().filterdbremote_plugins,
                         self.GetParent().filterdbremote_scripts)
        else:
            title = _(
                'Open Customization files, Avisynth scripts or Avsp options files'
            )
            initial_dir = self.GetParent().ExpandVars(
                self.GetParent().options['pluginsdir'])
            filefilter = (_('All supported') +
                          '|*.txt;*.md;*.avsi;*.avs;*.dat|' +
                          _('Customization file') +
                          ' (*.txt, *.md)|*.txt;*.md|' + _('AviSynth script') +
                          ' (*.avs, *.avsi)|*.avs;*.avsi|' + _('AvsP data') +
                          ' (*.dat)|*.dat|' + _('All files') + ' (*.*)|*.*')
            dlg = wx.FileDialog(self, title, initial_dir, '', filefilter,
                                wx.OPEN | wx.MULTIPLE | wx.FILE_MUST_EXIST)
            ID = dlg.ShowModal()
            if ID == wx.ID_OK:
                filenames = dlg.GetPaths()
            dlg.Destroy()
            if not filenames:
                return

        for filename in filenames:
            ext = os.path.splitext(filename)[1]
            try:
                if ext in ['.avs', '.avsi']:
                    info = self.ParseAvisynthScript(filename)
                elif ext in ['.txt', '.md']:
                    info = self.ParseCustomizations(filename)
                elif ext == '.dat':
                    if filename.startswith('http'):
                        f = urllib2.urlopen(filename)
                    else:
                        f = open(filename, 'rb')
                    data = cPickle.load(f)
                    f.close()
                    info = []
                    for filtername, filterargs, ftype in data[
                            'filteroverrides'].values():
                        info.append((filename, filtername, filterargs, ftype))
                else:
                    info = None
            except (urllib2.URLError, urllib2.HTTPError), err:
                wx.MessageBox(u'\n\n'.join(
                    (os.path.basename(filename), unicode(err))),
                              _('Error'),
                              style=wx.OK | wx.ICON_ERROR)
                continue
            except:
示例#26
0
 def ShowWarning(self, textCtrl, message, comboBox=False):
     color = textCtrl.GetBackgroundColour()
     textCtrl.SetBackgroundColour('pink')
     textCtrl.Refresh()
     wx.MessageBox(message, _('Error'), style=wx.OK|wx.ICON_ERROR)
     textCtrl.SetBackgroundColour(color)
     textCtrl.Refresh()
     textCtrl.GetParent().Refresh()
     if comboBox:
         textCtrl.SetMark(-1,-1)
     else:
         textCtrl.SetSelection(-1,-1)
     textCtrl.SetFocus()
     textCtrl.Refresh()
示例#27
0
 def ShowWarning(self, textCtrl, message, comboBox=False):
     color = textCtrl.GetBackgroundColour()
     textCtrl.SetBackgroundColour('pink')
     textCtrl.Refresh()
     wx.MessageBox(message, _('Error'), style=wx.OK | wx.ICON_ERROR)
     textCtrl.SetBackgroundColour(color)
     textCtrl.Refresh()
     textCtrl.GetParent().Refresh()
     if comboBox:
         textCtrl.SetMark(-1, -1)
     else:
         textCtrl.SetSelection(-1, -1)
     textCtrl.SetFocus()
     textCtrl.Refresh()
示例#28
0
 def ClearCustomizations(self):
     dlg = wx.MessageDialog(
         self, _('This will delete all filter customizations. Continue?'),
         _('Warning'), wx.YES_NO)
     ID = dlg.ShowModal()
     if ID == wx.ID_YES:
         #~ for lowername, (name, args, ftype) in self.overrideDict.items():
         #~ originalName = self.filterDict.get(lowername, [name])[0]
         #~ newName = originalName+' '
         #~ adjustedName = name+' '
         #~ if lowername in self.overrideDict:
         #~ adjustedName += '*'
         #~ if lowername in self.presetDict:
         #~ adjustedName += '~'
         #~ newName += '~'
         #~ if newName != adjustedName:
         #~ for index in xrange(self.notebook.GetPageCount()):
         #~ panel = self.notebook.GetPage(index)
         #~ if panel.functiontype == ftype:
         #~ listbox = panel.listbox
         #~ foundindex = listbox.FindString(adjustedName)
         #~ if foundindex != wx.NOT_FOUND:
         #~ listbox.SetString(foundindex, newName)
         #~ break
         for lowername, (name, args,
                         ftype) in self.overrideDict.iteritems():
             if ftype == 2 and lowername not in self.filterDict:
                 shortname = self.parent.GetPluginFunctionShortName(
                     lowername)
                 if len(self.shortnamesDict[shortname]) == 1:
                     del self.shortnamesDict[shortname]
                 else:
                     self.shortnamesDict[shortname].remove(lowername)
         self.overrideDict = {}
         self.RefreshListNames()
     dlg.Destroy()
示例#29
0
 def BindShortcuts(self):
     menuInfo = (
         (_('Insert frame #'), self.idInsertFrame),
         (_('Save script'), wx.ID_SAVE),
         (_('Toggle scrap window'), self.idToggleScrapWindow),
     )
     menu = self.contextMenu
     counter = 0
     accList = []
     for itemName, shortcut, id in self.parent.options['shortcuts']:
         for label, id in menuInfo:
             if itemName.endswith(label):
                 counter += 1
                 accel = wx.GetAccelFromString('\t'+shortcut)
                 if accel and accel.IsOk():
                     accList.append((accel.GetFlags(), accel.GetKeyCode(), id))
                 menuItem = menu.FindItemById(id)
                 label = '%s\t%s' % (menuItem.GetItemLabelText(), shortcut)
                 menuItem.SetItemLabel(label)
                 break
         if counter == len(menuInfo):
             break
     accTable = wx.AcceleratorTable(accList)
     self.textCtrl.SetAcceleratorTable(accTable)
示例#30
0
 def __init__(self,
              parent,
              title=_('Scrap Window'),
              pos=wx.DefaultPosition,
              size=(250, 250)):
     style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER
     wx.Dialog.__init__(self,
                        parent,
                        wx.ID_ANY,
                        title,
                        pos,
                        size,
                        style=style)
     self.parent = parent
     # Create the stc control
     self.textCtrl = self.createTextCtrl()
     self.Style()
     self.textCtrl.nInserted = 0
     # Define keyboard shortcuts
     #~ self.BindShortcuts()
     # Add the text from the previous session
     txt, anchor, pos = self.parent.options['scraptext']
     self.textCtrl.SetText(txt)
     self.textCtrl.SetAnchor(anchor)
     self.textCtrl.SetCurrentPos(pos)
     self.textCtrl.EnsureCaretVisible()
     self.textCtrl.EmptyUndoBuffer()
     # Set the width for the horizontal scrollbar
     maxWidth = 50
     if wx.VERSION > (2, 9):
         self.textCtrl.SetScrollWidth(maxWidth)
         self.textCtrl.SetScrollWidthTracking(True)
     else:
         for line in txt.split('\n'):
             width = self.textCtrl.TextWidth(stc.STC_STYLE_DEFAULT, line)
             if width > maxWidth:
                 maxWidth = width
         self.textCtrl.SetScrollWidth(maxWidth)
     # Event binding
     self.Bind(wx.EVT_CLOSE, self.OnClose)
     # Misc
     sizer = wx.BoxSizer()
     sizer.Add(self.textCtrl, 1, wx.EXPAND)
     self.SetSizerAndFit(sizer)
     self.neverShown = True
示例#31
0
    def CreatePluginsContextMenu(self):
        """Chose between long and short names"""

        def OnPluginsContextMenu(event):
            name = listbox.GetString(listbox.GetSelection()).split()[0].lower()
            item = menu.FindItemByPosition((self.pluginDict[name] + 2) % 3)
            item.Check()
            listbox.PopupMenu(menu)

        def OnContextMenuItem(event):
            id = event.GetId()
            if id in [idLong, idShort, idBoth]:
                if id == idLong:
                    value = 1
                elif id == idShort:
                    value = 2
                elif id == idBoth:
                    value = 0
                name = listbox.GetString(listbox.GetSelection())
                self.pluginDict[name.split()[0].lower()] = value
            else:
                if id == idLongOnly:
                    value = 1
                elif id == idShortOnly:
                    value = 2
                elif id == idAll:
                    value = 0
                for name in self.pluginDict:
                    self.pluginDict[name] = value

        listbox = self.notebook.GetPage(1).listbox
        listbox.Bind(wx.EVT_CONTEXT_MENU, OnPluginsContextMenu)
        idLong = wx.NewId()
        idShort = wx.NewId()
        idBoth = wx.NewId()
        idLongOnly = wx.NewId()
        idShortOnly = wx.NewId()
        idAll = wx.NewId()
        menu = wx.Menu()
        menu.AppendRadioItem(idLong, _('Long name'))
        menu.AppendRadioItem(idShort, _('Short name'))
        menu.AppendRadioItem(idBoth, _('Both'))
        menu.AppendSeparator()
        menu.Append(idLongOnly, _('Only long names'))
        menu.Append(idShortOnly, _('Only short names'))
        menu.Append(idAll, _('All names'))
        listbox.Bind(wx.EVT_MENU, OnContextMenuItem, id=idLong)
        listbox.Bind(wx.EVT_MENU, OnContextMenuItem, id=idShort)
        listbox.Bind(wx.EVT_MENU, OnContextMenuItem, id=idBoth)
        listbox.Bind(wx.EVT_MENU, OnContextMenuItem, id=idLongOnly)
        listbox.Bind(wx.EVT_MENU, OnContextMenuItem, id=idShortOnly)
        listbox.Bind(wx.EVT_MENU, OnContextMenuItem, id=idAll)
示例#32
0
 def SetRange(self, minValue, maxValue, refresh=True):
     if minValue >= maxValue:
         if minValue == 0 and (maxValue == -1 or maxValue ==0):
             maxValue = 1
         else:
             print>>sys.stderr, _('Error: minValue must be less than maxValue')
             return
     self.minValue = minValue
     self.maxValue = maxValue
     self.selections = self._createSelections()
     if refresh:
         if self.IsDoubleBuffered():
             dc = wx.ClientDC(self)
         else:
             dc = wx.BufferedDC(wx.ClientDC(self))
         dc.Clear()
         self._PaintSlider(dc)
     return True
示例#33
0
    def ImportFromFiles(self, wiki=False):
        filenames, filterInfo, unrecognized = [], [], []
        if wiki:
            filenames = (self.GetParent().filterdbremote_plugins,
                         self.GetParent().filterdbremote_scripts)
        else:
            title = _('Open Customization files, Avisynth scripts or Avsp options files')
            initial_dir = self.GetParent().ExpandVars(self.GetParent().options['pluginsdir'])
            filefilter = (_('All supported') + '|*.txt;*.md;*.avsi;*.avs;*.dat|' +
                          _('Customization file') + ' (*.txt, *.md)|*.txt;*.md|' +
                          _('AviSynth script') + ' (*.avs, *.avsi)|*.avs;*.avsi|' +
                          _('AvsP data') + ' (*.dat)|*.dat|' +
                          _('All files') + ' (*.*)|*.*')
            dlg = wx.FileDialog(self, title, initial_dir, '', filefilter,
                                wx.OPEN|wx.MULTIPLE|wx.FILE_MUST_EXIST)
            ID = dlg.ShowModal()
            if ID == wx.ID_OK:
                filenames = dlg.GetPaths()
            dlg.Destroy()
            if not filenames:
                return

        for filename in filenames:
            ext = os.path.splitext(filename)[1]
            try:
                if ext in ['.avs', '.avsi']:
                    info = self.ParseAvisynthScript(filename)
                elif ext in ['.txt', '.md']:
                    info = self.ParseCustomizations(filename)
                elif ext == '.dat':
                    if filename.startswith('http'):
                        f = urllib2.urlopen(filename)
                    else:
                        f = open(filename, 'rb')
                    data = cPickle.load(f)
                    f.close()
                    info = []
                    for filtername, filterargs, ftype in data['filteroverrides'].values():
                        info.append((filename, filtername, filterargs, ftype))
                else:
                    info = None
            except (urllib2.URLError, urllib2.HTTPError), err:
                wx.MessageBox(u'\n\n'.join((os.path.basename(filename), unicode(err))),
                              _('Error'), style=wx.OK|wx.ICON_ERROR)
                continue
            except:
示例#34
0
    def CreatePluginsContextMenu(self):
        """Chose between long and short names"""
        def OnPluginsContextMenu(event):
            name = listbox.GetString(listbox.GetSelection()).split()[0].lower()
            item = menu.FindItemByPosition((self.pluginDict[name] + 2) % 3)
            item.Check()
            listbox.PopupMenu(menu)

        def OnContextMenuItem(event):
            id = event.GetId()
            if id in [idLong, idShort, idBoth]:
                if id == idLong:
                    value = 1
                elif id == idShort:
                    value = 2
                elif id == idBoth:
                    value = 0
                name = listbox.GetString(listbox.GetSelection())
                self.pluginDict[name.split()[0].lower()] = value
            else:
                if id == idLongOnly:
                    value = 1
                elif id == idShortOnly:
                    value = 2
                elif id == idAll:
                    value = 0
                for name in self.pluginDict:
                    self.pluginDict[name] = value

        listbox = self.notebook.GetPage(1).listbox
        listbox.Bind(wx.EVT_CONTEXT_MENU, OnPluginsContextMenu)
        idLong = wx.NewId()
        idShort = wx.NewId()
        idBoth = wx.NewId()
        idLongOnly = wx.NewId()
        idShortOnly = wx.NewId()
        idAll = wx.NewId()
        menu = wx.Menu()
        menu.AppendRadioItem(idLong, _('Long name'))
        menu.AppendRadioItem(idShort, _('Short name'))
        menu.AppendRadioItem(idBoth, _('Both'))
        menu.AppendSeparator()
        menu.Append(idLongOnly, _('Only long names'))
        menu.Append(idShortOnly, _('Only short names'))
        menu.Append(idAll, _('All names'))
        listbox.Bind(wx.EVT_MENU, OnContextMenuItem, id=idLong)
        listbox.Bind(wx.EVT_MENU, OnContextMenuItem, id=idShort)
        listbox.Bind(wx.EVT_MENU, OnContextMenuItem, id=idBoth)
        listbox.Bind(wx.EVT_MENU, OnContextMenuItem, id=idLongOnly)
        listbox.Bind(wx.EVT_MENU, OnContextMenuItem, id=idShortOnly)
        listbox.Bind(wx.EVT_MENU, OnContextMenuItem, id=idAll)
示例#35
0
    def _drawPageHeader(self, dc, page):
        """Draw the page header into the DC for printing

        dc: the device context representing the page

        page: page number

        """
        rect = self.GetLogicalPageMarginsRect(self.page_setup_data)
        # Set font for title/page number rendering
        dc.SetFont(self.getHeaderFont())
        dc.SetTextForeground ("black")
        # Title
        if self.title:
            dc.DrawText(self.title, rect[0], rect[1])
        # Page Number
        page_lbl = _("Page: %d") % page
        pg_lbl_w, pg_lbl_h = dc.GetTextExtent(page_lbl)
        dc.DrawText(page_lbl, rect[2] - pg_lbl_w, rect[1])
示例#36
0
 def OnContextMenu(event):
     listbox.Bind(wx.EVT_MENU, OnContextMenuItem, id=idSelectionAll)
     listbox.Bind(wx.EVT_MENU, OnContextMenuItem, id=idAll)
     listbox.Bind(wx.EVT_MENU, OnContextMenuItem, id=idFileAll)
     listbox.Bind(wx.EVT_MENU, OnContextMenuItem, id=idNotCustomizedAll)
     listbox.Bind(wx.EVT_MENU, OnContextMenuItem, id=idSelectionNone)
     listbox.Bind(wx.EVT_MENU, OnContextMenuItem, id=idNone)
     listbox.Bind(wx.EVT_MENU, OnContextMenuItem, id=idFileNone)
     listbox.Bind(wx.EVT_MENU, OnContextMenuItem, id=idCustomizedNone)
     menu = wx.Menu()
     menu.Append(idSelectionAll, _('Check selected'))
     menu.Append(idAll, _('Check all'))
     menu.Append(idFileAll, _('Check all in this file'))
     menu.Append(idNotCustomizedAll, _('Check all not customized'))
     menu.AppendSeparator()
     menu.Append(idSelectionNone, _('Uncheck selected'))
     menu.Append(idNone, _('Uncheck all'))
     menu.Append(idFileNone, _('Uncheck all in this file'))
     menu.Append(idCustomizedNone, _('Uncheck all customized'))
     listbox.PopupMenu(menu)
     menu.Destroy()
示例#37
0
 def SetRange(self, minValue, maxValue, refresh=True):
     if minValue >= maxValue:
         if minValue == 0 and (maxValue == -1 or maxValue == 0):
             maxValue = 1
         else:
             print >> sys.stderr, _(
                 'Error: minValue must be less than maxValue')
             return
     self.minValue = minValue
     self.maxValue = maxValue
     self.selections = self._createSelections()
     if refresh:
         if self.IsDoubleBuffered():
             dc = wx.ClientDC(self)
         else:
             dc = wx.BufferedDC(wx.ClientDC(self))
         dc.Clear()
         self._PaintSlider(dc)
     return True
示例#38
0
    def _drawPageHeader(self, dc, page):
        """Draw the page header into the DC for printing

        dc: the device context representing the page

        page: page number

        """
        rect = self.GetLogicalPageMarginsRect(self.page_setup_data)
        # Set font for title/page number rendering
        dc.SetFont(self.getHeaderFont())
        dc.SetTextForeground("black")
        # Title
        if self.title:
            dc.DrawText(self.title, rect[0], rect[1])
        # Page Number
        page_lbl = _("Page: %d") % page
        pg_lbl_w, pg_lbl_h = dc.GetTextExtent(page_lbl)
        dc.DrawText(page_lbl, rect[2] - pg_lbl_w, rect[1])
示例#39
0
 def OnContextMenu(event):
     listbox.Bind(wx.EVT_MENU, OnContextMenuItem, id=idSelectionAll)
     listbox.Bind(wx.EVT_MENU, OnContextMenuItem, id=idAll)
     listbox.Bind(wx.EVT_MENU, OnContextMenuItem, id=idFileAll)
     listbox.Bind(wx.EVT_MENU, OnContextMenuItem, id=idNotCustomizedAll)
     listbox.Bind(wx.EVT_MENU, OnContextMenuItem, id=idSelectionNone)
     listbox.Bind(wx.EVT_MENU, OnContextMenuItem, id=idNone)
     listbox.Bind(wx.EVT_MENU, OnContextMenuItem, id=idFileNone)
     listbox.Bind(wx.EVT_MENU, OnContextMenuItem, id=idCustomizedNone)
     menu = wx.Menu()
     menu.Append(idSelectionAll, _('Check selected'))
     menu.Append(idAll, _('Check all'))
     menu.Append(idFileAll, _('Check all in this file'))
     menu.Append(idNotCustomizedAll, _('Check all not customized'))
     menu.AppendSeparator()
     menu.Append(idSelectionNone, _('Uncheck selected'))
     menu.Append(idNone, _('Uncheck all'))
     menu.Append(idFileNone, _('Uncheck all in this file'))
     menu.Append(idCustomizedNone, _('Uncheck all customized'))
     listbox.PopupMenu(menu)
     menu.Destroy()
示例#40
0
 def __init__(self,
              parent,
              filterDict,
              overrideDict,
              avsfilterdict,
              presetDict,
              removedSet,
              pluginDict,
              shortnamesDict,
              installed_plugins_filternames,
              installed_avsi_filternames,
              functionName=None,
              functionArgs=None,
              CreateDefaultPreset=None,
              ExportFilterData=None,
              nag=True):
     wx.Dialog.__init__(
         self,
         parent,
         wx.ID_ANY,
         _('Add or override AviSynth functions in the database'),
         size=(500, 300),
         style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER)
     self.parent = parent
     self.filterDict = filterDict.copy()
     self.overrideDict = overrideDict.copy()
     self.avsfilterdict = avsfilterdict.copy()
     self.presetDict = presetDict.copy()
     self.removedSet = removedSet.copy()
     self.pluginDict = pluginDict.copy()
     self.shortnamesDict = shortnamesDict.copy()
     self.installed_plugins_filternames = installed_plugins_filternames
     self.installed_avsi_filternames = installed_avsi_filternames
     self.CreateDefaultPreset = CreateDefaultPreset
     self.ExportFilterData = ExportFilterData
     self.nag = nag
     self.CreateWindowElements()
     self.CreateFilterInfoDialog()
     if functionName is not None:
         wx.FutureCall(100, self.HighlightFunction, functionName,
                       functionArgs)
示例#41
0
    def _calculatePageStarts(self, dc):
        """Calculates offsets into the STC for each page

        This pre-calculates the page offsets for each page to support print
        preview being able to seek backwards and forwards.

        """
        if self.header:
            # Set font for title/page number rendering
            dc.SetFont(self.getHeaderFont())
            # Title
            self.header_height = dc.GetTextExtent(self.title)[1]
            # Page Number
            page_lbl = _("Page:")
            self.header_height = 1.5 * max(self.header_height,
                                           dc.GetTextExtent(page_lbl)[1])
        else:
            self.header_height = 0

        self.stc.SetPrintColourMode(self.print_mode)
        edge_mode = self.stc.GetEdgeMode()
        self.stc.SetEdgeMode(wx.stc.STC_EDGE_NONE)
        stc_len = self.stc.GetLength()
        self.start_points = [0]
        rect = self.GetLogicalPageMarginsRect(self.page_setup_data)
        rect[2] -= self.stc.GetMarginWidth(0)
        rect[1] += self.header_height
        rect[3] -= self.header_height
        if self.debuglevel > 0:
            print  "prepare rect: ", rect
        while self.start_points[-1] < stc_len:
            self.start_points.append(self.stc.FormatRange(False,
                                    self.start_points[-1], stc_len,
                                    dc, dc, rect, rect))
            if self.debuglevel > 0:
                if self.start_points[-1] == stc_len:
                    print "prepare printing - reached end of document: %d" % stc_len
                else:
                    print ("prepare printing - page %d first line: %d" % (
                           len(self.start_points), self.start_points[-1]))
        self.stc.SetEdgeMode(edge_mode)
示例#42
0
    def _calculatePageStarts(self, dc):
        """Calculates offsets into the STC for each page

        This pre-calculates the page offsets for each page to support print
        preview being able to seek backwards and forwards.

        """
        if self.header:
            # Set font for title/page number rendering
            dc.SetFont(self.getHeaderFont())
            # Title
            self.header_height = dc.GetTextExtent(self.title)[1]
            # Page Number
            page_lbl = _("Page:")
            self.header_height = 1.5 * max(self.header_height,
                                           dc.GetTextExtent(page_lbl)[1])
        else:
            self.header_height = 0

        self.stc.SetPrintColourMode(self.print_mode)
        edge_mode = self.stc.GetEdgeMode()
        self.stc.SetEdgeMode(wx.stc.STC_EDGE_NONE)
        stc_len = self.stc.GetLength()
        self.start_points = [0]
        rect = self.GetLogicalPageMarginsRect(self.page_setup_data)
        rect[2] -= self.stc.GetMarginWidth(0)
        rect[1] += self.header_height
        rect[3] -= self.header_height
        if self.debuglevel > 0:
            print "prepare rect: ", rect
        while self.start_points[-1] < stc_len:
            self.start_points.append(
                self.stc.FormatRange(False, self.start_points[-1], stc_len, dc,
                                     dc, rect, rect))
            if self.debuglevel > 0:
                if self.start_points[-1] == stc_len:
                    print "prepare printing - reached end of document: %d" % stc_len
                else:
                    print("prepare printing - page %d first line: %d" %
                          (len(self.start_points), self.start_points[-1]))
        self.stc.SetEdgeMode(edge_mode)
示例#43
0
 def OnFilterInfoDialogButtonOK(event):
     newName = textCtrl0.GetValue()
     enteredName = dlg.enteredName
     if enteredName is None:
         lowername = newName.lower()
         if lowername in self.overrideDict or lowername in self.filterDict:
             wx.MessageBox(_('Filter name already exists!'), _('Error'), style=wx.OK|wx.ICON_ERROR)
             textCtrl0.SetFocus()
             return
         if not newName or newName[0].isdigit() or re.findall('\W', newName):
             wx.MessageBox(_('Invalid filter name!'), _('Error'), style=wx.OK|wx.ICON_ERROR)
             textCtrl0.SetFocus()
             return
     elif newName.lower() != enteredName.lower():
         wx.MessageBox(_('Renaming not allowed!'), _('Error'), style=wx.OK|wx.ICON_ERROR)
         textCtrl0.SetFocus()
         return
     if dlg.typeBox.GetCurrentSelection() == 2 and newName.count('_') == 0:
         wx.MessageBox(_('You must use dllname_function naming format for plugins!'),
                       _('Error'), style=wx.OK|wx.ICON_ERROR)
         textCtrl0.SetFocus()
         return
     event.Skip()
示例#44
0
    def __init__(self, parent, infoDict, export=True):
        self.export = export
        if export:
            title = _('Export filter customizations')
        else:
            title = _('Import filter customizations')
        wx.Dialog.__init__(self,
                           parent,
                           wx.ID_ANY,
                           title,
                           size=(500, 300),
                           style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER)
        self.calltipDict = infoDict[0]
        self.presetDict = infoDict[1]
        self.docpathDict = infoDict[2]
        self.functiontypeDict = infoDict[3]

        # Create the list control using the dictionary
        decList = [(s.lower(), s) for s in self.calltipDict.keys()]
        decList.sort()
        self.names = [s[1] for s in decList]
        self.checkListBox = wx.CheckListBox(self,
                                            wx.ID_ANY,
                                            choices=self.names)

        # Create extra control buttons
        def OnButtonSelectAll(event):
            for index in xrange(len(self.names)):
                self.checkListBox.Check(index, True)

        def OnButtonClearAll(event):
            for index in xrange(len(self.names)):
                self.checkListBox.Check(index, False)

        buttonSelectAll = wx.Button(self, wx.ID_ANY, _('Select all'))
        self.Bind(wx.EVT_BUTTON, OnButtonSelectAll, buttonSelectAll)
        buttonClearAll = wx.Button(self, wx.ID_ANY, _('Clear all'))
        self.Bind(wx.EVT_BUTTON, OnButtonClearAll, buttonClearAll)

        if export:
            staticText = wx.StaticText(self, wx.ID_ANY,
                                       _('Select filters to export:'))
            extraItem = (-1, 20)
        else:
            staticText = wx.StaticText(
                self, wx.ID_ANY, _('Select filters to import from the file:'))
            # Import dialog, check all names by default
            for index in xrange(len(self.names)):
                self.checkListBox.Check(index)
            # Extra controls to provide options for import information
            #~ self.checkBoxCalltip = wx.CheckBox(self, wx.ID_ANY, _('Calltips'))
            #~ self.checkBoxPreset = wx.CheckBox(self, wx.ID_ANY, _('Presets'))
            #~ self.checkBoxDocpath = wx.CheckBox(self, wx.ID_ANY, _('Docpaths'))
            #~ self.checkBoxType = wx.CheckBox(self, wx.ID_ANY, _('Filter types'))
            #~ staticBox = wx.StaticBox(self, wx.ID_ANY, _('Import from filters:'))
            #~ staticBoxSizer = wx.StaticBoxSizer(staticBox, wx.HORIZONTAL)
            #~ for item in (self.checkBoxCalltip, self.checkBoxPreset, self.checkBoxDocpath, self.checkBoxType):
            #~ item.SetValue(True)
            #~ staticBoxSizer.Add(item, 0, wx.ALL, 5)
            self.checkBoxOverwriteAll = wx.CheckBox(self, wx.ID_ANY,
                                                    _('Overwrite all data'))
            self.checkBoxOverwriteAll.SetValue(True)
            extraItem = wx.BoxSizer(wx.VERTICAL)
            #~ extraItem.Add(staticBoxSizer, 0, wx.BOTTOM, 10)
            extraItem.Add(self.checkBoxOverwriteAll, 0, wx.LEFT | wx.BOTTOM, 5)

        # Standard buttons
        okay = wx.Button(self, wx.ID_OK, _('OK'))
        self.Bind(wx.EVT_BUTTON, self.OnButtonOK, okay)
        cancel = wx.Button(self, wx.ID_CANCEL, _('Cancel'))
        btns = wx.StdDialogButtonSizer()
        btns.AddButton(okay)
        btns.AddButton(cancel)
        btns.Realize()

        # Size the elements
        buttonSizer = wx.BoxSizer(wx.VERTICAL)
        buttonSizer.Add(buttonSelectAll, 0, wx.ALL, 5)
        buttonSizer.Add(buttonClearAll, 0, wx.ALL, 5)
        listSizer = wx.BoxSizer(wx.HORIZONTAL)
        listSizer.Add(self.checkListBox, 1, wx.EXPAND | wx.ALL, 5)
        listSizer.Add(buttonSizer, 0, wx.ALL, 5)
        dlgSizer = wx.BoxSizer(wx.VERTICAL)
        dlgSizer.Add((-1, 5))
        dlgSizer.Add(staticText, 0, wx.ALL, 5)
        dlgSizer.Add(listSizer, 1, wx.EXPAND | wx.LEFT | wx.RIGHT, 5)
        dlgSizer.Add(extraItem, 0, wx.ALL, 5)
        dlgSizer.Add(btns, 0, wx.EXPAND | wx.ALL, 5)
        self.SetSizer(dlgSizer)
        dlgSizer.SetSizeHints(self)
        # Misc
        okay.SetDefault()
示例#45
0
 def Validate(self, parent):
     textCtrl = self.GetWindow()
     text = textCtrl.GetValue()
     if len(text) == 0:
         self.ShowWarning(textCtrl, _('This field must contain a value!'))
         return False
     elif textCtrl == self.ctrlDict['label']:
         try:
             temp = str(text)
         except UnicodeEncodeError:
             temp = text
         if temp in self.labels:
             self.ShowWarning(textCtrl,
                              _('This slider label already exists!'))
             return False
         if self.getModFromLabel(text) == -1:
             self.ShowWarning(textCtrl,
                              _('Invalid slider label modulo syntax!'))
             return False
         return True
     else:
         try:
             float(text)
         except ValueError:
             self.ShowWarning(textCtrl,
                              _('This field must contain a number!'))
             return False
         try:
             minValue = float(self.ctrlDict['min'].GetValue())
             maxValue = float(self.ctrlDict['max'].GetValue())
             value = float(self.ctrlDict['val'].GetValue())
             # Validate ranges
             if minValue >= maxValue and textCtrl == self.ctrlDict['min']:
                 self.ShowWarning(
                     textCtrl,
                     _('The min value must be less than the max!'))
                 return False
             if value < minValue or value > maxValue and textCtrl == self.ctrlDict[
                     'val']:
                 self.ShowWarning(
                     textCtrl,
                     _('The initial value must be between the min and the max!'
                       ))
                 return False
             # Validate modulo divisibility
             mod = self.getModFromLabel(self.ctrlDict['label'].GetValue())
             if mod == -1:
                 self.ShowWarning(textCtrl,
                                  _('Invalid slider label modulo syntax!'))
                 return False
             if mod is not None:
                 if int(minValue) % mod != 0 and textCtrl == self.ctrlDict[
                         'min']:
                     self.ShowWarning(
                         textCtrl,
                         _('The min value must be a multiple of %(mod)s!') %
                         locals())
                     return False
                 if int(maxValue) % mod != 0 and textCtrl == self.ctrlDict[
                         'max']:
                     self.ShowWarning(
                         textCtrl,
                         _('The max value must be a multiple of %(mod)s!') %
                         locals())
                     return False
                 if int(value) % mod != 0 and textCtrl == self.ctrlDict[
                         'val']:
                     self.ShowWarning(
                         textCtrl,
                         _('The initial value must be a multiple of %(mod)s!'
                           ) % locals())
                     return False
                 if mod > (maxValue - minValue):
                     self.ShowWarning(
                         self.ctrlDict['min'],
                         _('The difference between the min and max must be greater than %(mod)s!'
                           ) % locals())
                     return False
         except ValueError:
             pass
         return True
示例#46
0
    def __init__(self, parent, mainFrame, filterName, filterInfo, title=_('Edit filter database')):
        wx.Dialog.__init__(self, parent, wx.ID_ANY, title, style=wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER)
        self.mainFrame = mainFrame
        self.newFilterInfo = None
        # Filter name label
        filterLabel = wx.StaticText(self, wx.ID_ANY, filterName)
        font = filterLabel.GetFont()
        font.SetPointSize(10)
        font.SetWeight(wx.FONTWEIGHT_BOLD)
        filterLabel.SetFont(font)
        # Arguments
        argWindow = wx.ScrolledWindow(self, wx.ID_ANY, style=wx.TAB_TRAVERSAL)
        argWindow.SetScrollRate(10, 10)
        argSizer = wx.GridBagSizer(hgap=0, vgap=10)
        row = 0
        growable = False
        self.argctrls = []
        for argInfo in self.mainFrame.currentScript.GetFilterCalltipArgInfo(calltip=filterInfo):
            totalInfo, cArgType, cArgName, boolRepeatArg, boolOptionalArg, cArgInfo = argInfo
            argtype, argname, guitype, defaultValue, other = self.mainFrame.ParseCalltipArgInfo(totalInfo)
            #~ if guitype is None or argname is None or argtype not in ('int', 'float', 'bool', 'string'):
            if argname is None or argtype not in ('int', 'float', 'bool', 'string'):
                self.argctrls.append((argtype, argname, None, boolRepeatArg, boolOptionalArg))
            else:
                argLabel = wx.StaticText(argWindow, wx.ID_ANY, '%(argtype)s %(argname)s' % locals())
                argLabel.controls = []
                argSizer.Add(argLabel, (row,0), wx.DefaultSpan, wx.ALIGN_RIGHT|wx.ALIGN_BOTTOM|wx.BOTTOM|wx.RIGHT, 5)
                if argtype in ('int', 'float') and guitype != 'intlist':
                    strDefaultValue = strMinValue = strMaxValue = strMod = ''
                    if other is not None:
                        minValue, maxValue, nDecimal, mod = other
                        if nDecimal is None:
                            nDecimal = 0
                        strTemplate = '%.'+str(nDecimal)+'f'
                        if defaultValue is not None:
                            try:
                                strDefaultValue = strTemplate % defaultValue
                            except TypeError:
                                strDefaultValue = defaultValue
                        if minValue is not None:
                            try:
                                strMinValue = strTemplate % minValue
                            except TypeError:
                                strMinValue = minValue
                        if maxValue is not None:
                            try:
                                strMaxValue = strTemplate % maxValue
                            except TypeError:
                                strMaxValue = maxValue
                        if mod is not None:
                            try:
                                strMod = '%i' % mod
                            except TypeError:
                                strMod = mod
                    elif guitype == 'color':
                        strDefaultValue = '$%s' % defaultValue
                    itemData = (
                        (strDefaultValue, _('Default')),
                        (strMinValue, _('Min value')),
                        (strMaxValue, _('Max value')),
                        (strMod, _('Step size')),
                    )
                    hsizer = wx.BoxSizer(wx.HORIZONTAL)
                    for itemValue, itemName in itemData:
                        itemLabel = wx.StaticText(argWindow, wx.ID_ANY, itemName)
                        itemTextCtrl = wx.TextCtrl(argWindow, wx.ID_ANY, itemValue,size=(75,-1))
                        vsizer = wx.BoxSizer(wx.VERTICAL)
                        vsizer.Add(itemLabel, 0, wx.LEFT, 2)
                        vsizer.Add(itemTextCtrl, 0, wx.ALL, 0)
                        hsizer.Add(vsizer, 0, wx.EXPAND|wx.RIGHT,5)
                        argLabel.controls.append(itemTextCtrl)
                    argSizer.Add(hsizer, (row,1), wx.DefaultSpan, wx.ALIGN_CENTER_VERTICAL|wx.RIGHT, 0)
                elif argtype == 'bool':
                    strDefaultValue = ''
                    if defaultValue is not None:
                        if defaultValue.lower() == 'true':
                            strDefaultValue = 'True'
                        if defaultValue.lower() == 'false':
                            strDefaultValue = 'False'
                    itemLabel = wx.StaticText(argWindow, wx.ID_ANY, _('Default'))
                    itemTextCtrl = wx.ComboBox(argWindow, wx.ID_ANY, strDefaultValue, choices=['True', 'False'], style=wx.CB_DROPDOWN, size=(75,-1))
                    vsizer = wx.BoxSizer(wx.VERTICAL)
                    vsizer.Add(itemLabel, 0, wx.LEFT, 2)
                    vsizer.Add(itemTextCtrl, 0, wx.ALL, 0)
                    argLabel.controls.append(itemTextCtrl)
                    argSizer.Add(vsizer, (row,1), wx.DefaultSpan, wx.ALIGN_CENTER_VERTICAL|wx.RIGHT, 0)
                elif argtype == 'string' or argtype == 'int' and guitype == 'intlist':
                    strDefaultValue = strValuesList = ''
                    if defaultValue is not None:
                        if defaultValue:
                            if argtype == 'string':
                                strDefaultValue = '"%s"' % defaultValue.strip('"')
                            else:
                                strDefaultValue = str(defaultValue)
                    if other is not None:
                        strValuesList = ', '.join(other)
                    hsizer = wx.BoxSizer(wx.HORIZONTAL)
                    # Default control
                    itemLabel = wx.StaticText(argWindow, wx.ID_ANY, _('Default'))
                    itemTextCtrl = wx.TextCtrl(argWindow, wx.ID_ANY, strDefaultValue, size=(75,-1))
                    vsizer = wx.BoxSizer(wx.VERTICAL)
                    vsizer.Add(itemLabel, 0, wx.LEFT, 2)
                    vsizer.Add(itemTextCtrl, 0, wx.ALL, 0)
                    argLabel.controls.append(itemTextCtrl)
                    hsizer.Add(vsizer, 0, wx.EXPAND|wx.RIGHT,5)
                    # Values control
                    itemLabel = wx.StaticText(argWindow, wx.ID_ANY, _('Value list (comma separated)'))
                    itemTextCtrl = wx.TextCtrl(argWindow, wx.ID_ANY, strValuesList, size=(200,-1))
                    vsizer = wx.BoxSizer(wx.VERTICAL)
                    vsizer.Add(itemLabel, 0, wx.LEFT, 2)
                    vsizer.Add(itemTextCtrl, 1, wx.EXPAND|wx.ALL, 0)
                    argLabel.controls.append(itemTextCtrl)
                    hsizer.Add(vsizer, 1, wx.EXPAND|wx.RIGHT,5)

                    argSizer.Add(hsizer, (row,1), wx.DefaultSpan, wx.EXPAND|wx.ALIGN_CENTER_VERTICAL|wx.RIGHT, 0)
                    if wx.VERSION > (2, 9):
                        if not argSizer.IsColGrowable(1):
                            argSizer.AddGrowableCol(1)
                    else:
                        if not growable:
                            argSizer.AddGrowableCol(1)
                            growable = True
                row += 1
                self.argctrls.append((argtype, argname, argLabel, boolRepeatArg, boolOptionalArg))
        argWindow.SetSizer(argSizer)
        # Standard buttons
        okay  = wx.Button(self, wx.ID_OK, _('OK'))
        self.Bind(wx.EVT_BUTTON, self.OnButtonOK, okay)
        okay.SetDefault()
        cancel = wx.Button(self, wx.ID_CANCEL, _('Cancel'))
        btns = wx.StdDialogButtonSizer()
        btns.AddButton(okay)
        btns.AddButton(cancel)
        btns.Realize()
        # Set the sizer
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add((-1,-1), 0, wx.TOP, 10)
        sizer.Add(filterLabel, 0, wx.EXPAND|wx.ALL, 5)
        sizer.Add(wx.StaticLine(self, wx.ID_ANY), 0, wx.EXPAND|wx.LEFT|wx.RIGHT, 5)
        sizer.Add(argWindow, 1, wx.EXPAND|wx.ALL, 5)
        sizer.Add(wx.StaticLine(self, wx.ID_ANY), 0, wx.EXPAND|wx.LEFT|wx.RIGHT, 5)
        #~ sizer.Add(wx.StaticText(self,wx.ID_ANY, _('* optional value')), 0, wx.EXPAND|wx.ALL, 10)
        sizer.Add(btns, 0, wx.EXPAND|wx.ALL, 5)
        self.SetSizer(sizer)
        sizer.Layout()
        argWindow.FitInside()
        w, h = argSizer.GetMinSize()
        w = max(w + 10, 400)
        h = min(h + 100, 700)
        self.SetSize(self.ClientToWindowSize((w, h)))
        if argWindow.HasScrollbar(wx.HORIZONTAL):
            scrollbar_w = wx.SystemSettings_GetMetric(wx.SYS_VSCROLL_X)
            self.SetSize(self.ClientToWindowSize((w + scrollbar_w, -1)))
示例#47
0
 def Validate(self, parent):
     textCtrl = self.GetWindow()
     text = textCtrl.GetValue()
     if len(text) == 0:
         self.ShowWarning(textCtrl, _('This field must contain a value!'))
         return False
     elif textCtrl == self.ctrlDict['label']:
         try:
             temp  = str(text)
         except UnicodeEncodeError:
             temp = text
         if temp in self.labels:
             self.ShowWarning(textCtrl, _('This slider label already exists!'))
             return False
         if self.getModFromLabel(text) == -1:
             self.ShowWarning(textCtrl, _('Invalid slider label modulo syntax!'))
             return False
         return True
     else:
         try:
             float(text)
         except ValueError:
             self.ShowWarning(textCtrl, _('This field must contain a number!'))
             return False
         try:
             minValue = float(self.ctrlDict['min'].GetValue())
             maxValue = float(self.ctrlDict['max'].GetValue())
             value = float(self.ctrlDict['val'].GetValue())
             # Validate ranges
             if minValue >= maxValue and textCtrl == self.ctrlDict['min']:
                 self.ShowWarning(textCtrl, _('The min value must be less than the max!'))
                 return False
             if value < minValue or value > maxValue and textCtrl == self.ctrlDict['val']:
                 self.ShowWarning(textCtrl, _('The initial value must be between the min and the max!'))
                 return False
             # Validate modulo divisibility
             mod = self.getModFromLabel(self.ctrlDict['label'].GetValue())
             if mod == -1:
                 self.ShowWarning(textCtrl, _('Invalid slider label modulo syntax!'))
                 return False
             if mod is not None:
                 if int(minValue) % mod != 0 and textCtrl == self.ctrlDict['min']:
                     self.ShowWarning(textCtrl, _('The min value must be a multiple of %(mod)s!') % locals())
                     return False
                 if int(maxValue) % mod != 0 and textCtrl == self.ctrlDict['max']:
                     self.ShowWarning(textCtrl, _('The max value must be a multiple of %(mod)s!') % locals())
                     return False
                 if int(value) % mod != 0 and textCtrl == self.ctrlDict['val']:
                     self.ShowWarning(textCtrl, _('The initial value must be a multiple of %(mod)s!') % locals())
                     return False
                 if mod > (maxValue - minValue):
                     self.ShowWarning(self.ctrlDict['min'], _('The difference between the min and max must be greater than %(mod)s!') % locals())
                     return False
         except ValueError:
             pass
         return True
示例#48
0
    def OnButtonOK(self, event):
        strList = []
        for argtype, argname, argLabel, boolRepeatArg, boolOptionalArg in self.argctrls:
            if argtype is None and argname is None:
                continue
            strBase = '%(argtype)s %(argname)s' % locals()
            strInfoNew = strBase
            if argLabel is None:
                if argname is None:
                    strInfoNew = argtype
            else:

                strDef = argLabel.controls[0].GetValue().strip()
                is_list = argtype == 'int' and argLabel.controls[1].GetValue(
                ).count(',')
                #~ strList.append('%(strBase)s=%(strDefaultValue)s' % locals())
                if argtype in ('int', 'float') and not is_list:
                    strMin = argLabel.controls[1].GetValue().strip()
                    strMax = argLabel.controls[2].GetValue().strip()
                    strMod = argLabel.controls[3].GetValue().strip()
                    # Validate if any field has input
                    sliderValues = None
                    if strDef or strMin or strMax or strMod:
                        errorType, errorMessage, sliderValues = self.mainFrame.ValidateAvsSliderInputs(
                            strDef, strMin, strMax, strMod)
                        if errorType is not None and errorType != -1:
                            self.ShowWarning(
                                argLabel.controls[errorType],
                                '%(argtype)s %(argname)s: %(errorMessage)s' %
                                locals())
                            return
                    # Create the new string info
                    #~ if sliderValues is not None and len(sliderValues) == 1:
                    if strDef and not strMin and not strMax:
                        strInfoNew = '%(strBase)s=%(strDef)s' % locals()
                    elif not strMin and not strMax:
                        strInfoNew = strBase
                    elif strMod:
                        strInfoNew = '%(strBase)s=%(strDef)s (%(strMin)s to %(strMax)s by %(strMod)s)' % locals(
                        )
                    else:
                        strInfoNew = '%(strBase)s=%(strDef)s (%(strMin)s to %(strMax)s)' % locals(
                        )
                elif argtype == 'bool':
                    if strDef:
                        if strDef.lower() not in ('true', 'false'):
                            self.ShowWarning(
                                argLabel.controls[0],
                                '%s %s: %s' %
                                (argtype, argname,
                                 _('Value must be True or False!')),
                                comboBox=True)
                            return
                        strInfoNew = '%(strBase)s=%(strDef)s' % locals()
                elif argtype == 'string' or argtype == 'int' and is_list:
                    strValues = argLabel.controls[1].GetValue().strip()
                    if strDef or strValues:
                        if not strValues:
                            strValuesNew = ''
                            #~ msg =  _('Must enter a value list!')
                            #~ self.ShowWarning(argLabel.controls[1], '%s %s: %s' % (argtype, argname,msg))
                            #~ return
                            pass
                        else:
                            if argtype == 'int':
                                strValuesNew = ' (%s)' % ' / '.join(
                                    [s.strip() for s in strValues.split(',')])
                            else:
                                strValuesNew = ' (%s)' % '/ '.join([
                                    '"%s"' % s.strip(' "')
                                    for s in strValues.split(',')
                                ])
                        if strDef and argtype == 'string':
                            strDef = '"%s"' % strDef.strip('"')
                        strInfoNew = '%(strBase)s=%(strDef)s%(strValuesNew)s' % locals(
                        )
            strRepeatArg = ''
            if boolRepeatArg:
                strRepeatArg = ' [, ...]'
            if boolOptionalArg:
                strInfoNew = '[{0}]'.format(strInfoNew)
            strList.append(strInfoNew + strRepeatArg)
        self.newFilterInfo = '(\n%s\n)' % ',\n'.join(strList)
        event.Skip()
示例#49
0
    def OnButtonOK(self, event):
        strList = []
        for argtype, argname, argLabel, boolRepeatArg, boolOptionalArg in self.argctrls:
            if argtype is None and argname is None:
                continue
            strBase = '%(argtype)s %(argname)s' % locals()
            strInfoNew = strBase
            if argLabel is None:
                if argname is None:
                    strInfoNew = argtype
            else:

                strDef = argLabel.controls[0].GetValue().strip()
                is_list = argtype == 'int' and argLabel.controls[1].GetValue().count(',')
                #~ strList.append('%(strBase)s=%(strDefaultValue)s' % locals())
                if argtype in ('int', 'float') and not is_list:
                    strMin = argLabel.controls[1].GetValue().strip()
                    strMax = argLabel.controls[2].GetValue().strip()
                    strMod = argLabel.controls[3].GetValue().strip()
                    # Validate if any field has input
                    sliderValues = None
                    if strDef or strMin or strMax or strMod:
                        errorType, errorMessage, sliderValues = self.mainFrame.ValidateAvsSliderInputs(strDef, strMin, strMax, strMod)
                        if errorType is not None and errorType != -1:
                            self.ShowWarning(argLabel.controls[errorType], '%(argtype)s %(argname)s: %(errorMessage)s' % locals())
                            return
                    # Create the new string info
                    #~ if sliderValues is not None and len(sliderValues) == 1:
                    if strDef and not strMin and not strMax:
                        strInfoNew = '%(strBase)s=%(strDef)s' % locals()
                    elif not strMin and not strMax:
                        strInfoNew = strBase
                    elif strMod:
                        strInfoNew = '%(strBase)s=%(strDef)s (%(strMin)s to %(strMax)s by %(strMod)s)' % locals()
                    else:
                        strInfoNew = '%(strBase)s=%(strDef)s (%(strMin)s to %(strMax)s)' % locals()
                elif argtype == 'bool':
                    if strDef:
                        if strDef.lower() not in ('true', 'false'):
                            self.ShowWarning(argLabel.controls[0], '%s %s: %s' % (argtype, argname, _('Value must be True or False!')), comboBox=True)
                            return
                        strInfoNew = '%(strBase)s=%(strDef)s' % locals()
                elif argtype == 'string' or argtype == 'int' and is_list:
                    strValues = argLabel.controls[1].GetValue().strip()
                    if strDef or strValues:
                        if not strValues:
                            strValuesNew = ''
                            #~ msg =  _('Must enter a value list!')
                            #~ self.ShowWarning(argLabel.controls[1], '%s %s: %s' % (argtype, argname,msg))
                            #~ return
                            pass
                        else:
                            if argtype == 'int':
                                strValuesNew = ' (%s)' % ' / '.join([s.strip() for s in strValues.split(',')])
                            else:
                                strValuesNew = ' (%s)' % '/ '.join(['"%s"' % s.strip(' "') for s in strValues.split(',')])
                        if strDef and argtype == 'string':
                            strDef = '"%s"' % strDef.strip('"')
                        strInfoNew = '%(strBase)s=%(strDef)s%(strValuesNew)s' % locals()
            strRepeatArg = ''
            if boolRepeatArg:
                strRepeatArg = ' [, ...]'
            if boolOptionalArg:
                strInfoNew = '[{0}]'.format(strInfoNew)
            strList.append(strInfoNew+strRepeatArg)
        self.newFilterInfo = '(\n%s\n)' % ',\n'.join(strList)
        event.Skip()
示例#50
0
    def CreateWindowElements(self):
        self.notebook = wxp.Notebook(self, wx.ID_ANY, style=wx.NO_BORDER,
                                     invert_scroll=self.GetParent().options['invertscrolling'])

        class CheckListBox(wx.CheckListBox):
            def __init__(self, *args, **kwargs):
                wx.CheckListBox.__init__(self, *args, **kwargs)
                self.Bind(wx.EVT_CHECKLISTBOX, self.OnCheckListBox)
                self.removedSet = self.GetTopLevelParent().removedSet

            def Check(self, item, check=True):
                wx.CheckListBox.Check(self, item, check)
                self.UpdateRemovedSet(item)

            def OnCheckListBox(self, event):
                self.UpdateRemovedSet(event.GetInt())
                event.Skip()

            def UpdateRemovedSet(self, item):
                name = self.GetString(item).split()[0].lower()
                if self.IsChecked(item):
                    if name in self.removedSet:
                        self.removedSet.remove(name)
                else:
                    self.removedSet.add(name)

        pageInfo = (
            (_('Core filters'), 0),
            (_('Plugins'), 2),
            (_('User functions'), 3),
            (_('Script functions'), 4),
            (_('Clip properties'), 1),
        )
        pageDict = collections.defaultdict(list)
        for key in set(self.filterDict.keys()+self.overrideDict.keys()):
            name, args, ftype = self.overrideDict.get(key, (None, None, None))
            extra = ' '
            if name is None:
                try:
                    name, args, ftype = self.filterDict[key]
                except:
                    continue
            else:
                extra += '*'
            if key in self.presetDict:
                extra += '~'
            pageDict[ftype].append(name + extra)
        for title, index in pageInfo:
            panel = wx.Panel(self.notebook, wx.ID_ANY, size=(700,-1))
            self.notebook.AddPage(panel, title)
            # List box

            #~ choices = [
                #~ self.overrideDict.get(key, value)[0]
                #~ for key, value in self.filterDict.items()
                #~ if value[2] == index
            #~ ]

            #~ d1 = dict([(lowername, name) for lowername, (name,args,ftype) in self.filterDict.items() if ftype==index])
            #~ d2 = dict([(lowername, name+' *') for lowername, (name,args,ftype) in self.overrideDict.items() if ftype==index])
            #~ d1.update(d2)
            #~ choices = [value for key, value in d1.items()]

            choices = pageDict[index]
            listbox = CheckListBox(panel, wx.ID_ANY, choices=choices, size=(-1,300), style=wx.LB_SORT)
            if choices:
                listbox.SetSelection(0)
            listbox.Bind(wx.EVT_LISTBOX_DCLICK, lambda event: self.EditFunctionInfo())
            for i in xrange(listbox.GetCount()):
                name = listbox.GetString(i).split()[0]
                if name.lower() not in self.removedSet:
                    listbox.Check(i)
            title = title.lower()
            # Buttons
            buttonadd = wx.Button(panel, wx.ID_ANY, _('New function'))#, size=(100, -1))
            buttonedit = wx.Button(panel, wx.ID_ANY, _('Edit selected'))
            buttondelete = wx.Button(panel, wx.ID_ANY, _('Delete selected'))
            buttoncheckall = wx.Button(panel, wx.ID_ANY, _('Select all'))
            buttonuncheckall = wx.Button(panel, wx.ID_ANY, _('Clear all'))
            panel.Bind(wx.EVT_BUTTON, lambda event: self.AddNewFunction(ftype=-1), buttonadd)
            panel.Bind(wx.EVT_BUTTON, lambda event: self.EditFunctionInfo(), buttonedit)
            panel.Bind(wx.EVT_BUTTON, lambda event: self.DeleteFunction(), buttondelete)
            panel.Bind(wx.EVT_BUTTON, lambda event: self.CheckAllFunctions(True), buttoncheckall)
            panel.Bind(wx.EVT_BUTTON, lambda event: self.CheckAllFunctions(False), buttonuncheckall)
            buttonSizer = wx.BoxSizer(wx.VERTICAL)
            buttonSizer.Add(buttonadd, 0, wx.EXPAND|wx.TOP|wx.BOTTOM, 5)
            buttonSizer.Add(buttonedit, 0, wx.EXPAND|wx.BOTTOM, 5)
            buttonSizer.Add(buttondelete, 0, wx.EXPAND|wx.BOTTOM, 5)
            buttonSizer.Add(wx.StaticLine(panel, wx.ID_ANY, style=wx.HORIZONTAL), 0, wx.EXPAND|wx.TOP|wx.BOTTOM, 5)
            buttonSizer.Add(buttonuncheckall, 0, wx.EXPAND|wx.TOP|wx.BOTTOM, 5)
            buttonSizer.Add(buttoncheckall, 0, wx.EXPAND|wx.BOTTOM, 5)
            #~ if index == 2:
                #~ self.buttonclearlongnames = wx.Button(panel, wx.ID_ANY, _('Clear long names'))
                #~ panel.Bind(wx.EVT_BUTTON, lambda event: self.ClearLongNames(), self.buttonclearlongnames)
                #~ buttonSizer.Add(self.buttonclearlongnames, 0, wx.EXPAND|wx.BOTTOM, 5)
            if index in (2, 3):
                buttonselectinstalled = wx.Button(panel, wx.ID_ANY, _('Select installed'))
                panel.Bind(wx.EVT_BUTTON, lambda event: self.SelectInstalledFilters(), buttonselectinstalled)
                buttonSizer.Add(buttonselectinstalled, 0, wx.EXPAND|wx.BOTTOM, 5)
            # Size the elements in the panel
            listboxSizer = wx.BoxSizer(wx.HORIZONTAL)
            listboxSizer.Add(listbox, 1, wx.EXPAND|wx.RIGHT, 15)
            listboxSizer.Add(buttonSizer, 0, wx.EXPAND|wx.RIGHT, 5)
            panelSizer = wx.BoxSizer(wx.VERTICAL)
            panelSizer.Add(listboxSizer, 1, wx.EXPAND|wx.ALL, 5)
            panel.SetSizer(panelSizer)
            panelSizer.Layout()
            # Bind items to the panel itself
            panel.listbox = listbox
            panel.functiontype = index
        self.CreatePluginsContextMenu()
        # Buttons
        button0 = wx.Button(self, wx.ID_ANY, _('Import'))
        menu0 = wx.Menu()
        menuItem = menu0.Append(wx.ID_ANY, _('Import from files'))
        self.Bind(wx.EVT_MENU, lambda event: self.ImportFromFiles(), menuItem)
        menuItem = menu0.Append(wx.ID_ANY, _('Import from wiki'))
        self.Bind(wx.EVT_MENU, lambda event: self.ImportFromFiles(wiki=True), menuItem)
        self.Bind(wx.EVT_BUTTON, lambda event: button0.PopupMenu(
                    menu0, (1, button0.GetSizeTuple()[1])), button0)
        button1 = wx.Button(self, wx.ID_ANY, _('Export customizations'))
        self.Bind(wx.EVT_BUTTON, lambda event: self.ExportCustomizations(), button1)
        button2 = wx.Button(self, wx.ID_ANY, _('Clear customizations'))
        self.Bind(wx.EVT_BUTTON, lambda event: self.ClearCustomizations(), button2)
        button3 = wx.Button(self, wx.ID_ANY, _('Clear manual presets'))
        self.Bind(wx.EVT_BUTTON, lambda event: self.ClearPresets(), button3)
        buttonSizer = wx.BoxSizer(wx.HORIZONTAL)
        buttonSizer.Add(button0, 0, wx.RIGHT, 5)
        buttonSizer.Add(button1, 0, wx.RIGHT, 5)
        buttonSizer.Add(button2, 0, wx.RIGHT, 5)
        buttonSizer.Add(button3, 0, wx.RIGHT, 5)
        self.checkBox = wx.CheckBox(self, wx.ID_ANY, _("When importing, don't show the choice dialog"))
        # Standard buttons
        okay  = wx.Button(self, wx.ID_OK, _('OK'))
        #~ self.Bind(wx.EVT_BUTTON, self.OnButtonOK, okay)
        cancel = wx.Button(self, wx.ID_CANCEL, _('Cancel'))
        sdtbtns = wx.StdDialogButtonSizer()
        sdtbtns.Add(self.checkBox)
        sdtbtns.AddButton(okay)
        sdtbtns.AddButton(cancel)
        sdtbtns.Realize()
        # Size the elements
        dlgSizer = wx.BoxSizer(wx.VERTICAL)
        dlgSizer.Add(self.notebook, 1, wx.EXPAND|wx.ALL, 5)
        dlgSizer.Add(buttonSizer, 0, wx.LEFT, 5)
        dlgSizer.Add(wx.StaticLine(self, style=wx.HORIZONTAL), 0, wx.EXPAND|wx.TOP|wx.BOTTOM, 5)
        dlgSizer.Add(sdtbtns, 0, wx.EXPAND|wx.ALL, 5)
        self.SetSizer(dlgSizer)
        dlgSizer.SetSizeHints(self)
        dlgSizer.Layout()
        # Misc
        def OnPageChanged(event):
            event.GetEventObject().GetCurrentPage().SetFocus()
            event.Skip()
        self.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGED, OnPageChanged)
        self.notebook.GetCurrentPage().listbox.SetFocus()
        okay.SetDefault()
示例#51
0
 def OnSelectTheme(self, event):
     theme = event.GetEventObject().GetStringSelection()
     if theme != _('Select a predefined theme'):
         return self.SetTheme(
             theme,
             only_colors=self.controls2['theme_set_only_colors'].GetValue())
示例#52
0
 def OnArgsEditSliders(event):
     name = textCtrl0.GetValue()
     dlg2 = AvsFilterAutoSliderInfo(dlg, self.GetParent(), name, textCtrl2.GetValue(), title=_('Slider information'))
     ID = dlg2.ShowModal()
     if ID == wx.ID_OK:
         textCtrl2.SetValue(dlg2.GetNewFilterInfo())
     dlg2.Destroy()
示例#53
0
 def CreateFilterInfoDialog(self, resetargsbutton=True):
     dlg = wx.Dialog(self, wx.ID_ANY, _('Edit function information'))
     staticText0 = wx.StaticText(dlg, wx.ID_ANY, _('Name:'))
     textCtrl0 = wx.TextCtrl(dlg, wx.ID_ANY, size=(200,-1))
     staticText1 = wx.StaticText(dlg, wx.ID_ANY, _('Type:'))
     choices = [_('core filter'), _('clip property'), _('plugin'), _('user function'), _('script function')]
     choiceBox1 = wx.Choice(dlg, wx.ID_ANY, choices=choices)
     staticText2 = wx.StaticText(dlg, wx.ID_ANY, _('Arguments:'))
     staticText2_4 = wx.StaticText(dlg, wx.ID_ANY, _('define sliders'))
     staticText2_5 = wx.StaticText(dlg, wx.ID_ANY, _('reset to default'))
     for eachCtrl in (staticText2_4, staticText2_5):
         font = eachCtrl.GetFont()
         font.SetUnderlined(True)
         eachCtrl.SetFont(font)
         eachCtrl.SetForegroundColour(wx.Colour(0,0,255))
         eachCtrl.SetCursor(wx.StockCursor(wx.CURSOR_HAND))
     def OnArgsEditSliders(event):
         name = textCtrl0.GetValue()
         dlg2 = AvsFilterAutoSliderInfo(dlg, self.GetParent(), name, textCtrl2.GetValue(), title=_('Slider information'))
         ID = dlg2.ShowModal()
         if ID == wx.ID_OK:
             textCtrl2.SetValue(dlg2.GetNewFilterInfo())
         dlg2.Destroy()
     staticText2_4.Bind(wx.EVT_LEFT_DOWN, OnArgsEditSliders)
     def OnClickSetToDefault(event):
         textCtrl0.SetValue(dlg.defaultName)
         textCtrl2.SetValue(dlg.defaultArgs)
     staticText2_5.Bind(wx.EVT_LEFT_DOWN, OnClickSetToDefault)
     textCtrl2 = wxp.TextCtrl(dlg, wx.ID_ANY, size=(200,200), style=wx.TE_MULTILINE|wx.HSCROLL)
     def OnArgsChange(event):
         if checkBox3.IsChecked():
             name = textCtrl0.GetValue() #dlg.defaultName
             args= textCtrl2.GetValue()
             textCtrl3.SetValue(self.CreateDefaultPreset(name, args))
     textCtrl0.Bind(wx.EVT_TEXT, OnArgsChange)
     textCtrl2.Bind(wx.EVT_TEXT, OnArgsChange)
     #~ textCtrl2.Bind(wx.EVT_LEFT_DCLICK, OnArgsEditSliders)
     staticText3 = wx.StaticText(dlg, wx.ID_ANY, _('Preset:'))
     checkBox3 = wx.CheckBox(dlg, wx.ID_ANY, _('Auto-generate'))
     def OnCheck(event):
         if checkBox3.IsChecked():
             textCtrl3.SetEditable(False)
             colour = self.GetBackgroundColour()
             textCtrl3.SetBackgroundColour(colour)
             OnArgsChange(None)
         else:
             textCtrl3.SetEditable(True)
             textCtrl3.SetBackgroundColour(wx.WHITE)
     checkBox3.Bind(wx.EVT_CHECKBOX, OnCheck)
     textCtrl3 = wxp.TextCtrl(dlg, wx.ID_ANY, size=(-1,50), style=wx.TE_MULTILINE|wx.HSCROLL)
     # Standard buttons
     okay  = wx.Button(dlg, wx.ID_OK, _('OK'))
     def OnFilterInfoDialogButtonOK(event):
         newName = textCtrl0.GetValue()
         enteredName = dlg.enteredName
         if enteredName is None:
             lowername = newName.lower()
             if lowername in self.overrideDict or lowername in self.filterDict:
                 wx.MessageBox(_('Filter name already exists!'), _('Error'), style=wx.OK|wx.ICON_ERROR)
                 textCtrl0.SetFocus()
                 return
             if not newName or newName[0].isdigit() or re.findall('\W', newName):
                 wx.MessageBox(_('Invalid filter name!'), _('Error'), style=wx.OK|wx.ICON_ERROR)
                 textCtrl0.SetFocus()
                 return
         elif newName.lower() != enteredName.lower():
             wx.MessageBox(_('Renaming not allowed!'), _('Error'), style=wx.OK|wx.ICON_ERROR)
             textCtrl0.SetFocus()
             return
         if dlg.typeBox.GetCurrentSelection() == 2 and newName.count('_') == 0:
             wx.MessageBox(_('You must use dllname_function naming format for plugins!'),
                           _('Error'), style=wx.OK|wx.ICON_ERROR)
             textCtrl0.SetFocus()
             return
         event.Skip()
     dlg.Bind(wx.EVT_BUTTON, OnFilterInfoDialogButtonOK, okay)
     cancel = wx.Button(dlg, wx.ID_CANCEL, _('Cancel'))
     btns = wx.StdDialogButtonSizer()
     btns.AddButton(okay)
     btns.AddButton(cancel)
     btns.Realize()
     # Size the elements
     sizer01 = wx.FlexGridSizer(cols=4, hgap=5, vgap=5)
     sizer01.Add(staticText0, 0, wx.ALIGN_CENTER_VERTICAL)
     sizer01.Add(textCtrl0, 0, wx.EXPAND|wx.RIGHT, 10)
     sizer01.Add(staticText1, 0, wx.ALIGN_CENTER_VERTICAL)
     sizer01.Add(choiceBox1, 0, wx.EXPAND)
     sizer2 = wx.BoxSizer(wx.HORIZONTAL)
     sizer2.Add(staticText2, 0, wx.ALL, 0)
     sizer2.Add((-1,-1), 1, wx.EXPAND|wx.ALL, 0)
     sizer2.Add(staticText2_5, 0, wx.RIGHT, 10)
     sizer2.Add(staticText2_4, 0, wx.LEFT|wx.RIGHT, 10)
     sizer3 = wx.BoxSizer(wx.HORIZONTAL)
     sizer3.Add(staticText3, 0, wx.ALL, 0)
     sizer3.Add((-1,-1), 1, wx.EXPAND|wx.ALL, 0)
     sizer3.Add(checkBox3, 0, wx.RIGHT, 10)
     dlgSizer = wx.BoxSizer(wx.VERTICAL)
     dlgSizer.Add((-1,5), 0, wx.EXPAND|wx.ALL, 0)
     dlgSizer.Add(sizer01, 0, wx.EXPAND|wx.ALL, 5)
     dlgSizer.Add(wx.StaticLine(dlg, style=wx.HORIZONTAL), 0, wx.EXPAND|wx.TOP|wx.BOTTOM, 5)
     #~ dlgSizer.Add(staticText2, 0, wx.EXPAND|wx.TOP|wx.LEFT, 5)
     dlgSizer.Add(sizer2, 0, wx.EXPAND|wx.TOP|wx.LEFT, 5)
     dlgSizer.Add(textCtrl2, 1, wx.EXPAND|wx.ALL, 5)
     #~ dlgSizer.Add(staticText3, 0, wx.TOP|wx.LEFT, 5)
     dlgSizer.Add(sizer3, 0, wx.EXPAND|wx.TOP|wx.LEFT, 5)
     dlgSizer.Add(textCtrl3, 0, wx.EXPAND|wx.ALL, 5)
     dlgSizer.Add(btns, 0, wx.EXPAND|wx.ALL, 5)
     dlg.SetSizer(dlgSizer)
     if not resetargsbutton:
         staticText2_5.Hide()
     def SetAutopreset(on=True):
         if on:
             checkBox3.SetValue(True)
             textCtrl3.SetEditable(False)
             colour = self.GetBackgroundColour()
             textCtrl3.SetBackgroundColour(colour)
         else:
             checkBox3.SetValue(False)
             textCtrl3.SetEditable(True)
             textCtrl3.SetBackgroundColour(wx.WHITE)
     dlg.SetAutopreset = SetAutopreset
     dlg.Fit()
     dlgSizer.Layout()
     # Bind variables
     dlg.nameBox = textCtrl0
     dlg.typeBox = choiceBox1
     dlg.argsBox = textCtrl2
     dlg.presetBox = textCtrl3
     dlg.resetCtrl = staticText2_5
     dlg.autopresetCheckbox = checkBox3
     dlg.cancelButton = cancel
     dlg.defaultArgs = ''
     dlg.defaultName = ''
     dlg.enteredName = ''
     self.FilterInfoDialog = dlg
示例#54
0
    def SelectImportFilters(self, filterInfo):
        choices = []
        filterInfo.sort(key=lambda fi:
                    [i.lower() if isinstance(i, basestring) else i for i in fi])
        for filename, filtername, filterargs, ftype in filterInfo:
            choices.append(os.path.basename(filename) + ' -> ' + filtername)
        dlg = wx.Dialog(self, wx.ID_ANY, _('Select the functions to import'),
                        style=wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER)
        listbox = wx.CheckListBox(dlg, wx.ID_ANY, choices=choices, style=wx.LB_EXTENDED)
        customized, not_customized = [], []
        for i in range(len(choices)):
            filename, filtername = choices[i].lower().split(' -> ')
            if filtername in self.overrideDict:
                listbox.SetItemForegroundColour(i, wx.RED)
                customized.append(i)
            else:
                not_customized.append(i)
                if filename.find(filtername) != -1:
                    listbox.Check(i)
        idSelectionAll = wx.NewId()
        idAll = wx.NewId()
        idFileAll = wx.NewId()
        idNotCustomizedAll = wx.NewId()
        idSelectionNone = wx.NewId()
        idNone = wx.NewId()
        idFileNone = wx.NewId()
        idCustomizedNone = wx.NewId()

        def OnContextMenuItem(event):
            id = event.GetId()
            value = id in (idSelectionAll, idAll, idFileAll, idNotCustomizedAll)
            if id in [idSelectionAll, idSelectionNone]:
                listbox_range = listbox.GetSelections()
            elif id in [idAll, idNone]:
                listbox_range = range(len(filterInfo))
            elif id in [idFileAll, idFileNone]:
                pos = listbox.GetSelections()
                if not pos:
                    return
                filename = filterInfo[pos[0]][0]
                listbox_range = (i for i in range(len(filterInfo))
                                 if filename == filterInfo[i][0])
            elif id == idNotCustomizedAll:
                listbox_range = not_customized
            elif id == idCustomizedNone:
                listbox_range = customized
            for i in listbox_range:
                listbox.Check(i, value)

        def OnContextMenu(event):
            listbox.Bind(wx.EVT_MENU, OnContextMenuItem, id=idSelectionAll)
            listbox.Bind(wx.EVT_MENU, OnContextMenuItem, id=idAll)
            listbox.Bind(wx.EVT_MENU, OnContextMenuItem, id=idFileAll)
            listbox.Bind(wx.EVT_MENU, OnContextMenuItem, id=idNotCustomizedAll)
            listbox.Bind(wx.EVT_MENU, OnContextMenuItem, id=idSelectionNone)
            listbox.Bind(wx.EVT_MENU, OnContextMenuItem, id=idNone)
            listbox.Bind(wx.EVT_MENU, OnContextMenuItem, id=idFileNone)
            listbox.Bind(wx.EVT_MENU, OnContextMenuItem, id=idCustomizedNone)
            menu = wx.Menu()
            menu.Append(idSelectionAll, _('Check selected'))
            menu.Append(idAll, _('Check all'))
            menu.Append(idFileAll, _('Check all in this file'))
            menu.Append(idNotCustomizedAll, _('Check all not customized'))
            menu.AppendSeparator()
            menu.Append(idSelectionNone, _('Uncheck selected'))
            menu.Append(idNone, _('Uncheck all'))
            menu.Append(idFileNone, _('Uncheck all in this file'))
            menu.Append(idCustomizedNone, _('Uncheck all customized'))
            listbox.PopupMenu(menu)
            menu.Destroy()

        listbox.Bind(wx.EVT_CONTEXT_MENU, OnContextMenu)
        message = wx.StaticText(dlg, wx.ID_ANY, _('Red - a customized function already exists.'))
        okay  = wx.Button(dlg, wx.ID_OK, _('OK'))
        cancel = wx.Button(dlg, wx.ID_CANCEL, _('Cancel'))
        btns = wx.StdDialogButtonSizer()
        btns.AddButton(okay)
        btns.AddButton(cancel)
        btns.Realize()
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(listbox, 1, wx.EXPAND|wx.ALL,5)
        sizer.Add(message, 0, wx.LEFT, 5)
        sizer.Add(btns, 0, wx.EXPAND|wx.ALL,5)
        dlg.SetSizerAndFit(sizer)
        ID = dlg.ShowModal()
        for i in range(len(choices)-1, -1, -1):
            if ID != wx.ID_OK or not listbox.IsChecked(i):
                del filterInfo[i]
        dlg.Destroy()
示例#55
0
 def ParseCustomizations(self, filename):
     if filename.startswith('http'):
         f = urllib2.urlopen(filename)
     else:
         f = open(filename)
     text = '\n'.join([line.strip() for line in f.readlines()])
     f.close()
     if filename.endswith('.md'):
         text = text.split('```text\n', 1)[1].rsplit('```', 1)[0]
     filterInfo = []
     for section in text.split('\n\n['):
         title, data = section.split(']\n',1)
         title = title.strip('[]').lower()
         if title == 'clipproperties':
             for item in data.split('\n'):
                 if not item.strip():
                     continue
                 splitstring = item.split('(', 1)
                 if len(splitstring) == 2:
                     filtername = splitstring[0].strip()
                     filterargs = '('+splitstring[1].strip(' ')
                 else:
                     filtername = item
                     filterargs = ''
                 filterInfo.append((filename, filtername, filterargs, 1))
         elif title == 'scriptfunctions':
             for item in data.split('\n'):
                 if not item.strip():
                     continue
                 splitstring = item.split('(', 1)
                 if len(splitstring) == 2:
                     filtername = splitstring[0].strip()
                     filterargs = '('+splitstring[1].strip(' ')
                 else:
                     filtername = item
                     filterargs = ''
                 filterInfo.append((filename, filtername, filterargs, 4))
         elif title == 'corefilters':
             for s in data.split('\n\n'):
                 splitstring = s.split('(', 1)
                 if len(splitstring) == 2:
                     filtername = splitstring[0].strip()
                     filterargs = '('+splitstring[1].strip(' ')
                     filterInfo.append((filename, filtername, filterargs, 0))
         elif title == 'plugins':
             for s in data.split('\n\n'):
                 splitstring = s.split('(', 1)
                 if len(splitstring) == 2:
                     filtername = splitstring[0].strip()
                     if not self.parent.GetPluginFunctionShortName(filtername.lower()):
                         print>>sys.stderr, '{0}: {1}'.format(_('Error'), _('Invalid plugin '
                             'function name "{name}". Must be "pluginname_functionname".').format(name=filtername))
                         continue
                     filterargs = '('+splitstring[1].strip(' ')
                     filterInfo.append((filename, filtername, filterargs, 2))
         elif title == 'userfunctions':
             for s in data.split('\n\n'):
                 splitstring = s.split('(', 1)
                 if len(splitstring) == 2:
                     filtername = splitstring[0].strip()
                     filterargs = '('+splitstring[1].strip(' ')
                     filterInfo.append((filename, filtername, filterargs, 3))
     return filterInfo
示例#56
0
 def createTextCtrl(self):
     textCtrl = stc.StyledTextCtrl(self,
                                   wx.ID_ANY,
                                   size=(250, 250),
                                   style=wx.SIMPLE_BORDER)
     # Define the context menu
     textCtrl.UsePopUp(0)
     self.idInsertFrame = wx.NewId()
     self.idGetStatusText = wx.NewId()
     self.idToggleScrapWindow = wx.NewId()
     menuInfo = (
         (_('Undo') + '\tCtrl+Z', lambda event: textCtrl.Undo(), wx.ID_ANY),
         (_('Redo') + '\tCtrl+Y', lambda event: textCtrl.Redo(), wx.ID_ANY),
         (''),
         (_('Cut') + '\tCtrl+X', lambda event: textCtrl.Cut(), wx.ID_ANY),
         (_('Copy') + '\tCtrl+C', lambda event: textCtrl.Copy(), wx.ID_ANY),
         (_('Paste') + '\tCtrl+V', lambda event: textCtrl.Paste(),
          wx.ID_ANY),
         (''),
         (_('Select all') + '\tCtrl+A', lambda event: textCtrl.SelectAll(),
          wx.ID_ANY),
         (''),
         (_('Refresh'), self.OnRefresh, wx.ID_ANY),
         (_('Insert frame #'), self.OnInsertFrameNumber,
          self.idInsertFrame),
         (_('Save to file...'), self.OnSave, wx.ID_SAVE),
         (_('Clear all'), self.OnClearAll, wx.ID_ANY),
         (_('Toggle scrap window'), self.OnToggleScrapWindow,
          self.idToggleScrapWindow),
     )
     self.contextMenu = menu = wx.Menu()
     for eachMenuInfo in menuInfo:
         # Define optional arguments
         if not eachMenuInfo:
             menu.AppendSeparator()
         else:
             label = eachMenuInfo[0]
             handler = eachMenuInfo[1]
             status = ''
             id = eachMenuInfo[2]
             menuItem = menu.Append(id, label, status)
             textCtrl.Bind(wx.EVT_MENU, handler, menuItem)
     textCtrl.contextMenu = menu
     textCtrl.Bind(wx.EVT_CONTEXT_MENU, self.OnContextMenu)
     # Misc properties
     textCtrl.SetMarginWidth(1, 0)
     textCtrl.SetEOLMode(stc.STC_EOL_LF)
     return textCtrl
示例#57
0
 def ParseCustomizations(self, filename):
     if filename.startswith('http'):
         f = urllib2.urlopen(filename)
     else:
         f = open(filename)
     text = '\n'.join([line.strip() for line in f.readlines()])
     f.close()
     if filename.endswith('.md'):
         text = text.split('```text\n', 1)[1].rsplit('```', 1)[0]
     filterInfo = []
     for section in text.split('\n\n['):
         title, data = section.split(']\n', 1)
         title = title.strip('[]').lower()
         if title == 'clipproperties':
             for item in data.split('\n'):
                 if not item.strip():
                     continue
                 splitstring = item.split('(', 1)
                 if len(splitstring) == 2:
                     filtername = splitstring[0].strip()
                     filterargs = '(' + splitstring[1].strip(' ')
                 else:
                     filtername = item
                     filterargs = ''
                 filterInfo.append((filename, filtername, filterargs, 1))
         elif title == 'scriptfunctions':
             for item in data.split('\n'):
                 if not item.strip():
                     continue
                 splitstring = item.split('(', 1)
                 if len(splitstring) == 2:
                     filtername = splitstring[0].strip()
                     filterargs = '(' + splitstring[1].strip(' ')
                 else:
                     filtername = item
                     filterargs = ''
                 filterInfo.append((filename, filtername, filterargs, 4))
         elif title == 'corefilters':
             for s in data.split('\n\n'):
                 splitstring = s.split('(', 1)
                 if len(splitstring) == 2:
                     filtername = splitstring[0].strip()
                     filterargs = '(' + splitstring[1].strip(' ')
                     filterInfo.append(
                         (filename, filtername, filterargs, 0))
         elif title == 'plugins':
             for s in data.split('\n\n'):
                 splitstring = s.split('(', 1)
                 if len(splitstring) == 2:
                     filtername = splitstring[0].strip()
                     if not self.parent.GetPluginFunctionShortName(
                             filtername.lower()):
                         print >> sys.stderr, '{0}: {1}'.format(
                             _('Error'),
                             _('Invalid plugin '
                               'function name "{name}". Must be "pluginname_functionname".'
                               ).format(name=filtername))
                         continue
                     filterargs = '(' + splitstring[1].strip(' ')
                     filterInfo.append(
                         (filename, filtername, filterargs, 2))
         elif title == 'userfunctions':
             for s in data.split('\n\n'):
                 splitstring = s.split('(', 1)
                 if len(splitstring) == 2:
                     filtername = splitstring[0].strip()
                     filterargs = '(' + splitstring[1].strip(' ')
                     filterInfo.append(
                         (filename, filtername, filterargs, 3))
     return filterInfo
示例#58
0
            except (urllib2.URLError, urllib2.HTTPError), err:
                wx.MessageBox(u'\n\n'.join((os.path.basename(filename), unicode(err))),
                              _('Error'), style=wx.OK|wx.ICON_ERROR)
                continue
            except:
                info = None
            if not info:
                unrecognized.append(filename)
            else:
                filterInfo += info
        if filterInfo and (wiki or not self.checkBox.IsChecked()):
            self.SelectImportFilters(filterInfo)
        for filename, filtername, filterargs, ftype in filterInfo:
            self.EditFunctionInfo(filtername, filterargs, ftype)
        if unrecognized:
            wx.MessageBox('\n'.join(unrecognized), _('Unrecognized files'))

    def SelectImportFilters(self, filterInfo):
        choices = []
        filterInfo.sort(key=lambda fi:
                    [i.lower() if isinstance(i, basestring) else i for i in fi])
        for filename, filtername, filterargs, ftype in filterInfo:
            choices.append(os.path.basename(filename) + ' -> ' + filtername)
        dlg = wx.Dialog(self, wx.ID_ANY, _('Select the functions to import'),
                        style=wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER)
        listbox = wx.CheckListBox(dlg, wx.ID_ANY, choices=choices, style=wx.LB_EXTENDED)
        customized, not_customized = [], []
        for i in range(len(choices)):
            filename, filtername = choices[i].lower().split(' -> ')
            if filtername in self.overrideDict:
                listbox.SetItemForegroundColour(i, wx.RED)
示例#59
0
    def __init__(self,
                 parent,
                 mainFrame,
                 filterName,
                 filterInfo,
                 title=_('Edit filter database')):
        wx.Dialog.__init__(self,
                           parent,
                           wx.ID_ANY,
                           title,
                           style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER)
        self.mainFrame = mainFrame
        self.newFilterInfo = None
        # Filter name label
        filterLabel = wx.StaticText(self, wx.ID_ANY, filterName)
        font = filterLabel.GetFont()
        font.SetPointSize(10)
        font.SetWeight(wx.FONTWEIGHT_BOLD)
        filterLabel.SetFont(font)
        # Arguments
        argWindow = wx.ScrolledWindow(self, wx.ID_ANY, style=wx.TAB_TRAVERSAL)
        argWindow.SetScrollRate(10, 10)
        argSizer = wx.GridBagSizer(hgap=0, vgap=10)
        row = 0
        growable = False
        self.argctrls = []
        for argInfo in self.mainFrame.currentScript.GetFilterCalltipArgInfo(
                calltip=filterInfo):
            totalInfo, cArgType, cArgName, boolRepeatArg, boolOptionalArg, cArgInfo = argInfo
            argtype, argname, guitype, defaultValue, other = self.mainFrame.ParseCalltipArgInfo(
                totalInfo)
            #~ if guitype is None or argname is None or argtype not in ('int', 'float', 'bool', 'string'):
            if argname is None or argtype not in ('int', 'float', 'bool',
                                                  'string'):
                self.argctrls.append(
                    (argtype, argname, None, boolRepeatArg, boolOptionalArg))
            else:
                argLabel = wx.StaticText(argWindow, wx.ID_ANY,
                                         '%(argtype)s %(argname)s' % locals())
                argLabel.controls = []
                argSizer.Add(
                    argLabel, (row, 0), wx.DefaultSpan,
                    wx.ALIGN_RIGHT | wx.ALIGN_BOTTOM | wx.BOTTOM | wx.RIGHT, 5)
                if argtype in ('int', 'float') and guitype != 'intlist':
                    strDefaultValue = strMinValue = strMaxValue = strMod = ''
                    if other is not None:
                        minValue, maxValue, nDecimal, mod = other
                        if nDecimal is None:
                            nDecimal = 0
                        strTemplate = '%.' + str(nDecimal) + 'f'
                        if defaultValue is not None:
                            try:
                                strDefaultValue = strTemplate % defaultValue
                            except TypeError:
                                strDefaultValue = defaultValue
                        if minValue is not None:
                            try:
                                strMinValue = strTemplate % minValue
                            except TypeError:
                                strMinValue = minValue
                        if maxValue is not None:
                            try:
                                strMaxValue = strTemplate % maxValue
                            except TypeError:
                                strMaxValue = maxValue
                        if mod is not None:
                            try:
                                strMod = '%i' % mod
                            except TypeError:
                                strMod = mod
                    elif guitype == 'color':
                        strDefaultValue = '$%s' % defaultValue
                    itemData = (
                        (strDefaultValue, _('Default')),
                        (strMinValue, _('Min value')),
                        (strMaxValue, _('Max value')),
                        (strMod, _('Step size')),
                    )
                    hsizer = wx.BoxSizer(wx.HORIZONTAL)
                    for itemValue, itemName in itemData:
                        itemLabel = wx.StaticText(argWindow, wx.ID_ANY,
                                                  itemName)
                        itemTextCtrl = wx.TextCtrl(argWindow,
                                                   wx.ID_ANY,
                                                   itemValue,
                                                   size=(75, -1))
                        vsizer = wx.BoxSizer(wx.VERTICAL)
                        vsizer.Add(itemLabel, 0, wx.LEFT, 2)
                        vsizer.Add(itemTextCtrl, 0, wx.ALL, 0)
                        hsizer.Add(vsizer, 0, wx.EXPAND | wx.RIGHT, 5)
                        argLabel.controls.append(itemTextCtrl)
                    argSizer.Add(hsizer, (row, 1), wx.DefaultSpan,
                                 wx.ALIGN_CENTER_VERTICAL | wx.RIGHT, 0)
                elif argtype == 'bool':
                    strDefaultValue = ''
                    if defaultValue is not None:
                        if defaultValue.lower() == 'true':
                            strDefaultValue = 'True'
                        if defaultValue.lower() == 'false':
                            strDefaultValue = 'False'
                    itemLabel = wx.StaticText(argWindow, wx.ID_ANY,
                                              _('Default'))
                    itemTextCtrl = wx.ComboBox(argWindow,
                                               wx.ID_ANY,
                                               strDefaultValue,
                                               choices=['True', 'False'],
                                               style=wx.CB_DROPDOWN,
                                               size=(75, -1))
                    vsizer = wx.BoxSizer(wx.VERTICAL)
                    vsizer.Add(itemLabel, 0, wx.LEFT, 2)
                    vsizer.Add(itemTextCtrl, 0, wx.ALL, 0)
                    argLabel.controls.append(itemTextCtrl)
                    argSizer.Add(vsizer, (row, 1), wx.DefaultSpan,
                                 wx.ALIGN_CENTER_VERTICAL | wx.RIGHT, 0)
                elif argtype == 'string' or argtype == 'int' and guitype == 'intlist':
                    strDefaultValue = strValuesList = ''
                    if defaultValue is not None:
                        if defaultValue:
                            if argtype == 'string':
                                strDefaultValue = '"%s"' % defaultValue.strip(
                                    '"')
                            else:
                                strDefaultValue = str(defaultValue)
                    if other is not None:
                        strValuesList = ', '.join(other)
                    hsizer = wx.BoxSizer(wx.HORIZONTAL)
                    # Default control
                    itemLabel = wx.StaticText(argWindow, wx.ID_ANY,
                                              _('Default'))
                    itemTextCtrl = wx.TextCtrl(argWindow,
                                               wx.ID_ANY,
                                               strDefaultValue,
                                               size=(75, -1))
                    vsizer = wx.BoxSizer(wx.VERTICAL)
                    vsizer.Add(itemLabel, 0, wx.LEFT, 2)
                    vsizer.Add(itemTextCtrl, 0, wx.ALL, 0)
                    argLabel.controls.append(itemTextCtrl)
                    hsizer.Add(vsizer, 0, wx.EXPAND | wx.RIGHT, 5)
                    # Values control
                    itemLabel = wx.StaticText(
                        argWindow, wx.ID_ANY,
                        _('Value list (comma separated)'))
                    itemTextCtrl = wx.TextCtrl(argWindow,
                                               wx.ID_ANY,
                                               strValuesList,
                                               size=(200, -1))
                    vsizer = wx.BoxSizer(wx.VERTICAL)
                    vsizer.Add(itemLabel, 0, wx.LEFT, 2)
                    vsizer.Add(itemTextCtrl, 1, wx.EXPAND | wx.ALL, 0)
                    argLabel.controls.append(itemTextCtrl)
                    hsizer.Add(vsizer, 1, wx.EXPAND | wx.RIGHT, 5)

                    argSizer.Add(
                        hsizer, (row, 1), wx.DefaultSpan,
                        wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.RIGHT, 0)
                    if wx.VERSION > (2, 9):
                        if not argSizer.IsColGrowable(1):
                            argSizer.AddGrowableCol(1)
                    else:
                        if not growable:
                            argSizer.AddGrowableCol(1)
                            growable = True
                row += 1
                self.argctrls.append((argtype, argname, argLabel,
                                      boolRepeatArg, boolOptionalArg))
        argWindow.SetSizer(argSizer)
        # Standard buttons
        okay = wx.Button(self, wx.ID_OK, _('OK'))
        self.Bind(wx.EVT_BUTTON, self.OnButtonOK, okay)
        okay.SetDefault()
        cancel = wx.Button(self, wx.ID_CANCEL, _('Cancel'))
        btns = wx.StdDialogButtonSizer()
        btns.AddButton(okay)
        btns.AddButton(cancel)
        btns.Realize()
        # Set the sizer
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add((-1, -1), 0, wx.TOP, 10)
        sizer.Add(filterLabel, 0, wx.EXPAND | wx.ALL, 5)
        sizer.Add(wx.StaticLine(self, wx.ID_ANY), 0,
                  wx.EXPAND | wx.LEFT | wx.RIGHT, 5)
        sizer.Add(argWindow, 1, wx.EXPAND | wx.ALL, 5)
        sizer.Add(wx.StaticLine(self, wx.ID_ANY), 0,
                  wx.EXPAND | wx.LEFT | wx.RIGHT, 5)
        #~ sizer.Add(wx.StaticText(self,wx.ID_ANY, _('* optional value')), 0, wx.EXPAND|wx.ALL, 10)
        sizer.Add(btns, 0, wx.EXPAND | wx.ALL, 5)
        self.SetSizer(sizer)
        sizer.Layout()
        argWindow.FitInside()
        w, h = argSizer.GetMinSize()
        w = max(w + 10, 400)
        h = min(h + 100, 700)
        self.SetSize(self.ClientToWindowSize((w, h)))
        if argWindow.HasScrollbar(wx.HORIZONTAL):
            scrollbar_w = wx.SystemSettings_GetMetric(wx.SYS_VSCROLL_X)
            self.SetSize(self.ClientToWindowSize((w + scrollbar_w, -1)))
示例#60
0
    def __init__(self,
                 parent,
                 dlgInfo,
                 options,
                 defaults,
                 colour_data=None,
                 extra=None,
                 title=_('AviSynth fonts and colors')):
        wx.Dialog.__init__(self, parent, wx.ID_ANY, title)
        self.dlgInfo = dlgInfo
        self.options = options.copy()
        self.defaults = defaults
        self.colour_data = colour_data
        # Create the font buttons
        self.controls = {}
        self.controls2 = {}
        self.notebook = wxp.Notebook(
            self,
            wx.ID_ANY,
            style=wx.NO_BORDER,
            invert_scroll=self.GetParent().options['invertscrolling'])

        def OnNotebookPageChanged(event):
            event.GetEventObject().GetCurrentPage().SetFocus()
            event.Skip()

        for tabLabel, tabInfo in dlgInfo:
            tabPanel = wx.Panel(self.notebook, wx.ID_ANY)
            self.notebook.AddPage(tabPanel, tabLabel)
            sizer = wx.FlexGridSizer(cols=4, hgap=20, vgap=5)
            sizer.Add((0, 0), 0)
            for label in (_('Font'), _('Text color'), _('Background')):
                staticText = wx.StaticText(tabPanel, wx.ID_ANY, label)
                font = staticText.GetFont()
                font.SetUnderlined(True)
                font.SetWeight(wx.FONTWEIGHT_BOLD)
                staticText.SetFont(font)
                sizer.Add(staticText, flag=wx.ALIGN_CENTER)
            for label, key in tabInfo:
                (fontSize, fontStyle, fontWeight, fontUnderline, fontFace,
                 fontFore,
                 fontBack) = self.ParseStyleInfo(options[key].split(','))
                if fontFace is not None:
                    font = wx.Font(fontSize,
                                   wx.FONTFAMILY_DEFAULT,
                                   fontStyle,
                                   fontWeight,
                                   fontUnderline,
                                   faceName=fontFace)
                else:
                    font = None
                # Create the controls
                if type(label) is tuple:
                    label, optKey, tip = label
                    staticText = checkbox = wx.CheckBox(
                        tabPanel, wx.ID_ANY, label)
                    checkbox.SetValue(parent.options[optKey])
                    checkbox.SetToolTipString(tip)
                    self.controls2[optKey] = checkbox
                else:
                    staticText = wx.StaticText(tabPanel, wx.ID_ANY, label)
                if font is not None:
                    fontLabel = '%s, %d' % (fontFace, fontSize)
                    fontButton = wxButtons.GenButton(tabPanel,
                                                     wx.ID_ANY,
                                                     label=fontLabel)
                    fontButton.SetUseFocusIndicator(False)
                    fontButton.SetFont(font)
                    self.Bind(wx.EVT_BUTTON, self.OnButtonFont, fontButton)
                else:
                    fontButton = None
                if fontFore is not None:
                    #~ foreButton = wx.StaticText(tabPanel, wx.ID_ANY, size=(50, 20))
                    #~ foreButton.SetBackgroundColour(wx.Colour(*fontFore))
                    #~ foreButton.SetCursor(wx.StockCursor(wx.CURSOR_HAND))
                    #~ foreButton.Bind(wx.EVT_LEFT_UP, self.OnButtonColor)
                    foreButton = wxp.ColourSelect(tabPanel,
                                                  wx.ID_ANY,
                                                  colour=wx.Colour(*fontFore),
                                                  size=(50, 23),
                                                  colour_data=self.colour_data)
                else:
                    foreButton = None
                if fontBack is not None:
                    #~ backButton = wx.StaticText(tabPanel, wx.ID_ANY, size=(50, 20))
                    #~ backButton.SetBackgroundColour(wx.Colour(*fontBack))
                    #~ backButton.SetCursor(wx.StockCursor(wx.CURSOR_HAND))
                    #~ backButton.Bind(wx.EVT_LEFT_UP, self.OnButtonColor)
                    backButton = wxp.ColourSelect(tabPanel,
                                                  wx.ID_ANY,
                                                  colour=wx.Colour(*fontBack),
                                                  size=(50, 23),
                                                  colour_data=self.colour_data)
                else:
                    backButton = None
                sizer.Add(staticText, flag=wx.ALIGN_CENTER)
                if fontButton is not None:
                    sizer.Add(fontButton, flag=wx.ALIGN_CENTER)
                else:
                    sizer.Add((0, 0), flag=wx.ALIGN_CENTER)
                if foreButton is not None:
                    sizer.Add(foreButton, flag=wx.ALIGN_CENTER)
                else:
                    sizer.Add((0, 0), flag=wx.ALIGN_CENTER)
                if backButton is not None:
                    sizer.Add(backButton, flag=wx.ALIGN_CENTER)
                else:
                    sizer.Add((0, 0), flag=wx.ALIGN_CENTER)
                self.controls[key] = (fontButton, foreButton, backButton)
            tabSizer = wx.BoxSizer(wx.VERTICAL)
            tabSizer.Add(sizer, 0, wx.ALL, 10)
            tabPanel.SetSizerAndFit(tabSizer)
        self.notebook.SetSelection(0)
        # Standard (and not standard) buttons
        themes = [_('Select a predefined theme')
                  ] + parent.defaulttextstylesDict.keys()
        theme_choice = wx.Choice(self, choices=themes)
        theme_choice.SetSelection(0)
        self.Bind(wx.EVT_CHOICE, self.OnSelectTheme, theme_choice)
        only_colors_checkbox = wx.CheckBox(self, wx.ID_ANY,
                                           _('Only change colours'))
        only_colors_checkbox.SetValue(parent.options['theme_set_only_colors'])
        only_colors_checkbox.SetToolTipString(
            _("When selecting a theme, don't change current fonts"))
        self.controls2['theme_set_only_colors'] = only_colors_checkbox
        okay = wx.Button(self, wx.ID_OK, _('OK'))
        self.Bind(wx.EVT_BUTTON, self.OnButtonOK, okay)
        cancel = wx.Button(self, wx.ID_CANCEL, _('Cancel'))
        btns = wx.StdDialogButtonSizer()
        if extra:  # single CheckBox
            label, optKey, tip = extra
            checkbox = wx.CheckBox(self, wx.ID_ANY, label)
            checkbox.SetValue(parent.options[optKey])
            checkbox.SetToolTipString(tip)
            self.controls2[optKey] = checkbox
            btns.Add(checkbox, 0,
                     wx.LEFT | wx.RIGHT | wx.ALIGN_CENTER_VERTICAL, 3)
        btns.Add(theme_choice, 0, wx.LEFT | wx.RIGHT, 3)
        btns.Add(only_colors_checkbox, 0,
                 wx.LEFT | wx.RIGHT | wx.ALIGN_CENTER_VERTICAL, 3)
        btns.AddButton(okay)
        btns.AddButton(cancel)
        btns.Realize()
        # Size the elements
        dlgSizer = wx.BoxSizer(wx.VERTICAL)
        #~ dlgSizer.Add(sizer, 0, wx.EXPAND|wx.ALL, 5)
        dlgSizer.Add(self.notebook, 0, wx.EXPAND | wx.ALL, 5)
        dlgSizer.Add(btns, 0, wx.EXPAND | wx.ALL, 10)
        self.SetSizer(dlgSizer)
        dlgSizer.Fit(self)
        self.sizer = dlgSizer
        # Misc
        okay.SetDefault()
        self.Centre(wx.CENTRE_ON_SCREEN)