section stringlengths 2 30 | filename stringlengths 1 82 | text stringlengths 783 28M |
|---|---|---|
neubot | main_win32 | # neubot/main_win32.py
#
# Copyright (c) 2012 Simone Basso <bassosimone@gmail.com>,
# NEXA Center for Internet & Society at Politecnico di Torino
#
# This file is part of Neubot <http://www.neubot.org/>.
#
# Neubot is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Neubot is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Neubot. If not, see <http://www.gnu.org/licenses/>.
#
""" Win32 main() """
import getopt
import sys
if __name__ == "__main__":
sys.path.insert(0, ".")
from neubot import main_common, utils_ctl, utils_version
# Reference notifier so py2exe includes 'em
if sys.platform == "win32" and not hasattr(sys, "frozen"):
from neubot import notifier, raw
def subcommand_start(args):
"""Start subcommand"""
try:
options, arguments = getopt.getopt(args[1:], "k")
except getopt.error:
sys.exit("usage: neubot start [-k]")
if arguments:
sys.exit("usage: neubot start [-k]")
kill = False
for tpl in options:
if tpl[0] == "-k":
kill = True
#
# Wait for the parent to die, so that it closes the listening
# socket and we can successfully bind() it.
#
count = 0
while kill:
running = utils_ctl.is_running("127.0.0.1", "9774", quick=1)
if not running:
break
utils_ctl.stop("127.0.0.1", "9774")
count += 1
if count > 512:
sys.exit("FATAL: cannot stop neubot daemon")
# Lazy import
from neubot import background_win32
background_win32.main(["neubot"])
def subcommand_status(args):
"""Status subcommand"""
try:
options, arguments = getopt.getopt(args[1:], "v")
except getopt.error:
sys.exit("usage: neubot status [-v]")
if arguments:
sys.exit("usage: neubot status [-v]")
verbose = 0
for opt in options:
if opt[0] == "-v":
verbose = 1
running = utils_ctl.is_running("127.0.0.1", "9774")
if verbose:
if not running:
sys.stdout.write("Neubot is not running\n")
else:
sys.stdout.write("Neubot is running\n")
if not running:
sys.exit(1)
def subcommand_stop(args):
"""Stop subcommand"""
try:
options, arguments = getopt.getopt(args[1:], "")
except getopt.error:
sys.exit("usage: neubot stop")
if options or arguments:
sys.exit("usage: neubot stop")
running = utils_ctl.is_running("127.0.0.1", "9774")
if not running:
sys.exit("ERROR: neubot is not running")
utils_ctl.stop("127.0.0.1", "9774")
USAGE = """\
usage: neubot -h|--help
neubot -V
neubot start [-k]
neubot status [-v]
neubot stop
neubot subcommand [option]... [argument]...
"""
def main(args):
"""Main function"""
if len(args) == 1:
sys.stdout.write(USAGE)
main_common.print_subcommands(sys.stdout)
sys.exit(0)
del args[0]
subcommand = args[0]
if subcommand == "--help" or subcommand == "-h":
sys.stdout.write(USAGE)
main_common.print_subcommands(sys.stdout)
sys.exit(0)
if subcommand == "-V":
sys.stdout.write(utils_version.PRODUCT + "\n")
sys.exit(0)
if subcommand == "start":
subcommand_start(args)
sys.exit(0)
if subcommand == "status":
subcommand_status(args)
sys.exit(0)
if subcommand == "stop":
subcommand_stop(args)
sys.exit(0)
main_common.main(subcommand, args)
if __name__ == "__main__":
main(sys.argv)
|
gui | propertyEditor | import csv
import gui.builtinMarketBrowser.pfSearchBox as SBox
import gui.display as d
import gui.globalEvents as GE
# noinspection PyPackageRequirements
import wx
# noinspection PyPackageRequirements
import wx.propgrid as wxpg
from eos.db.gamedata.queries import getAttributeInfo, getItem
from gui.auxWindow import AuxiliaryFrame
from gui.bitmap_loader import BitmapLoader
from gui.marketBrowser import SearchBox
from logbook import Logger
from service.fit import Fit
from service.market import Market
pyfalog = Logger(__name__)
_t = wx.GetTranslation
class AttributeEditor(AuxiliaryFrame):
def __init__(self, parent):
super().__init__(
parent,
wx.ID_ANY,
title=_t("Attribute Editor"),
pos=wx.DefaultPosition,
size=wx.Size(650, 600),
resizeable=True,
)
i = wx.Icon(BitmapLoader.getBitmap("fit_rename_small", "gui"))
self.SetIcon(i)
self.mainFrame = parent
menubar = wx.MenuBar()
fileMenu = wx.Menu()
fileImport = fileMenu.Append(wx.ID_ANY, _t("Import"), _t("Import overrides"))
fileExport = fileMenu.Append(wx.ID_ANY, _t("Export"), _t("Import overrides"))
fileClear = fileMenu.Append(
wx.ID_ANY, _t("Clear All"), _t("Clear all overrides")
)
menubar.Append(fileMenu, _t("&File"))
self.SetMenuBar(menubar)
self.Bind(wx.EVT_MENU, self.OnImport, fileImport)
self.Bind(wx.EVT_MENU, self.OnExport, fileExport)
self.Bind(wx.EVT_MENU, self.OnClear, fileClear)
i = wx.Icon(BitmapLoader.getBitmap("fit_rename_small", "gui"))
self.SetIcon(i)
self.mainFrame = parent
self.panel = panel = wx.Panel(self, wx.ID_ANY)
mainSizer = wx.BoxSizer(wx.HORIZONTAL)
leftSizer = wx.BoxSizer(wx.VERTICAL)
leftPanel = wx.Panel(
panel,
wx.ID_ANY,
style=wx.DOUBLE_BORDER if "wxMSW" in wx.PlatformInfo else wx.SIMPLE_BORDER,
)
self.searchBox = SearchBox(leftPanel)
self.itemView = ItemView(leftPanel)
leftSizer.Add(self.searchBox, 0, wx.EXPAND)
leftSizer.Add(self.itemView, 1, wx.EXPAND)
leftPanel.SetSizer(leftSizer)
mainSizer.Add(leftPanel, 1, wx.ALL | wx.EXPAND, 5)
rightSizer = wx.BoxSizer(wx.VERTICAL)
self.btnRemoveOverrides = wx.Button(
panel,
wx.ID_ANY,
_t("Remove Overides for Item"),
wx.DefaultPosition,
wx.DefaultSize,
0,
)
self.pg = AttributeGrid(panel)
rightSizer.Add(self.pg, 1, wx.ALL | wx.EXPAND, 5)
rightSizer.Add(self.btnRemoveOverrides, 0, wx.ALL | wx.EXPAND, 5)
self.btnRemoveOverrides.Bind(wx.EVT_BUTTON, self.pg.removeOverrides)
self.btnRemoveOverrides.Enable(False)
mainSizer.Add(rightSizer, 1, wx.EXPAND)
panel.SetSizer(mainSizer)
mainSizer.SetSizeHints(panel)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(panel, 1, wx.EXPAND)
self.SetSizer(sizer)
self.SetAutoLayout(True)
self.SetMinSize(self.GetSize())
self.Bind(wx.EVT_CLOSE, self.OnClose)
self.Bind(wx.EVT_CHAR_HOOK, self.kbEvent)
def kbEvent(self, event):
if event.GetKeyCode() == wx.WXK_ESCAPE and event.GetModifiers() == wx.MOD_NONE:
self.Close()
return
event.Skip()
def OnClose(self, event):
fitID = self.mainFrame.getActiveFit()
if fitID is not None:
wx.PostEvent(self.mainFrame, GE.FitChanged(fitIDs=(fitID,)))
event.Skip()
def OnImport(self, event):
with wx.FileDialog(
self,
_t("Import pyfa override file"),
wildcard=_t("pyfa override file") + " (*.csv)|*.csv",
style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST,
) as dlg:
if dlg.ShowModal() == wx.ID_OK:
path = dlg.GetPath()
with open(path, "r") as csvfile:
spamreader = csv.reader(csvfile)
for row in spamreader:
if (
len(row) == 0
): # csvwriter seems to added blank lines to the end sometimes
continue
itemID, attrID, value = row
item = getItem(int(itemID))
attr = getAttributeInfo(int(attrID))
item.setOverride(attr, float(value))
self.itemView.updateItems(True)
def OnExport(self, event):
sMkt = Market.getInstance()
items = sMkt.getItemsWithOverrides()
defaultFile = "pyfa_overrides.csv"
with wx.FileDialog(
self,
_t("Save Overrides As..."),
wildcard=_t("pyfa overrides") + " (*.csv)|*.csv",
style=wx.FD_SAVE,
defaultFile=defaultFile,
) as dlg:
if dlg.ShowModal() == wx.ID_OK:
path = dlg.GetPath()
with open(path, "w", encoding="utf-8") as csvfile:
writer = csv.writer(csvfile)
for item in items:
for key, override in item.overrides.items():
writer.writerow([item.ID, override.attrID, override.value])
def OnClear(self, event):
with wx.MessageDialog(
self,
_t("Are you sure you want to delete all overrides?"),
_t("Confirm Delete"),
wx.YES | wx.NO | wx.ICON_EXCLAMATION,
) as dlg:
if dlg.ShowModal() == wx.ID_YES:
sMkt = Market.getInstance()
items = sMkt.getItemsWithOverrides()
# We can't just delete overrides, as loaded items will still have
# them assigned. Deleting them from the database won't propagate
# them due to the eve/user database disconnect. We must loop through
# all items that have overrides and remove them
for item in items:
for _, x in list(item.overrides.items()):
item.deleteOverride(x.attr)
self.itemView.updateItems(True)
self.pg.Clear()
# This is literally a stripped down version of the market.
class ItemView(d.Display):
DEFAULT_COLS = ["Base Icon", "Base Name", "attr:power,,,True", "attr:cpu,,,True"]
def __init__(self, parent):
d.Display.__init__(self, parent)
self.activeItems = []
self.searchTimer = wx.Timer(self)
self.Bind(wx.EVT_TIMER, self.scheduleSearch, self.searchTimer)
self.searchBox = parent.Parent.Parent.searchBox
# Bind search actions
self.searchBox.Bind(SBox.EVT_TEXT_ENTER, self.scheduleSearch)
self.searchBox.Bind(SBox.EVT_SEARCH_BTN, self.scheduleSearch)
self.searchBox.Bind(SBox.EVT_CANCEL_BTN, self.clearSearch)
self.searchBox.Bind(SBox.EVT_TEXT, self.delaySearch)
self.update(Market.getInstance().getItemsWithOverrides())
def clearSearch(self, event=None):
if event:
self.searchBox.Clear()
self.update(Market.getInstance().getItemsWithOverrides())
def updateItems(self, updateDisplay=False):
if updateDisplay:
self.update(Market.getInstance().getItemsWithOverrides())
def delaySearch(self, evt):
sFit = Fit.getInstance()
self.searchTimer.Stop()
self.searchTimer.Start(sFit.serviceFittingOptions["marketSearchDelay"], True)
def scheduleSearch(self, event=None):
sMkt = Market.getInstance()
search = self.searchBox.GetLineText(0)
# Make sure we do not count wildcards as search symbol
realsearch = search.replace("*", "").replace("?", "")
# Show nothing if query is too short
if len(realsearch) < 3:
self.clearSearch()
return
sMkt.searchItems(search, self.populateSearch, "everything")
def itemSort(self, item):
sMkt = Market.getInstance()
isFittable = (
item.group.name in sMkt.FIT_GROUPS
or item.category.name in sMkt.FIT_CATEGORIES
)
return (not isFittable, *sMkt.itemSort(item))
def populateSearch(self, itemIDs):
items = Market.getItems(itemIDs)
self.update(items)
def populate(self, items):
if len(items) > 0:
self.unselectAll()
items.sort(key=self.itemSort)
self.activeItems = items
d.Display.populate(self, items)
def refresh(self, items):
if len(items) > 1:
items.sort(key=self.itemSort)
d.Display.refresh(self, items)
class AttributeGrid(wxpg.PropertyGrid):
def __init__(self, parent):
wxpg.PropertyGrid.__init__(
self,
parent,
style=wxpg.PG_HIDE_MARGIN
| wxpg.PG_HIDE_CATEGORIES
| wxpg.PG_BOLD_MODIFIED
| wxpg.PG_TOOLTIPS,
)
self.SetExtraStyle(wxpg.PG_EX_HELP_AS_TOOLTIPS)
self.item = None
self.itemView = parent.Parent.itemView
self.btn = parent.Parent.btnRemoveOverrides
self.Bind(wxpg.EVT_PG_CHANGED, self.OnPropGridChange)
self.Bind(wxpg.EVT_PG_SELECTED, self.OnPropGridSelect)
self.Bind(wxpg.EVT_PG_RIGHT_CLICK, self.OnPropGridRightClick)
self.itemView.Bind(wx.EVT_LIST_ITEM_SELECTED, self.itemActivated)
self.itemView.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.itemActivated)
def itemActivated(self, event):
self.Clear()
self.btn.Enable(True)
sel = event.EventObject.GetFirstSelected()
self.item = item = self.itemView.activeItems[sel]
for key in sorted(item.attributes.keys()):
override = item.overrides.get(key, None)
default = item.attributes[key].value
if override and override.value != default:
prop = wxpg.FloatProperty(key, value=override.value)
prop.SetModifiedStatus(True)
else:
prop = wxpg.FloatProperty(key, value=default)
prop.SetClientData(
item.attributes[key]
) # set this so that we may access it later
prop.SetHelpString(
"%s\n%s"
% (
item.attributes[key].displayName or key,
_t("Default Value: %0.3f") % default,
)
)
self.Append(prop)
def removeOverrides(self, event):
if self.item is None:
return
for x in list(self.item.overrides.values()):
self.item.deleteOverride(x.attr)
self.itemView.updateItems(True)
self.ClearModifiedStatus()
self.itemView.Select(self.itemView.GetFirstSelected(), on=False)
self.Clear()
def Clear(self):
self.item = None
self.btn.Enable(False)
wxpg.PropertyGrid.Clear(self)
def OnPropGridChange(self, event):
p = event.GetProperty()
attr = p.GetClientData()
if p.GetValue() == attr.value:
self.item.deleteOverride(attr)
p.SetModifiedStatus(False)
else:
self.item.setOverride(attr, p.GetValue())
self.itemView.updateItems()
pyfalog.debug('{0} changed to "{1}"', p.GetName(), p.GetValueAsString())
def OnPropGridSelect(self, event):
pass
def OnPropGridRightClick(self, event):
pass
|
scripting | keyboard | # Copyright (C) 2011 Chris Dekter
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""Keyboard Functions"""
import typing
from typing import Callable
import autokey.iomediator.waiter
import autokey.model.phrase
from autokey import iomediator, model
class Keyboard:
"""
Provides access to the keyboard for event generation.
"""
SendMode = autokey.model.phrase.SendMode
def __init__(self, mediator):
"""Initialize the Keyboard"""
self.mediator = mediator # type: iomediator.IoMediator
"""See C{IoMediator} documentation"""
def send_keys(
self,
key_string,
send_mode: typing.Union[
autokey.model.phrase.SendMode, int
] = autokey.model.phrase.SendMode.KEYBOARD,
):
"""
Send a sequence of keys via keyboard events as the default or via clipboard pasting.
Because the clipboard can only contain
printable characters, special keys and embedded key combinations can only be sent in keyboard mode.
Trying to send special keys using a clipboard pasting method will paste the literal representation
(e.g. "<ctrl>+<f11>") instead of the actual special key or key combination.
Usage: C{keyboard.send_keys(keyString)}
@param key_string: string of keys to send. Special keys are only possible in keyboard mode.
@param send_mode: Determines how the string is sent.
"""
if not isinstance(key_string, str):
raise TypeError("Only strings can be sent using this function")
send_mode = _validate_send_mode(send_mode)
self.mediator.interface.begin_send()
try:
if send_mode is autokey.model.phrase.SendMode.KEYBOARD:
self.mediator.send_string(key_string)
else:
self.mediator.paste_string(key_string, send_mode)
finally:
self.mediator.interface.finish_send()
def send_key(self, key, repeat=1):
"""
Send a keyboard event
Usage: C{keyboard.send_key(key, repeat=1)}
@param key: the key to be sent (e.g. "s" or "<enter>")
@param repeat: number of times to repeat the key event
"""
for _ in range(repeat):
self.mediator.send_key(key)
self.mediator.flush()
def press_key(self, key):
"""
Send a key down event
Usage: C{keyboard.press_key(key)}
The key will be treated as down until a matching release_key() is sent.
@param key: the key to be pressed (e.g. "s" or "<enter>")
"""
self.mediator.press_key(key)
def release_key(self, key):
"""
Send a key up event
Usage: C{keyboard.release_key(key)}
If the specified key was not made down using press_key(), the event will be
ignored.
@param key: the key to be released (e.g. "s" or "<enter>")
"""
self.mediator.release_key(key)
def fake_keypress(self, key, repeat=1):
"""
Fake a keypress
Usage: C{keyboard.fake_keypress(key, repeat=1)}
Uses XTest to 'fake' a keypress. This is useful to send keypresses to some
applications which won't respond to keyboard.send_key()
@param key: the key to be sent (e.g. "s" or "<enter>")
@param repeat: number of times to repeat the key event
"""
for _ in range(repeat):
self.mediator.fake_keypress(key)
def wait_for_keypress(self, key, modifiers: list = None, timeOut=10.0):
"""
Wait for a keypress or key combination
Usage: C{keyboard.wait_for_keypress(self, key, modifiers=[], timeOut=10.0)}
Note: this function cannot be used to wait for modifier keys on their own
@param key: the key to wait for
@param modifiers: list of modifiers that should be pressed with the key
@param timeOut: maximum time, in seconds, to wait for the keypress to occur
"""
if modifiers is None:
modifiers = []
w = self.mediator.waiter(key, modifiers, None, None, None, timeOut)
self.mediator.listeners.append(w)
rtn = w.wait()
self.mediator.listeners.remove(w)
return rtn
def wait_for_keyevent(
self,
check: Callable[[any, str, list, str], bool],
name: str = None,
timeOut=10.0,
):
"""
Wait for a key event, potentially accumulating the intervening characters
Usage: C{keyboard.wait_for_keypress(self, check, name=None, timeOut=10.0)}
@param check: a function that returns True or False to signify we've finished waiting
@param name: only one waiter can have this name. Used to prevent more threads waiting on this.
@param timeOut: maximum time, in seconds, to wait for the keypress to occur
Example:
# Accumulate the traditional emacs C-u prefix arguments
# See https://www.gnu.org/software/emacs/manual/html_node/elisp/Prefix-Command-Arguments.html
def check(waiter,rawKey,modifiers,key,*args):
isCtrlU = (key == 'u' and len(modifiers) == 1 and modifiers[0] == '<ctrl>')
if isCtrlU: # If we get here, they've already pressed C-u at least 2x
try:
val = int(waiter.result) * 4
waiter.result = str(val)
except ValueError:
waiter.result = "16"
return False
elif any(m == "<ctrl>" or m == "<alt>" or m == "<meta>" or m == "<super>" or m == "<hyper>" for m in modifiers):
# Some other control character is an indication we're done.
if waiter.result is None or waiter.result == "":
waiter.result = "4"
store.set_global_value("emacs-prefix-arg", waiter.result)
return True
else: # accumulate as a string
waiter.result = waiter.result + key
return False
keyboard.wait_for_keyevent(check, "emacs-prefix")
"""
if name is None or not any(
elem.name == name for elem in self.mediator.listeners
):
w = self.mediator.waiter(None, None, None, check, name, timeOut)
self.mediator.listeners.append(w)
rtn = w.wait()
self.mediator.listeners.remove(w)
return rtn
return False
def _validate_send_mode(send_mode):
permissible_values = "\n".join(
"keyboard.{}".format(mode) for mode in map(str, autokey.model.phrase.SendMode)
)
if isinstance(send_mode, int):
if send_mode in range(len(autokey.model.phrase.SendMode)):
send_mode = tuple(autokey.model.phrase.SendMode)[send_mode] # type: model.SendMode
else:
permissible_values = "\n".join(
"{}: keyboard.{}".format(number, str(constant))
for number, constant in enumerate(autokey.model.phrase.SendMode)
)
raise ValueError(
"send_mode out of range for index-based access. "
"Permissible values are:\n{}".format(permissible_values)
)
elif isinstance(send_mode, str):
try:
send_mode = autokey.model.phrase.SendMode(send_mode)
except ValueError as v:
raise ValueError("Permissible values are: " + permissible_values) from v
elif send_mode is None: # Selection has value None
send_mode = autokey.model.phrase.SendMode.SELECTION
elif not isinstance(send_mode, autokey.model.phrase.SendMode):
raise TypeError(
"Unsupported type for send_mode parameter: {} Use one of: {}".format(
send_mode, permissible_values
)
)
return send_mode
|
migrations | 0008_userpreferences | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-03-23 19:08
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
("deposit", "0007_remove_urls_and_add_oairecord"),
]
operations = [
migrations.CreateModel(
name="UserPreferences",
fields=[
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
(
"last_repository",
models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.CASCADE,
related_name="last_used_by",
to="deposit.Repository",
),
),
(
"preferred_repository",
models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.CASCADE,
related_name="preferrend_by",
to="deposit.Repository",
),
),
(
"user",
models.OneToOneField(
on_delete=django.db.models.deletion.CASCADE,
to=settings.AUTH_USER_MODEL,
),
),
],
),
]
|
ui | lineNumberRulerView | import math
from AppKit import (
NSBezierPath,
NSColor,
NSFont,
NSFontAttributeName,
NSForegroundColorAttributeName,
NSMiniControlSize,
NSNotificationCenter,
NSRectFill,
NSRulerView,
NSTextStorageDidProcessEditingNotification,
NSTextView,
NSViewBoundsDidChangeNotification,
)
from Foundation import (
NSHeight,
NSInvocation,
NSLocationInRange,
NSMakeRange,
NSMakeRect,
NSMaxRange,
NSMinY,
NSNotFound,
NSString,
NSWidth,
)
from objc import super
"""
Based/translated from NoodleLineNumberView
http://www.noodlesoft.com/blog/2008/10/05/displaying-line-numbers-with-nstextview/
"""
class LineNumberNSRulerView(NSRulerView):
DEFAULT_THICKNESS = 22.0
RULER_MARGIN = 5.0
def init(self):
self = super(LineNumberNSRulerView, self).init()
self._font = NSFont.labelFontOfSize_(
NSFont.systemFontSizeForControlSize_(NSMiniControlSize)
)
self._textColor = NSColor.colorWithCalibratedWhite_alpha_(0.42, 1)
self._rulerBackgroundColor = None
self._lineIndices = None
return self
def setFont_(self, font):
self._font = font
def font(self):
return self._font
def setTextColor_(self, color):
self._textColor = color
self.setNeedsDisplay_(True)
def textColor(self):
return self._textColor
def textAttributes(self):
return {
NSFontAttributeName: self.font(),
NSForegroundColorAttributeName: self.textColor(),
}
def setRulerBackgroundColor_(self, color):
self._rulerBackgroundColor = color
self.setNeedsDisplay_(True)
def rulerBackgroundColor(self):
return self._rulerBackgroundColor
def setClientView_(self, view):
oldClientView = self.clientView()
if oldClientView != view and isinstance(oldClientView, NSTextView):
NSNotificationCenter.defaultCenter().removeObserver_name_object_(
self,
NSTextStorageDidProcessEditingNotification,
oldClientView.textStorage(),
)
super(LineNumberNSRulerView, self).setClientView_(view)
if view is not None and isinstance(view, NSTextView):
NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(
self,
"textDidChange:",
NSTextStorageDidProcessEditingNotification,
view.textStorage(),
)
NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(
self,
"textViewBoundsChange:",
NSViewBoundsDidChangeNotification,
view.enclosingScrollView().contentView(),
)
def lineIndices(self):
if self._lineIndices is None:
self.calculateLines()
return self._lineIndices
def invalidateLineIndices(self):
self._lineIndices = None
def textDidChange_(self, sender):
self.calculateLines()
self.invalidateLineIndices()
self.setNeedsDisplay_(True)
def textViewBoundsChange_(self, sender):
self.setNeedsDisplay_(True)
def dealloc(self):
# make sure we remove ourselves as an observer of the text storage
NSNotificationCenter.defaultCenter().removeObserver_(self)
super(LineNumberNSRulerView, self).dealloc()
def calculateLines(self):
view = self.clientView()
if not isinstance(view, NSTextView):
return
text = view.string()
textLength = text.length()
if not textLength:
self._lineIndices = [1]
return
lineIndices = []
index = 0
numberOfLines = 0
while index < textLength:
lineIndices.append(index)
index = NSMaxRange(text.lineRangeForRange_(NSMakeRange(index, 0)))
numberOfLines += 1
lineStart, lineEnd, contentEnd = text.getLineStart_end_contentsEnd_forRange_(
None, None, None, NSMakeRange(lineIndices[-1], 0)
)
if contentEnd < lineEnd:
lineIndices.append(index)
self._lineIndices = lineIndices
oldThickness = self.ruleThickness()
newThickness = self.requiredThickness()
if abs(oldThickness - newThickness) > 0:
invocation = NSInvocation.invocationWithMethodSignature_(
self.methodSignatureForSelector_("setRuleThickness:")
)
invocation.setSelector_("setRuleThickness:")
invocation.setTarget_(self)
invocation.setArgument_atIndex_(newThickness, 2)
invocation.performSelector_withObject_afterDelay_("invoke", None, 0)
def requiredThickness(self):
lineCount = len(self.lineIndices())
digits = int(math.log10(lineCount) + 1)
sampleString = NSString.stringWithString_("8" * digits)
stringSize = sampleString.sizeWithAttributes_(self.textAttributes())
return math.ceil(
max([self.DEFAULT_THICKNESS, stringSize.width + self.RULER_MARGIN * 2])
)
def lineNumberForCharacterIndex_inText_(self, index, text):
lines = self.lineIndices()
left = 0
right = len(lines)
while (right - left) > 1:
mid = (right + left) // 2
lineStart = lines[mid]
if index < lineStart:
right = mid
elif index > lineStart:
left = mid
else:
return mid
return left
def drawHashMarksAndLabelsInRect_(self, rect):
bounds = self.bounds()
view = self.clientView()
rulerBackgroundColor = self.rulerBackgroundColor()
if rulerBackgroundColor is not None:
rulerBackgroundColor.set()
NSRectFill(bounds)
if not isinstance(view, NSTextView):
return
layoutManager = view.layoutManager()
container = view.textContainer()
text = view.string()
nullRange = NSMakeRange(NSNotFound, 0)
yinset = view.textContainerInset().height
visibleRect = self.scrollView().contentView().bounds()
textAttributes = self.textAttributes()
lines = self.lineIndices()
glyphRange = layoutManager.glyphRangeForBoundingRect_inTextContainer_(
visibleRect, container
)
_range = layoutManager.characterRangeForGlyphRange_actualGlyphRange_(
glyphRange, None
)[0]
_range.length += 1
count = len(lines)
index = 0
lineNumber = self.lineNumberForCharacterIndex_inText_(_range.location, text)
for line in range(lineNumber, count):
index = lines[line]
if NSLocationInRange(index, _range):
(
rects,
rectCount,
) = layoutManager.rectArrayForCharacterRange_withinSelectedCharacterRange_inTextContainer_rectCount_(
NSMakeRange(index, 0), nullRange, container, None
)
if rectCount > 0:
ypos = yinset + NSMinY(rects[0]) - NSMinY(visibleRect)
labelText = NSString.stringWithString_("%s" % (line + 1))
stringSize = labelText.sizeWithAttributes_(textAttributes)
x = NSWidth(bounds) - stringSize.width - self.RULER_MARGIN
y = ypos + (NSHeight(rects[0]) - stringSize.height) / 2.0
w = NSWidth(bounds) - self.RULER_MARGIN * 2.0
h = NSHeight(rects[0])
labelText.drawInRect_withAttributes_(
NSMakeRect(x, y, w, h), textAttributes
)
if index > NSMaxRange(_range):
break
path = NSBezierPath.bezierPath()
path.moveToPoint_((bounds.origin.x + bounds.size.width, bounds.origin.y))
path.lineToPoint_(
(bounds.origin.x + bounds.size.width, bounds.origin.y + bounds.size.height)
)
NSColor.grayColor().set()
path.stroke()
|
SCL | Rules | # Copyright (c) 2011-2012, Thomas Paviot (tpaviot@gmail.com)
# All rights reserved.
# This file is part of the StepClassLibrary (SCL).
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# Neither the name of the <ORGANIZATION> nor the names of its contributors may
# be used to endorse or promote products derived from this software without
# specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED.
# IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
__doc__ = "This module defines EXPRESS rules"
class Rule(object):
"""
This class describes a RULE
@TODO: to be implemented
"""
pass
|
ui | caa_types_selector | # -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2007 Oliver Charles
# Copyright (C) 2007, 2010-2011 Lukáš Lalinský
# Copyright (C) 2007-2011, 2015, 2018-2023 Philipp Wolfer
# Copyright (C) 2011 Michael Wiencek
# Copyright (C) 2011-2012 Wieland Hoffmann
# Copyright (C) 2013-2015, 2018-2023 Laurent Monin
# Copyright (C) 2015-2016 Rahul Raturi
# Copyright (C) 2016-2017 Sambhav Kothari
# Copyright (C) 2017 Frederik “Freso” S. Olesen
# Copyright (C) 2018 Bob Swift
# Copyright (C) 2018 Vishal Choudhary
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from functools import partial
from picard.ui import PicardDialog
from picard.ui.util import StandardButton, qlistwidget_items
from PyQt5 import QtCore, QtGui, QtWidgets
class ArrowButton(QtWidgets.QPushButton):
"""Standard arrow button for CAA image type selection dialog.
Keyword Arguments:
label {string} -- Label to display on the button
command {command} -- Command to execute when the button is clicked (default: {None})
parent {[type]} -- Parent of the QPushButton object being created (default: {None})
"""
def __init__(self, icon_name, command=None, parent=None):
icon = QtGui.QIcon(":/images/16x16/" + icon_name + ".png")
super().__init__(icon, "", parent=parent)
if command is not None:
self.clicked.connect(command)
class ArrowsColumn(QtWidgets.QWidget):
"""Standard arrow buttons column for CAA image type selection dialog.
Keyword Arguments:
selection_list {ListBox} -- ListBox of selected items associated with this arrow column
ignore_list {ListBox} -- ListBox of unselected items associated with this arrow column
callback {command} -- Command to execute after items are moved between lists (default: {None})
reverse {bool} -- Determines whether the arrow directions should be reversed (default: {False})
parent {[type]} -- Parent of the QWidget object being created (default: {None})
"""
def __init__(
self, selection_list, ignore_list, callback=None, reverse=False, parent=None
):
super().__init__(parent=parent)
self.selection_list = selection_list
self.ignore_list = ignore_list
self.callback = callback
spacer_item = QtWidgets.QSpacerItem(
20,
20,
QtWidgets.QSizePolicy.Policy.Minimum,
QtWidgets.QSizePolicy.Policy.Expanding,
)
arrows_layout = QtWidgets.QVBoxLayout()
arrows_layout.addItem(QtWidgets.QSpacerItem(spacer_item))
self.button_add = ArrowButton(
"go-next" if reverse else "go-previous", self.move_from_ignore
)
arrows_layout.addWidget(self.button_add)
self.button_add_all = ArrowButton(
"move-all-right" if reverse else "move-all-left", self.move_all_from_ignore
)
arrows_layout.addWidget(self.button_add_all)
self.button_remove = ArrowButton(
"go-previous" if reverse else "go-next", self.move_to_ignore
)
arrows_layout.addWidget(self.button_remove)
self.button_remove_all = ArrowButton(
"move-all-left" if reverse else "move-all-right", self.move_all_to_ignore
)
arrows_layout.addWidget(self.button_remove_all)
arrows_layout.addItem(QtWidgets.QSpacerItem(spacer_item))
self.setLayout(arrows_layout)
def move_from_ignore(self):
self.ignore_list.move_selected_items(
self.selection_list, callback=self.callback
)
def move_all_from_ignore(self):
self.ignore_list.move_all_items(self.selection_list, callback=self.callback)
def move_to_ignore(self):
self.selection_list.move_selected_items(
self.ignore_list, callback=self.callback
)
def move_all_to_ignore(self):
self.selection_list.move_all_items(self.ignore_list, callback=self.callback)
class ListBox(QtWidgets.QListWidget):
"""Standard list box for CAA image type selection dialog.
Keyword Arguments:
parent {[type]} -- Parent of the QListWidget object being created (default: {None})
"""
LISTBOX_WIDTH = 100
LISTBOX_HEIGHT = 250
def __init__(self, parent=None):
super().__init__(parent=parent)
self.setMinimumSize(QtCore.QSize(self.LISTBOX_WIDTH, self.LISTBOX_HEIGHT))
self.setSizePolicy(
QtWidgets.QSizePolicy.Policy.MinimumExpanding,
QtWidgets.QSizePolicy.Policy.Expanding,
)
self.setSortingEnabled(True)
self.setSelectionMode(
QtWidgets.QAbstractItemView.SelectionMode.ExtendedSelection
)
def move_item(self, item, target_list):
"""Move the specified item to another listbox."""
self.takeItem(self.row(item))
target_list.addItem(item)
def move_selected_items(self, target_list, callback=None):
"""Move the selected item to another listbox."""
for item in self.selectedItems():
self.move_item(item, target_list)
if callback:
callback()
def move_all_items(self, target_list, callback=None):
"""Move all items to another listbox."""
while self.count():
self.move_item(self.item(0), target_list)
if callback:
callback()
def all_items_data(self, role=QtCore.Qt.ItemDataRole.UserRole):
for item in qlistwidget_items(self):
yield item.data(role)
class CAATypesSelectorDialog(PicardDialog):
"""Display dialog box to select the CAA image types to include and exclude from download and use.
Keyword Arguments:
parent {[type]} -- Parent of the QDialog object being created (default: {None})
types_include {[string]} -- List of CAA image types to include (default: {None})
types_exclude {[string]} -- List of CAA image types to exclude (default: {None})
default_include {[string]} -- List of CAA image types to include by default (default: {None})
default_exclude {[string]} -- List of CAA image types to exclude by default (default: {None})
known_types {{string: string}} -- Dict. of all known CAA image types, unique name as key, translated title as value (default: {None})
"""
help_url = "doc_cover_art_types"
def __init__(
self,
parent=None,
types_include=None,
types_exclude=None,
default_include=None,
default_exclude=None,
known_types=None,
):
super().__init__(parent)
if types_include is None:
types_include = []
if types_exclude is None:
types_exclude = []
self._default_include = default_include or []
self._default_exclude = default_exclude or []
self._known_types = known_types or {}
self.setWindowTitle(_("Cover art types"))
self.setWindowModality(QtCore.Qt.WindowModality.WindowModal)
self.layout = QtWidgets.QVBoxLayout(self)
self.layout.setSizeConstraint(QtWidgets.QLayout.SizeConstraint.SetFixedSize)
# Create list boxes for dialog
self.list_include = ListBox()
self.list_exclude = ListBox()
self.list_ignore = ListBox()
# Populate list boxes from current settings
self.fill_lists(types_include, types_exclude)
# Set triggers when the lists receive the current focus
self.list_include.clicked.connect(
partial(self.clear_focus, [self.list_ignore, self.list_exclude])
)
self.list_exclude.clicked.connect(
partial(self.clear_focus, [self.list_ignore, self.list_include])
)
self.list_ignore.clicked.connect(
partial(self.clear_focus, [self.list_include, self.list_exclude])
)
# Add instructions to the dialog box
instructions = QtWidgets.QLabel()
instructions.setText(
_(
"Please select the contents of the image type 'Include' and 'Exclude' lists."
)
)
instructions.setWordWrap(True)
instructions.setSizePolicy(
QtWidgets.QSizePolicy.Policy.Expanding,
QtWidgets.QSizePolicy.Policy.Expanding,
)
self.layout.addWidget(instructions)
self.arrows_include = ArrowsColumn(
self.list_include,
self.list_ignore,
callback=self.set_buttons_enabled_state,
)
self.arrows_exclude = ArrowsColumn(
self.list_exclude,
self.list_ignore,
callback=self.set_buttons_enabled_state,
reverse=True,
)
lists_layout = QtWidgets.QHBoxLayout()
include_list_layout = QtWidgets.QVBoxLayout()
include_list_layout.addWidget(QtWidgets.QLabel(_("Include types list")))
include_list_layout.addWidget(self.list_include)
lists_layout.addLayout(include_list_layout)
lists_layout.addWidget(self.arrows_include)
ignore_list_layout = QtWidgets.QVBoxLayout()
ignore_list_layout.addWidget(QtWidgets.QLabel(""))
ignore_list_layout.addWidget(self.list_ignore)
lists_layout.addLayout(ignore_list_layout)
lists_layout.addWidget(self.arrows_exclude)
exclude_list_layout = QtWidgets.QVBoxLayout()
exclude_list_layout.addWidget(QtWidgets.QLabel(_("Exclude types list")))
exclude_list_layout.addWidget(self.list_exclude)
lists_layout.addLayout(exclude_list_layout)
self.layout.addLayout(lists_layout)
# Add usage explanation to the dialog box
instructions = QtWidgets.QLabel()
instructions.setText(
_(
"CAA images with an image type found in the 'Include' list will be downloaded and used "
"UNLESS they also have an image type found in the 'Exclude' list. Images with types "
"found in the 'Exclude' list will NEVER be used. Image types not appearing in the 'Include' "
"or 'Exclude' lists will not be considered when determining whether or not to download and "
"use a CAA image.\n"
)
)
instructions.setWordWrap(True)
instructions.setSizePolicy(
QtWidgets.QSizePolicy.Policy.Expanding,
QtWidgets.QSizePolicy.Policy.Expanding,
)
self.layout.addWidget(instructions)
self.buttonbox = QtWidgets.QDialogButtonBox(self)
self.buttonbox.setOrientation(QtCore.Qt.Orientation.Horizontal)
self.buttonbox.addButton(
StandardButton(StandardButton.OK),
QtWidgets.QDialogButtonBox.ButtonRole.AcceptRole,
)
self.buttonbox.addButton(
StandardButton(StandardButton.CANCEL),
QtWidgets.QDialogButtonBox.ButtonRole.RejectRole,
)
self.buttonbox.addButton(
StandardButton(StandardButton.HELP),
QtWidgets.QDialogButtonBox.ButtonRole.HelpRole,
)
extrabuttons = [
(N_("I&nclude all"), self.move_all_to_include_list),
(N_("E&xclude all"), self.move_all_to_exclude_list),
(N_("C&lear all"), self.move_all_to_ignore_list),
(N_("Restore &Defaults"), self.reset_to_defaults),
]
for label, callback in extrabuttons:
button = QtWidgets.QPushButton(_(label))
self.buttonbox.addButton(
button, QtWidgets.QDialogButtonBox.ButtonRole.ActionRole
)
button.clicked.connect(callback)
self.layout.addWidget(self.buttonbox)
self.buttonbox.accepted.connect(self.accept)
self.buttonbox.rejected.connect(self.reject)
self.buttonbox.helpRequested.connect(self.show_help)
self.set_buttons_enabled_state()
def move_all_to_include_list(self):
self.list_ignore.move_all_items(self.list_include)
self.list_exclude.move_all_items(self.list_include)
self.set_buttons_enabled_state()
def move_all_to_exclude_list(self):
self.list_ignore.move_all_items(self.list_exclude)
self.list_include.move_all_items(self.list_exclude)
self.set_buttons_enabled_state()
def move_all_to_ignore_list(self):
self.list_include.move_all_items(self.list_ignore)
self.list_exclude.move_all_items(self.list_ignore)
self.set_buttons_enabled_state()
def fill_lists(self, includes, excludes):
"""Fill dialog listboxes.
First clears the contents of the three listboxes, and then populates the listboxes
from the dictionary of standard CAA types, using the provided 'includes' and
'excludes' lists to determine the appropriate list for each type.
Arguments:
includes -- list of standard image types to place in the "Include" listbox
excludes -- list of standard image types to place in the "Exclude" listbox
"""
self.list_include.clear()
self.list_exclude.clear()
self.list_ignore.clear()
for name, title in self._known_types.items():
item = QtWidgets.QListWidgetItem(title)
item.setData(QtCore.Qt.ItemDataRole.UserRole, name)
if name in includes:
self.list_include.addItem(item)
elif name in excludes:
self.list_exclude.addItem(item)
else:
self.list_ignore.addItem(item)
@property
def included(self):
return list(self.list_include.all_items_data()) or ["front"]
@property
def excluded(self):
return list(self.list_exclude.all_items_data()) or ["none"]
def clear_focus(self, lists):
for temp_list in lists:
temp_list.clearSelection()
self.set_buttons_enabled_state()
def reset_to_defaults(self):
self.fill_lists(self._default_include, self._default_exclude)
self.set_buttons_enabled_state()
def set_buttons_enabled_state(self):
has_items_include = self.list_include.count()
has_items_exclude = self.list_exclude.count()
has_items_ignore = self.list_ignore.count()
has_selected_include = bool(self.list_include.selectedItems())
has_selected_exclude = bool(self.list_exclude.selectedItems())
has_selected_ignore = bool(self.list_ignore.selectedItems())
# "Include" list buttons
self.arrows_include.button_add.setEnabled(
has_items_ignore and has_selected_ignore
)
self.arrows_include.button_add_all.setEnabled(has_items_ignore)
self.arrows_include.button_remove.setEnabled(
has_items_include and has_selected_include
)
self.arrows_include.button_remove_all.setEnabled(has_items_include)
# "Exclude" list buttons
self.arrows_exclude.button_add.setEnabled(
has_items_ignore and has_selected_ignore
)
self.arrows_exclude.button_add_all.setEnabled(has_items_ignore)
self.arrows_exclude.button_remove.setEnabled(
has_items_exclude and has_selected_exclude
)
self.arrows_exclude.button_remove_all.setEnabled(has_items_exclude)
def display_caa_types_selector(**kwargs):
dialog = CAATypesSelectorDialog(**kwargs)
result = dialog.exec_()
return (
dialog.included,
dialog.excluded,
result == QtWidgets.QDialog.DialogCode.Accepted,
)
|
decrypters | HearthisAtFolder | # -*- coding: utf-8 -*-
import re
import urllib.parse
from ..base.decrypter import BaseDecrypter
class HearthisAtFolder(BaseDecrypter):
__name__ = "HearthisAtFolder"
__type__ = "decrypter"
__version__ = "0.01"
__status__ = "testing"
__pattern__ = r"https?://(?:www\.)?hearthis\.at/.*(?<!#pyload)$"
__config__ = [
("enabled", "bool", "Activated", True),
("use_premium", "bool", "Use premium account if available", True),
(
"folder_per_package",
"Default;Yes;No",
"Create folder for each package",
"Default",
),
("max_wait", "int", "Reconnect if waiting time is greater than minutes", 10),
("dl_subfolders", "bool", "Download subfolders", False),
("package_subfolder", "bool", "Subfolder as a separate package", False),
]
__description__ = """Hearthis.at folder decrypter plugin"""
__license__ = "GPLv3"
__authors__ = [("GammaC0de", "nitzo2001[AT]yahoo[DOT]com")]
def decrypt(self, pyfile):
self.data = self.load(pyfile.url)
m = re.search(r"intTrackId = (\d+);", self.data)
if m is not None:
#: Single track
self.packages = [
(pyfile.package().name, pyfile.url + "#pyload", pyfile.package().folder)
]
else:
#: Playlist
m = re.search(r"intInternalId = (\d+);", self.data)
if m is None:
self.fail(self._("Internal Id not found"))
self.data = self.load(
"https://hearthis.at/user_ajax_more.php",
post={"user": m.group(1), "min": 0, "max": 200},
)
links = [
urllib.parse.urljoin(pyfile.url, x) + "#pyload"
for x in re.findall(
r'<a class="player-link".+?href="(.+?)".+?</a>', self.data, re.S
)
]
self.packages = [(pyfile.package().name, links, pyfile.package().folder)]
|
migrations | 0005_twilioaccount_twiliophonecallsender_twiliosmssender_twilioverificationsender | # Generated by Django 3.2.19 on 2023-05-25 15:32
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("twilioapp", "0004_twiliophonecall_twiliosms"),
]
operations = [
migrations.CreateModel(
name="TwilioAccount",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("name", models.CharField(max_length=100)),
("account_sid", models.CharField(max_length=64, unique=True)),
(
"auth_token",
models.CharField(default=None, max_length=64, null=True),
),
(
"api_key_sid",
models.CharField(default=None, max_length=64, null=True),
),
(
"api_key_secret",
models.CharField(default=None, max_length=64, null=True),
),
],
),
migrations.CreateModel(
name="TwilioVerificationSender",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("name", models.CharField(default="Default", max_length=100)),
(
"country_code",
models.CharField(default=None, max_length=16, null=True),
),
("verify_service_sid", models.CharField(max_length=64)),
(
"account",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="twilioapp_twilioverificationsender_account",
to="twilioapp.twilioaccount",
),
),
],
options={
"abstract": False,
},
),
migrations.CreateModel(
name="TwilioSmsSender",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("name", models.CharField(default="Default", max_length=100)),
(
"country_code",
models.CharField(default=None, max_length=16, null=True),
),
("sender", models.CharField(max_length=16)),
(
"account",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="twilioapp_twiliosmssender_account",
to="twilioapp.twilioaccount",
),
),
],
options={
"abstract": False,
},
),
migrations.CreateModel(
name="TwilioPhoneCallSender",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("name", models.CharField(default="Default", max_length=100)),
(
"country_code",
models.CharField(default=None, max_length=16, null=True),
),
("number", models.CharField(max_length=16)),
(
"account",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="twilioapp_twiliophonecallsender_account",
to="twilioapp.twilioaccount",
),
),
],
options={
"abstract": False,
},
),
]
|
PartDesign | SprocketFeature | # ***************************************************************************
# * Copyright (c) 2020 Adam Spontarelli <adam@vector-space.org> *
# * *
# * This program is free software; you can redistribute it and/or modify *
# * it under the terms of the GNU Lesser General Public License (LGPL) *
# * as published by the Free Software Foundation; either version 2 of *
# * the License, or (at your option) any later version. *
# * for detail see the LICENCE text file. *
# * *
# * This program is distributed in the hope that it will be useful, *
# * but WITHOUT ANY WARRANTY; without even the implied warranty of *
# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
# * GNU Library General Public License for more details. *
# * *
# * You should have received a copy of the GNU Library General Public *
# * License along with this program; if not, write to the Free Software *
# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
# * USA *
# * *
# ***************************************************************************
import FreeCAD
import Part
from fcsprocket import fcsprocket, sprocket
if FreeCAD.GuiUp:
import FreeCADGui
from FreeCADGui import PySideUic as uic
from PySide import QtCore, QtGui
__title__ = "PartDesign SprocketObject management"
__author__ = "Adam Spontarelli"
__url__ = "http://www.freecad.org"
def makeSprocket(name):
"""
makeSprocket(name): makes a Sprocket
"""
obj = FreeCAD.ActiveDocument.addObject("Part::Part2DObjectPython", name)
Sprocket(obj)
if FreeCAD.GuiUp:
ViewProviderSprocket(obj.ViewObject)
# FreeCAD.ActiveDocument.recompute()
if FreeCAD.GuiUp:
body = FreeCADGui.ActiveDocument.ActiveView.getActiveObject("pdbody")
part = FreeCADGui.ActiveDocument.ActiveView.getActiveObject("part")
if body:
body.Group = body.Group + [obj]
elif part:
part.Group = part.Group + [obj]
return obj
class CommandSprocket:
"""
the Fem Sprocket command definition
"""
def GetResources(self):
return {
"Pixmap": "PartDesign_Sprocket",
"MenuText": QtCore.QT_TRANSLATE_NOOP("PartDesign_Sprocket", "Sprocket..."),
"Accel": "",
"ToolTip": QtCore.QT_TRANSLATE_NOOP(
"PartDesign_Sprocket", "Creates or edit the sprocket definition."
),
}
def Activated(self):
FreeCAD.ActiveDocument.openTransaction("Create Sprocket")
FreeCADGui.addModule("SprocketFeature")
FreeCADGui.doCommand("SprocketFeature.makeSprocket('Sprocket')")
FreeCADGui.doCommand(
"Gui.activeDocument().setEdit(App.ActiveDocument.ActiveObject.Name,0)"
)
def IsActive(self):
if FreeCAD.ActiveDocument:
return True
else:
return False
class Sprocket:
"""
The Sprocket object
"""
"""
ANSI B29.1-2011 standard roller chain sizes in USCS units (inches)
{size: [Pitch, Roller Diameter]}
"""
SprocketReferenceRollerTable = {
"ANSI 25": [0.250, 0.130, 0.110],
"ANSI 35": [0.375, 0.200, 0.168],
"ANSI 41": [0.500, 0.306, 0.227],
"ANSI 40": [0.500, 0.312, 0.284],
"ANSI 50": [0.625, 0.400, 0.343],
"ANSI 60": [0.750, 0.469, 0.459],
"ANSI 80": [1.000, 0.625, 0.575],
"ANSI 100": [1.250, 0.750, 0.692],
"ANSI 120": [1.500, 0.875, 0.924],
"ANSI 140": [1.750, 1.000, 0.924],
"ANSI 160": [2.000, 1.125, 1.156],
"ANSI 180": [2.250, 1.460, 1.301],
"ANSI 200": [2.500, 1.562, 1.389],
"ANSI 240": [3.000, 1.875, 1.738],
"Bicycle with Derailleur": [0.500, 0.3125, 0.11],
"Bicycle without Derailleur": [0.500, 0.3125, 0.084],
"ISO 606 06B": [0.375, 5.72 / 25.4, 5.2 / 25.4],
"ISO 606 08B": [0.500, 7.75 / 25.4, 7.0 / 25.4],
"ISO 606 10B": [0.625, 9.65 / 25.4, 9.1 / 25.4],
"ISO 606 12B": [0.750, 11.68 / 25.4, 11.1 / 25.4],
"ISO 606 16B": [1.000, 17.02 / 25.4, 16.2 / 25.4],
"ISO 606 20B": [1.250, 19.56 / 25.4, 18.5 / 25.4],
"ISO 606 24B": [1.500, 25.4 / 25.4, 24.1 / 25.4],
"Motorcycle 420": [0.500, 0.3125, 0.227],
"Motorcycle 425": [0.500, 0.3125, 0.284],
"Motorcycle 428": [0.500, 0.335, 0.284],
"Motorcycle 520": [0.625, 0.400, 0.227],
"Motorcycle 525": [0.625, 0.400, 0.284],
"Motorcycle 530": [0.625, 0.400, 0.343],
"Motorcycle 630": [0.750, 0.400, 0.343],
}
def __init__(self, obj):
self.Type = "Sprocket"
obj.addProperty(
"App::PropertyInteger", "NumberOfTeeth", "Sprocket", "Number of gear teeth"
)
obj.addProperty("App::PropertyLength", "Pitch", "Sprocket", "Chain Pitch")
obj.addProperty(
"App::PropertyLength", "RollerDiameter", "Sprocket", "Roller Diameter"
)
obj.addProperty(
"App::PropertyEnumeration",
"SprocketReference",
"Sprocket",
"Sprocket Reference",
)
obj.addProperty(
"App::PropertyLength",
"Thickness",
"Sprocket",
"Thickness as stated in the reference specification",
)
obj.SprocketReference = list(self.SprocketReferenceRollerTable)
obj.NumberOfTeeth = 50
obj.Pitch = "0.375 in"
obj.RollerDiameter = "0.20 in"
obj.SprocketReference = "ANSI 35"
obj.Thickness = "0.11 in"
obj.Proxy = self
def execute(self, obj):
w = fcsprocket.FCWireBuilder()
sprocket.CreateSprocket(
w, obj.Pitch.Value, obj.NumberOfTeeth, obj.RollerDiameter.Value
)
sprocketw = Part.Wire([o.toShape() for o in w.wire])
obj.Shape = sprocketw
obj.positionBySupport()
return
class ViewProviderSprocket:
"""
A View Provider for the Sprocket object
"""
def __init__(self, vobj):
vobj.Proxy = self
def getIcon(self):
return ":/icons/PartDesign_Sprocket.svg"
def attach(self, vobj):
self.ViewObject = vobj
self.Object = vobj.Object
def setEdit(self, vobj, mode):
taskd = SprocketTaskPanel(self.Object, mode)
taskd.obj = vobj.Object
taskd.update()
FreeCADGui.Control.showDialog(taskd)
return True
def unsetEdit(self, vobj, mode):
FreeCADGui.Control.closeDialog()
return
def dumps(self):
return None
def loads(self, state):
return None
class SprocketTaskPanel:
"""
The editmode TaskPanel for Sprocket objects
"""
def __init__(self, obj, mode):
self.obj = obj
self.form = FreeCADGui.PySideUic.loadUi(
FreeCAD.getHomePath() + "Mod/PartDesign/SprocketFeature.ui"
)
self.form.setWindowIcon(QtGui.QIcon(":/icons/PartDesign_Sprocket.svg"))
QtCore.QObject.connect(
self.form.Quantity_Pitch,
QtCore.SIGNAL("valueChanged(double)"),
self.pitchChanged,
)
QtCore.QObject.connect(
self.form.Quantity_RollerDiameter,
QtCore.SIGNAL("valueChanged(double)"),
self.rollerDiameterChanged,
)
QtCore.QObject.connect(
self.form.spinBox_NumberOfTeeth,
QtCore.SIGNAL("valueChanged(int)"),
self.numTeethChanged,
)
QtCore.QObject.connect(
self.form.comboBox_SprocketReference,
QtCore.SIGNAL("currentTextChanged(const QString)"),
self.sprocketReferenceChanged,
)
QtCore.QObject.connect(
self.form.Quantity_Thickness,
QtCore.SIGNAL("valueChanged(double)"),
self.thicknessChanged,
)
self.update()
if mode == 0: # fresh created
self.obj.Proxy.execute(self.obj) # calculate once
FreeCAD.Gui.SendMsgToActiveView("ViewFit")
def transferTo(self):
"""
Transfer from the dialog to the object
"""
self.obj.NumberOfTeeth = self.form.spinBox_NumberOfTeeth.value()
self.obj.Pitch = self.form.Quantity_Pitch.text()
self.obj.RollerDiameter = self.form.Quantity_RollerDiameter.text()
self.obj.SprocketReference = self.form.comboBox_SprocketReference.currentText()
self.obj.Thickness = self.form.Quantity_Thickness.text()
def transferFrom(self):
"""
Transfer from the object to the dialog
"""
self.form.spinBox_NumberOfTeeth.setValue(self.obj.NumberOfTeeth)
self.form.Quantity_Pitch.setText(self.obj.Pitch.UserString)
self.form.Quantity_RollerDiameter.setText(self.obj.RollerDiameter.UserString)
self.form.comboBox_SprocketReference.setCurrentText(self.obj.SprocketReference)
self.form.Quantity_Thickness.setText(self.obj.Thickness.UserString)
def pitchChanged(self, value):
self.obj.Pitch = value
self.obj.Proxy.execute(self.obj)
FreeCAD.Gui.SendMsgToActiveView("ViewFit")
def sprocketReferenceChanged(self, size):
self.obj.Pitch = str(Sprocket.SprocketReferenceRollerTable[size][0]) + " in"
self.obj.RollerDiameter = (
str(Sprocket.SprocketReferenceRollerTable[size][1]) + " in"
)
self.obj.Thickness = str(Sprocket.SprocketReferenceRollerTable[size][2]) + " in"
self.obj.SprocketReference = str(size)
self.form.Quantity_Pitch.setText(self.obj.Pitch.UserString)
self.form.Quantity_RollerDiameter.setText(self.obj.RollerDiameter.UserString)
self.form.Quantity_Thickness.setText(self.obj.Thickness.UserString)
self.obj.Proxy.execute(self.obj)
FreeCAD.Gui.SendMsgToActiveView("ViewFit")
def rollerDiameterChanged(self, value):
self.obj.RollerDiameter = value
self.obj.Proxy.execute(self.obj)
def numTeethChanged(self, value):
self.obj.NumberOfTeeth = value
self.obj.Proxy.execute(self.obj)
FreeCAD.Gui.SendMsgToActiveView("ViewFit")
def thicknessChanged(self, value):
self.obj.Thickness = str(value)
self.obj.Proxy.execute(self.obj)
def getStandardButtons(self):
return (
int(QtGui.QDialogButtonBox.Ok)
| int(QtGui.QDialogButtonBox.Cancel)
| int(QtGui.QDialogButtonBox.Apply)
)
def clicked(self, button):
if button == QtGui.QDialogButtonBox.Apply:
self.transferTo()
self.obj.Proxy.execute(self.obj)
def update(self):
self.transferFrom()
def accept(self):
self.transferTo()
FreeCAD.ActiveDocument.recompute()
FreeCADGui.ActiveDocument.resetEdit()
def reject(self):
FreeCADGui.ActiveDocument.resetEdit()
FreeCAD.ActiveDocument.abortTransaction()
if FreeCAD.GuiUp:
FreeCADGui.addCommand("PartDesign_Sprocket", CommandSprocket())
|
code | planet | #!/usr/bin/env python
"""The Planet aggregator.
A flexible and easy-to-use aggregator for generating websites.
Visit http://www.planetplanet.org/ for more information and to download
the latest version.
Requires Python 2.1, recommends 2.3.
"""
__authors__ = [ "Scott James Remnant <scott@netsplit.com>",
"Jeff Waugh <jdub@perkypants.org>" ]
__license__ = "Python"
import locale
import os
import socket
import sys
import time
import planet
import urlparse
from ConfigParser import ConfigParser
# Default configuration file path
CONFIG_FILE = "config.ini"
# Defaults for the [Planet] config section
PLANET_NAME = "Unconfigured Planet"
PLANET_LINK = "Unconfigured Planet"
PLANET_FEED = None
OWNER_NAME = "Anonymous Coward"
OWNER_EMAIL = ""
LOG_LEVEL = "WARNING"
FEED_TIMEOUT = 20 # seconds
# Default template file list
TEMPLATE_FILES = "examples/basic/planet.html.tmpl"
def config_get(config, section, option, default=None, raw=0, vars=None):
"""Get a value from the configuration, with a default."""
if config.has_option(section, option):
return config.get(section, option, raw=raw, vars=None)
else:
return default
def main():
config_file = CONFIG_FILE
offline = 0
verbose = 0
for arg in sys.argv[1:]:
if arg == "-h" or arg == "--help":
print "Usage: planet [options] [CONFIGFILE]"
print
print "Options:"
print " -v, --verbose DEBUG level logging during update"
print " -o, --offline Update the Planet from the cache only"
print " -h, --help Display this help message and exit"
print
sys.exit(0)
elif arg == "-v" or arg == "--verbose":
verbose = 1
elif arg == "-o" or arg == "--offline":
offline = 1
elif arg.startswith("-"):
print >>sys.stderr, "Unknown option:", arg
sys.exit(1)
else:
config_file = arg
# Read the configuration file
config = ConfigParser()
config.read(config_file)
if not config.has_section("Planet"):
print >>sys.stderr, "Configuration missing [Planet] section."
sys.exit(1)
# Read the [Planet] config section
planet_name = config_get(config, "Planet", "name", PLANET_NAME)
planet_link = config_get(config, "Planet", "link", PLANET_LINK)
planet_feed = config_get(config, "Planet", "feed", PLANET_FEED)
owner_name = config_get(config, "Planet", "owner_name", OWNER_NAME)
owner_email = config_get(config, "Planet", "owner_email", OWNER_EMAIL)
if verbose:
log_level = "DEBUG"
else:
log_level = config_get(config, "Planet", "log_level", LOG_LEVEL)
feed_timeout = config_get(config, "Planet", "feed_timeout", FEED_TIMEOUT)
template_files = config_get(config, "Planet", "template_files",
TEMPLATE_FILES).split(" ")
# Default feed to the first feed for which there is a template
if not planet_feed:
for template_file in template_files:
name = os.path.splitext(os.path.basename(template_file))[0]
if name.find('atom')>=0 or name.find('rss')>=0:
planet_feed = urlparse.urljoin(planet_link, name)
break
# Define locale
if config.has_option("Planet", "locale"):
# The user can specify more than one locale (separated by ":") as
# fallbacks.
locale_ok = False
for user_locale in config.get("Planet", "locale").split(':'):
user_locale = user_locale.strip()
try:
locale.setlocale(locale.LC_ALL, user_locale)
except locale.Error:
pass
else:
locale_ok = True
break
if not locale_ok:
print >>sys.stderr, "Unsupported locale setting."
sys.exit(1)
# Activate logging
planet.logging.basicConfig()
planet.logging.getLogger().setLevel(planet.logging.getLevelName(log_level))
log = planet.logging.getLogger("planet.runner")
try:
log.warning
except:
log.warning = log.warn
if feed_timeout:
try:
feed_timeout = float(feed_timeout)
except:
log.warning("Feed timeout set to invalid value '%s', skipping", feed_timeout)
feed_timeout = None
if feed_timeout and not offline:
socket.setdefaulttimeout(feed_timeout)
log.debug("Socket timeout set to %d seconds", feed_timeout)
# run the planet
my_planet = planet.Planet(config)
my_planet.run(planet_name, planet_link, template_files, offline)
my_planet.generate_all_files(template_files, planet_name,
planet_link, planet_feed, owner_name, owner_email)
if __name__ == "__main__":
main()
|
AppImage-builder | create_appimage | # Copyright (c) 2023 UltiMaker
# Cura is released under the terms of the LGPLv3 or higher.
import argparse
import os
import shutil
import subprocess
from pathlib import Path
from jinja2 import Template
def prepare_workspace(dist_path, appimage_filename):
"""
Prepare the workspace for building the AppImage.
:param dist_path: Path to the distribution of Cura created with pyinstaller.
:param appimage_filename: name of the AppImage file.
:return:
"""
if not os.path.exists(dist_path):
raise RuntimeError(f"The dist_path {dist_path} does not exist.")
if os.path.exists(os.path.join(dist_path, appimage_filename)):
os.remove(os.path.join(dist_path, appimage_filename))
if not os.path.exists("AppDir"):
shutil.move(dist_path, "AppDir")
else:
print(f"AppDir already exists, assuming it is already prepared.")
copy_files("AppDir")
def build_appimage(dist_path, version, appimage_filename):
"""
Creates an AppImage file from the build artefacts created so far.
"""
generate_appimage_builder_config(dist_path, version, appimage_filename)
create_appimage()
sign_appimage(dist_path, appimage_filename)
def generate_appimage_builder_config(dist_path, version, appimage_filename):
with open(
os.path.join(Path(__file__).parent, "AppImageBuilder.yml.jinja"), "r"
) as appimage_builder_file:
appimage_builder = appimage_builder_file.read()
template = Template(appimage_builder)
appimage_builder = template.render(
app_dir="./AppDir",
icon="cura-icon.png",
version=version,
arch="x86_64",
file_name=appimage_filename,
)
with open(
os.path.join(Path(__file__).parent, "AppImageBuilder.yml"), "w"
) as appimage_builder_file:
appimage_builder_file.write(appimage_builder)
def copy_files(dist_path):
"""
Copy metadata files for the metadata of the AppImage.
"""
copied_files = {
os.path.join("..", "icons", "cura-icon.svg"): os.path.join(
"usr", "share", "icons", "hicolor", "scalable", "apps", "cura-icon.svg"
),
os.path.join("..", "icons", "cura-icon_64x64.png"): os.path.join(
"usr", "share", "icons", "hicolor", "64x64", "apps", "cura-icon.png"
),
os.path.join("..", "icons", "cura-icon_128x128.png"): os.path.join(
"usr", "share", "icons", "hicolor", "128x128", "apps", "cura-icon.png"
),
os.path.join("..", "icons", "cura-icon_256x256.png"): os.path.join(
"usr", "share", "icons", "hicolor", "256x256", "apps", "cura-icon.png"
),
os.path.join("..", "icons", "cura-icon_256x256.png"): "cura-icon.png",
}
# TODO: openssl.cnf ???
packaging_dir = os.path.dirname(__file__)
for source, dest in copied_files.items():
dest_file_path = os.path.join(dist_path, dest)
os.makedirs(os.path.dirname(dest_file_path), exist_ok=True)
shutil.copyfile(os.path.join(packaging_dir, source), dest_file_path)
def create_appimage():
appimagetool = os.getenv(
"APPIMAGEBUILDER_LOCATION", "appimage-builder-x86_64.AppImage"
)
command = [
appimagetool,
"--recipe",
os.path.join(Path(__file__).parent, "AppImageBuilder.yml"),
"--skip-test",
]
result = subprocess.call(command)
if result != 0:
raise RuntimeError(f"The AppImageTool command returned non-zero: {result}")
def sign_appimage(dist_path, appimage_filename):
command = ["gpg", "--yes", "--armor", "--detach-sig", appimage_filename]
result = subprocess.call(command)
if result != 0:
raise RuntimeError(f"The GPG command returned non-zero: {result}")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Create AppImages of Cura.")
parser.add_argument(
"dist_path",
type=str,
help="Path to where PyInstaller installed the distribution of Cura.",
)
parser.add_argument(
"version", type=str, help="Full version number of Cura (e.g. '5.1.0-beta')"
)
parser.add_argument(
"filename",
type=str,
help="Filename of the AppImage (e.g. 'UltiMaker-Cura-5.1.0-beta-Linux-X64.AppImage')",
)
args = parser.parse_args()
prepare_workspace(args.dist_path, args.filename)
build_appimage(args.dist_path, args.version, args.filename)
|
lib | strings | """
This file is part of the Stargate project, Copyright Stargate Team
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation version 3 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
"""
from sglib.lib.translate import _
from sglib.lib.util import KEY_ALT, KEY_CTRL
audio_viewer_widget_papifx = _(
"""\
This tab allows you to set effects per-audio file. There will be exactly one
instance of these effects per audio file. Use this as a mixing aid for EQ,
filter, etc... on a file."""
)
audio_viewer_widget_paifx = _(
"""\
This tab allows you to set effects per-audio-item. The effects will be unique
per instance of an audio file, and not share between instances."""
)
timestretch_modes = {
0: "No stretching or pitch adjustment",
1: (
"Repitch the item, it will become shorter at higher pitches, and "
"longer at lower pitches"
),
2: (
"Stretch the item to the desired length, it will have lower pitch "
"at longer lengths, and higher pitch at shorter lengths"
),
3: "Adjust pitch and time independently",
4: (
"Same as Rubberband, but preserves formants when pitch shifting. "
"Useful on vocal materials, an auto-tune type of pitch shifting"
),
5: (
"Adjust pitch and time independently, also with the ability to "
"set start/end pitch/time differently"
),
6: (
"Mostly for stretching items very long, creates a very smeared, "
"atmospheric sound. Useful for creative reverb-like effects and "
"soundscapes"
),
7: (
"A good timestretching algorithm for many types of materials. "
"Optimized for full pieces of music"
),
8: (
"A good timestretching algorithm for many types of materials. "
"Optimized for speech"
),
}
avconv_error = _(
"""\
Please ensure that ffmpeg (or avconv) and lame are installed.
cannot open mp3 converter dialog.
Check your normal sources for packages or visit:
http://lame.sourceforge.net
http://ffmpeg.org
Cannot find {}"""
)
export_format = _(
"""File is exported to 32 bit .wav at the sample rate your audio
interface is running at.
You can convert the format using the Menu->Tools dialogs"""
)
pitchbend_dialog = _(
"""\
Pitchbend values are in semitones. Use this dialog to add points with
precision,or double-click on the editor to add points."""
)
PianoRollEditor = f"""
Edit MIDI notes. See the "Parameter" combobox, the menu button and the mouse
tools in the transport panel. Draw notes holding {KEY_ALT} to move instead of
change length
"""
AudioItemSeq = _(
"""\
Item editor for audio. Each sequencer item can contain multiple
audio items in addition to MIDI. Drag audio files from the file browser
onto here.
"""
)
AudioSeqItem = _(
f"""
Audio item. Right click: actions. {KEY_CTRL}+{KEY_ALT}+drag: item volume,
CTRL+SHIFT+drag: vol. curve, {KEY_ALT}+SHIFT+drag: file vol. {KEY_CTRL}+drag:
copy, {KEY_ALT}+click: multi-select
"""
)
AUDIO_SEQ_HELP = """\
Select 1+ items, CTRL+click+drag up/down/left/right to copy selected items
Select 1+ items, ALT+SHIFT+Click and drag up/down:
Modify the volume of the file. This is useful for mixing, as it modifies
the volume of every instance of the file in the entire project.
Select 1+ items, CTRL+ALT+Click and drag up/down:
Modify the volume of selected items. Different audio items in the
same sequencer item can have different volumes using this technique.
Select 1+ items, CTRL+SHIFT+Click and drag up/down:
Create a volume line for the selected items. For example, you have the
same kick drum sample repeated 4 times in an item, one beat apart from
each other. Select all of them, perform this mouse gesture by clicking
on the first one and dragging down. The respective values might be
-9dB, -6dB, -3dB, 0dB, getting progressively louder.
See the menu button above for additional actions"""
multiple_instances_warning = _(
"""\
Detected that there are instances of the Stargate audio engine already running.
This could mean that you already have Stargate running, if so you
should click 'Cancel' and close the other instance.
This could also mean that for some reason the engine did not properly
terminate from another session. If so, click 'OK' to kill the
other process(es)"""
)
routing_graph = _(
"""\
Audio (click), sidechain(CTRL+click) and MIDI(SHIFT+click) routing between
tracks. Click below the dest. to route to lower numbered tracks,
above for higher. Double click a track to open plugins
"""
)
track_panel_dropdown = _(
"""\
The dropdown menu contains a shortcut to the track plugins (instrument and
effects), and controls for selecting parameters for automation. For a global
view of track sends, see the routing tab."""
)
"""
A track can be any or all of audio, MIDI, send or bus, at the same time.
Instrument plugins can be placed before or after effect plugins, and
will pass-through any audio from items or sends.
"""
ENGINE_MON = """\
Shows CPU and memory percentage. Note that the CPU usage is a max of the
cores that are in use, not based on the average of CPU load and available
logical cores, which is less useful.
"""
NO_AUDIO_INPUTS_INSTRUCTIONS = """\
No audio inputs available. If you are using an audio device with inputs, press
the Hardware Settings button and ensure that the audio inputs control is set to
a number greater than 0.
"""
|
accounts | UpleaCom | # -*- coding: utf-8 -*-
import re
import time
from ..base.account import BaseAccount
class UpleaCom(BaseAccount):
__name__ = "UpleaCom"
__type__ = "account"
__version__ = "0.02"
__status__ = "testing"
__description__ = """UpleaCom account plugin"""
__license__ = "GPLv3"
__authors__ = [("GammaC0de", "nitzo2001[AT]yahoo[DOT]com")]
LOGIN_URL = r"http://uplea.com"
LOGIN_SKIP_PATTERN = r'>DISCONNECT</span> <span class="agbold">ME NOW<'
PREMIUM_PATTERN = r"Uplea premium member <"
VALID_UNTIL_PATTERN = r"You\'re premium member until .+?>([\d/]+)"
def grab_info(self, user, password, data):
trafficleft = -1
html = self.load("http://uplea.com/account")
if re.search(self.PREMIUM_PATTERN, html):
premium = True
m = re.search(self.VALID_UNTIL_PATTERN, html)
if m is None:
premium = False
validuntil = -1
else:
premium = True
validuntil = time.mktime(time.strptime(m.group(1), "%d/%m/%Y"))
return {
"premium": premium,
"trafficleft": trafficleft,
"validuntil": validuntil,
}
def signin(self, user, password, data):
html = self.load("http://uplea.com")
if self.LOGIN_SKIP_PATTERN in html:
self.skip_login()
html = self.load(
"http://uplea.com",
post={"login": user, "password": password, "remember": 0, "login-form": ""},
)
if self.LOGIN_SKIP_PATTERN not in html:
self.fail_login()
|
gui | toolbar | # This file is part of MyPaint.
# Copyright (C) 2011-2018 by the MyPaint Development Team.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
"""The application toolbar, and its specialised widgets"""
## Imports
from __future__ import division, print_function
import os
from gettext import gettext as _
from lib.gibindings import Gtk
from . import widgets
## Module constants
FRAMEWORK_XML = "toolbar.xml"
MERGEABLE_XML = [
("toolbar1_file", "toolbar-file.xml", _("File handling")),
("toolbar1_scrap", "toolbar-scrap.xml", _("Scraps switcher")),
("toolbar1_edit", "toolbar-edit.xml", _("Undo and Redo")),
("toolbar1_blendmodes", "toolbar-blendmodes.xml", _("Blend Modes")),
("toolbar1_linemodes", "toolbar-linemodes.xml", _("Line Modes")),
("toolbar1_view_modes", "toolbar-view-modes.xml", _("View (Main)")),
(
"toolbar1_view_manips",
"toolbar-view-manips.xml",
_("View (Alternative/Secondary)"),
),
("toolbar1_view_resets", "toolbar-view-resets.xml", _("View (Resetting)")),
]
## Class definitions
class ToolbarManager(object):
"""Manager for toolbars, currently just the main one.
The main toolbar, /toolbar1, contains a menu button and quick
access to the painting tools.
"""
def __init__(self, draw_window):
super(ToolbarManager, self).__init__()
self.draw_window = draw_window
self.app = draw_window.app
self.toolbar1_ui_loaded = {} # {name: merge_id, ...}
self.init_actions()
ui_dir = os.path.dirname(os.path.abspath(__file__))
toolbarpath = os.path.join(ui_dir, FRAMEWORK_XML)
self.app.ui_manager.add_ui_from_file(toolbarpath)
self.toolbar1 = self.app.ui_manager.get_widget("/toolbar1")
self.toolbar1.set_style(Gtk.ToolbarStyle.ICONS)
self.toolbar1.set_icon_size(widgets.get_toolbar_icon_size())
self.toolbar1.set_border_width(0)
self.toolbar1.set_show_arrow(True)
self.toolbar1.connect("popup-context-menu", self.on_toolbar1_popup_context_menu)
self.toolbar1_popup = self.app.ui_manager.get_widget("/toolbar1-settings-menu")
for item in self.toolbar1:
if isinstance(item, Gtk.SeparatorToolItem):
item.set_draw(False)
self.toolbar2 = self.app.ui_manager.get_widget("/toolbar2")
self.toolbar2.set_style(Gtk.ToolbarStyle.ICONS)
self.toolbar2.set_icon_size(widgets.get_toolbar_icon_size())
self.toolbar2.set_border_width(0)
self.toolbar2.set_show_arrow(False)
for toolbar in (self.toolbar1, self.toolbar2):
styles = toolbar.get_style_context()
styles.add_class(Gtk.STYLE_CLASS_PRIMARY_TOOLBAR)
# Merge in UI pieces based on the user's saved preferences
for action in self.settings_actions:
name = action.get_property("name")
active = self.app.preferences["ui.toolbar_items"].get(name, False)
action.set_active(active)
action.toggled()
def init_actions(self):
ag = self.draw_window.action_group
actions = []
self.settings_actions = []
for name, ui_xml, label in MERGEABLE_XML:
action = Gtk.ToggleAction.new(name, label, None, None)
action.connect("toggled", self.on_settings_toggle, ui_xml)
self.settings_actions.append(action)
actions += self.settings_actions
for action in actions:
ag.add_action(action)
def on_toolbar1_popup_context_menu(self, toolbar, x, y, button):
menu = self.toolbar1_popup
def _posfunc(*a):
return x, y, True
time = Gtk.get_current_event_time()
menu.popup(None, None, _posfunc, None, button, time)
def on_settings_toggle(self, toggleaction, ui_xml_file):
name = toggleaction.get_property("name")
merge_id = self.toolbar1_ui_loaded.get(name, None)
if toggleaction.get_active():
self.app.preferences["ui.toolbar_items"][name] = True
if merge_id is not None:
return
ui_dir = os.path.dirname(os.path.abspath(__file__))
ui_xml_path = os.path.join(ui_dir, ui_xml_file)
merge_id = self.app.ui_manager.add_ui_from_file(ui_xml_path)
self.toolbar1_ui_loaded[name] = merge_id
else:
self.app.preferences["ui.toolbar_items"][name] = False
if merge_id is None:
return
self.app.ui_manager.remove_ui(merge_id)
self.toolbar1_ui_loaded.pop(name)
|
engines | postgresql | # SPDX-License-Identifier: AGPL-3.0-or-later
"""
PostgreSQL database (Offline)
"""
# error is ignored because the admin has to
# install it manually to use the engine
# pylint: disable=import-error
import psycopg2
engine_type = "offline"
host = "127.0.0.1"
port = "5432"
database = ""
username = ""
password = ""
query_str = ""
limit = 10
paging = True
result_template = "key-value.html"
_connection = None
def init(engine_settings):
if "query_str" not in engine_settings:
raise ValueError("query_str cannot be empty")
if not engine_settings["query_str"].lower().startswith("select "):
raise ValueError("only SELECT query is supported")
global _connection
_connection = psycopg2.connect(
database=database,
user=username,
password=password,
host=host,
port=port,
)
def search(query, params):
query_params = {"query": query}
query_to_run = query_str + " LIMIT {0} OFFSET {1}".format(
limit, (params["pageno"] - 1) * limit
)
with _connection:
with _connection.cursor() as cur:
cur.execute(query_to_run, query_params)
return _fetch_results(cur)
def _fetch_results(cur):
results = []
titles = []
try:
titles = [column_desc.name for column_desc in cur.description]
for res in cur:
result = dict(zip(titles, map(str, res)))
result["template"] = result_template
results.append(result)
# no results to fetch
except psycopg2.ProgrammingError:
pass
return results
|
ofdm | benchmark_add_channel | #!/usr/bin/env python
#
# Copyright 2010,2011 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# SPDX-License-Identifier: GPL-3.0-or-later
#
#
import math
import random
import sys
from optparse import OptionParser
from gnuradio import blocks, channels, eng_notation, gr
from gnuradio.eng_option import eng_option
class my_top_block(gr.top_block):
def __init__(self, ifile, ofile, options):
gr.top_block.__init__(self)
SNR = 10.0 ** (options.snr / 10.0)
time_offset = options.time_offset
phase_offset = options.phase_offset * (math.pi / 180.0)
# calculate noise voltage from SNR
power_in_signal = abs(options.tx_amplitude) ** 2
noise_power = power_in_signal / SNR
noise_voltage = math.sqrt(noise_power)
print("Noise voltage: ", noise_voltage)
frequency_offset = options.frequency_offset / options.fft_length
self.src = blocks.file_source(gr.sizeof_gr_complex, ifile)
# self.throttle = blocks.throttle(gr.sizeof_gr_complex, options.sample_rate)
self.channel = channels.channel_model(
noise_voltage,
frequency_offset,
time_offset,
noise_seed=-random.randint(0, 100000),
)
self.phase = blocks.multiply_const_cc(
complex(math.cos(phase_offset), math.sin(phase_offset))
)
self.snk = blocks.file_sink(gr.sizeof_gr_complex, ofile)
self.connect(self.src, self.channel, self.phase, self.snk)
# /////////////////////////////////////////////////////////////////////////////
# main
# /////////////////////////////////////////////////////////////////////////////
def main():
# Create Options Parser:
usage = "benchmack_add_channel.py [options] <input file> <output file>"
parser = OptionParser(
usage=usage, option_class=eng_option, conflict_handler="resolve"
)
parser.add_option(
"-n",
"--snr",
type="eng_float",
default=30,
help="set the SNR of the channel in dB [default=%default]",
)
parser.add_option(
"",
"--seed",
action="store_true",
default=False,
help="use a random seed for AWGN noise [default=%default]",
)
parser.add_option(
"-f",
"--frequency-offset",
type="eng_float",
default=0,
help="set frequency offset introduced by channel [default=%default]",
)
parser.add_option(
"-t",
"--time-offset",
type="eng_float",
default=1.0,
help="set timing offset between Tx and Rx [default=%default]",
)
parser.add_option(
"-p",
"--phase-offset",
type="eng_float",
default=0,
help="set phase offset (in degrees) between Tx and Rx [default=%default]",
)
parser.add_option(
"-m",
"--use-multipath",
action="store_true",
default=False,
help="Use a multipath channel [default=%default]",
)
parser.add_option(
"",
"--fft-length",
type="intx",
default=None,
help="set the number of FFT bins [default=%default]",
)
parser.add_option(
"",
"--tx-amplitude",
type="eng_float",
default=1.0,
help="tell the simulator the signal amplitude [default=%default]",
)
(options, args) = parser.parse_args()
if len(args) != 2:
parser.print_help(sys.stderr)
sys.exit(1)
if options.fft_length is None:
sys.stderr.write("Please enter the FFT length of the OFDM signal.\n")
sys.exit(1)
ifile = args[0]
ofile = args[1]
# build the graph
tb = my_top_block(ifile, ofile, options)
r = gr.enable_realtime_scheduling()
if r != gr.RT_OK:
print("Warning: Failed to enable realtime scheduling.")
tb.start() # start flow graph
tb.wait() # wait for it to finish
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
pass
|
radio-crawler | fetch_cast | #!/usr/bin/env python2
# Copyright 2011,2014 Christoph Reiter
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
"""
Loads and parses shoutcast/icecast pages and also adds new stream uris.
"""
import traceback
from multiprocessing import Pool
import cPickle as pickle
from util import (
LISTENERCURRENT,
LISTENERPEAK,
ParseError,
get_cache,
get_failed,
get_root,
parse_icecast,
parse_shoutcast1,
parse_shoutcast2,
set_cache,
set_failed,
)
PROCESSES = 20
PARSE_FAILED = "cast_failed.txt"
def get_parse_failed(path=PARSE_FAILED):
try:
with open(path, "rb") as h:
return set(filter(None, h.read().splitlines()))
except IOError:
return set()
def set_parse_failed(failed_uris, path=PARSE_FAILED):
with open(path, "wb") as h:
h.write("\n".join(sorted(set(failed_uris))))
def fetch_stream_infos(uri):
"""Returns a list of Stream objects (can be empty)"""
try:
return uri, [parse_shoutcast1(uri)]
except ParseError:
pass
except:
print(uri)
traceback.print_exc()
raise
try:
return uri, parse_icecast(uri)
except ParseError:
pass
except:
print(uri)
traceback.print_exc()
raise
try:
return uri, parse_shoutcast2(uri)
except ParseError:
pass
except:
print(uri)
traceback.print_exc()
raise
return uri, []
def main():
cache = get_cache()
failed_uris = get_failed()
parse_failed_uris = get_parse_failed()
uris = cache.keys()
peak_missing = [uri for uri in uris if LISTENERPEAK not in cache[uri]]
peak_missing = set(peak_missing) - failed_uris
# XXX: fetch_stream_infos is the same for each root url
peak_missing = {get_root(uri) for uri in peak_missing}
peak_missing = set(peak_missing) - parse_failed_uris
pool = Pool(PROCESSES)
try:
pfunc = fetch_stream_infos
for i, res in enumerate(pool.imap_unordered(pfunc, peak_missing)):
uri, streams = res
# save all 1000
if (i + 1) % 1000 == 0:
set_cache(cache)
print("%d/%d " % (i + 1, len(peak_missing)) + uri + " -> ", end="")
print("%d new streams" % len(streams))
if not streams:
parse_failed_uris.add(uri)
# add new found uris to cache + listener count
for stream in streams:
peak = str(int(stream.peak))
current = str(int(stream.current))
uri = stream.stream
if uri not in cache:
cache[uri] = {}
if LISTENERPEAK in cache[uri]:
cache[uri][LISTENERPEAK].append(peak)
else:
cache[uri][LISTENERPEAK] = [peak]
if LISTENERCURRENT in cache[uri]:
cache[uri][LISTENERCURRENT].append(current)
else:
cache[uri][LISTENERCURRENT] = [current]
except Exception as e:
print(e)
finally:
set_parse_failed(parse_failed_uris)
set_cache(cache)
pool.terminate()
pool.join()
if __name__ == "__main__":
main()
|
clientScripts | identify_file_format | #!/usr/bin/env python
import argparse
import multiprocessing
import uuid
import django
django.setup()
from databaseFunctions import getUTCDate, insertIntoEvents
from django.db import transaction
# archivematicaCommon
from executeOrRunSubProcess import executeOrRun
# dashboard
from fpr.models import FormatVersion, IDCommand, IDRule
from main.models import File, FileFormatVersion, FileID, UnitVariable
def concurrent_instances():
return multiprocessing.cpu_count()
def _save_id_preference(file_, value):
"""
Saves whether file format identification is being used.
This is necessary in order to allow post-extraction identification to work.
The replacement dict will be saved to the special 'replacementDict' unit
variable, which will be transformed back into a passVar when a new chain in
the same unit is begun.
"""
value = str(value)
# The unit_uuid foreign key can point to a transfer or SIP, and this tool
# runs in both.
# Check the SIP first - if it hasn't been assigned yet, then this is being
# run during the transfer.
unit = file_.sip or file_.transfer
rd = {"%IDCommand%": value}
UnitVariable.objects.create(
unituuid=unit.pk, variable="replacementDict", variablevalue=str(rd)
)
def write_identification_event(file_uuid, command, format=None, success=True):
event_detail_text = 'program="{}"; version="{}"'.format(
command.tool.description, command.tool.version
)
if success:
event_outcome_text = "Positive"
else:
event_outcome_text = "Not identified"
if not format:
format = "No Matching Format"
date = getUTCDate()
insertIntoEvents(
fileUUID=file_uuid,
eventIdentifierUUID=str(uuid.uuid4()),
eventType="format identification",
eventDateTime=date,
eventDetail=event_detail_text,
eventOutcome=event_outcome_text,
eventOutcomeDetailNote=format,
)
def write_file_id(file_uuid, format, output):
"""
Write the identified format to the DB.
:param str file_uuid: UUID of the file identified
:param FormatVersion format: FormatVersion it was identified as
:param str output: Text that generated the match
"""
if format.pronom_id:
format_registry = "PRONOM"
key = format.pronom_id
else:
format_registry = "Archivematica Format Policy Registry"
key = output
# Sometimes, this is null instead of an empty string
version = format.version or ""
FileID.objects.create(
file_id=file_uuid,
format_name=format.format.description,
format_version=version,
format_registry_name=format_registry,
format_registry_key=key,
)
def _default_idcommand():
"""Retrieve the default ``fpr.IDCommand``.
We only expect to find one command enabled/active.
"""
return IDCommand.active.first()
def main(job, enabled, file_path, file_uuid, disable_reidentify):
enabled = True if enabled == "True" else False
if not enabled:
job.print_output("Skipping file format identification")
return 0
command = _default_idcommand()
if command is None:
job.write_error("Unable to determine IDCommand.\n")
return 255
command_uuid = command.uuid
job.print_output("IDCommand:", command.description)
job.print_output("IDCommand UUID:", command.uuid)
job.print_output("IDTool:", command.tool.description)
job.print_output("IDTool UUID:", command.tool.uuid)
job.print_output(f"File: ({file_uuid}) {file_path}")
file_ = File.objects.get(uuid=file_uuid)
# If reidentification is disabled and a format identification event exists for this file, exit
if (
disable_reidentify
and file_.event_set.filter(event_type="format identification").exists()
):
job.print_output(
"This file has already been identified, and re-identification is disabled. Skipping."
)
return 0
# Save whether identification was enabled by the user for use in a later
# chain.
_save_id_preference(file_, enabled)
exitcode, output, err = executeOrRun(
command.script_type,
command.script,
arguments=[file_path],
printing=False,
capture_output=True,
)
output = output.strip()
if exitcode != 0:
job.print_error(f"Error: IDCommand with UUID {command_uuid} exited non-zero.")
job.print_error(f"Error: {err}")
return 255
job.print_output("Command output:", output)
# PUIDs are the same regardless of tool, so PUID-producing tools don't have "rules" per se - we just
# go straight to the FormatVersion table to see if there's a matching PUID
try:
if command.config == "PUID":
version = FormatVersion.active.get(pronom_id=output)
else:
rule = IDRule.active.get(command_output=output, command=command)
version = rule.format
except IDRule.DoesNotExist:
job.print_error(
'Error: No FPR identification rule for tool output "{}" found'.format(
output
)
)
write_identification_event(file_uuid, command, success=False)
return 255
except IDRule.MultipleObjectsReturned:
job.print_error(
'Error: Multiple FPR identification rules for tool output "{}" found'.format(
output
)
)
write_identification_event(file_uuid, command, success=False)
return 255
except FormatVersion.DoesNotExist:
job.print_error(f"Error: No FPR format record found for PUID {output}")
write_identification_event(file_uuid, command, success=False)
return 255
(ffv, created) = FileFormatVersion.objects.get_or_create(
file_uuid=file_, defaults={"format_version": version}
)
if not created: # Update the version if it wasn't created new
ffv.format_version = version
ffv.save()
job.print_output(f"{file_path} identified as a {version.description}")
write_identification_event(file_uuid, command, format=version.pronom_id)
write_file_id(file_uuid=file_uuid, format=version, output=output)
return 0
def call(jobs):
parser = argparse.ArgumentParser(description="Identify file formats.")
# Since AM19 the accepted values are "True" or "False" since the ability to
# choose the command from the workflow has been removed. Instead, this
# script will look up in FPR what's the preferred command.
# This argument may be renamed later.
parser.add_argument("idcommand", type=str, help="%IDCommand%")
parser.add_argument("file_path", type=str, help="%relativeLocation%")
parser.add_argument("file_uuid", type=str, help="%fileUUID%")
parser.add_argument(
"--disable-reidentify",
action="store_true",
help="Disable identification if it has already happened for this file.",
)
with transaction.atomic():
for job in jobs:
with job.JobContext():
args = parser.parse_args(job.args[1:])
job.set_status(
main(
job,
args.idcommand,
args.file_path,
args.file_uuid,
args.disable_reidentify,
)
)
|
dissemin | model_gettext | # coding:utf-8
gettext("Computer science, knowledge & systems")
gettext("Bibliographies")
gettext("Library & information sciences")
gettext("Encyclopedias & books of facts")
gettext("Magazines, journals & serials")
gettext("Associations, organizations & museums")
gettext("News media, journalism & publishing")
gettext("Quotations")
gettext("Manuscripts & rare books")
gettext("Philosophy")
gettext("Metaphysics")
gettext("Epistemology")
gettext("Parapsychology & occultism")
gettext("Philosophical schools of thought")
gettext("Psychology")
gettext("Philosophical logic")
gettext("Ethics")
gettext("Ancient, medieval & eastern philosophy")
gettext("Modern western philosophy")
gettext("Religion")
gettext("Philosophy & theory of religion")
gettext("The Bible")
gettext("Christianity")
gettext("Christian practice & observance")
gettext("Christian pastoral practice & religious orders")
gettext("Christian organization, social work & worship")
gettext("History of Christianity")
gettext("Christian denominations")
gettext("Other religions")
gettext("Social sciences, sociology & anthropology")
gettext("Statistics")
gettext("Political science")
gettext("Economics")
gettext("Law")
gettext("Public administration & military science")
gettext("Social problems & social services")
gettext("Education")
gettext("Commerce, communications & transportation")
gettext("Customs, etiquette & folklore")
gettext("Language")
gettext("Linguistics")
gettext("English & Old English languages")
gettext("German & related languages")
gettext("French & related languages")
gettext("Italian, Romanian & related languages")
gettext("Spanish, Portuguese, Galician")
gettext("Latin & Italic languages")
gettext("Classical & modern Greek languages")
gettext("Other languages")
gettext("Science")
gettext("Mathematics")
gettext("Astronomy")
gettext("Physics")
gettext("Chemistry")
gettext("Earth sciences & geology")
gettext("Fossils & prehistoric life")
gettext("Biology")
gettext("Plants (Botany)")
gettext("Animals (Zoology)")
gettext("Technology")
gettext("Medicine & health")
gettext("Engineering")
gettext("Agriculture")
gettext("Home & family management")
gettext("Management & public relations")
gettext("Chemical engineering")
gettext("Manufacturing")
gettext("Manufacture for specific uses")
gettext("Construction of buildings")
gettext("Arts")
gettext("Area planning & landscape architecture")
gettext("Architecture")
gettext("Sculpture, ceramics & metalwork")
gettext("Graphic arts & decorative arts")
gettext("Painting")
gettext("Printmaking & prints")
gettext("Photography, computer art, film, video")
gettext("Music")
gettext("Sports, games & entertainment")
gettext("Literature, rhetoric & criticism")
gettext("American literature in English")
gettext("English & Old English literatures")
gettext("German & related literatures")
gettext("French & related literatures")
gettext("Italian, Romanian & related literatures")
gettext("Spanish, Portuguese, Galician literatures")
gettext("Latin & Italic literatures")
gettext("Classical & modern Greek literatures")
gettext("Other literatures")
gettext("History")
gettext("Geography & travel")
gettext("Biography & genealogy")
gettext("History of ancient world (to ca. 499)")
gettext("History of Europe")
gettext("History of Asia")
gettext("History of Africa")
gettext("History of North America")
gettext("History of South America")
gettext("History of other areas")
gettext("Data processing & computer science")
gettext("Military science")
gettext("Other Germanic languages")
gettext("Public performances")
gettext("Stage presentations")
gettext("Indoor games & amusements")
gettext("Athletic & outdoor sports & games")
gettext("Other Germanic literatures")
gettext("Germany & neighboring central European countries")
gettext("Green Open Access Service")
gettext(
'Would you like that the University and State Library Darmstadt publishes your publications green open access for you?\n<br/>\nContact us: <a href="mailto:dpub@ulb-tu-darmstadt.de">dpub@ulb-tu-darmstadt.de</a>'
)
gettext("TUprints contract required!")
gettext(
"We need the TUprints agreement for all documents uploaded through Dissemin. After authentification with your TU-ID, please fill out the agreement and send it digitally. A signature is not necessary."
)
gettext("Fill in agreement")
gettext("Contract necessary!")
gettext(
"Before we can publish your publication, we need the completely filled in and signed publication agreement, which you can send to Braunschweig University Library by e-mail, fax or postal mail."
)
gettext("Download Contract")
gettext("Creative Commons 1.0 Universal (CC0 1.0) Public Domain Dedication")
gettext("Creative Commons Attribution 4.0 International (CC BY 4.0)")
gettext("Creative Commons Attribution-ShareAlike 4.0, International (CC BY-SA 4.0)")
gettext("Creative Commons Attribution-NonCommerical 4.0 International (CC BY-NC 4.0)")
gettext("Creative Commons Attribution-NoDerivatives 4.0 International (CC BY-ND 4.0)")
gettext(
"Free for private use; right holder retains other rights, including distribution"
)
gettext("Other open license")
gettext("No license")
gettext(
"Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0)"
)
gettext(
"Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0)"
)
gettext("Zenodo")
gettext(
"Zenodo is a general-purpose open repository hosted by CERN. If the document does not have a DOI yet, Zenodo will create one."
)
gettext("HAL")
gettext(
"HAL is a multidisciplinary open archive, sustained by the French Research Ministry."
)
gettext("OSF preprints")
gettext(
"Run by the Center for Open Science, OSF lets you share your preprints openly. You can also share supplemental data, materials or code associated with your article."
)
gettext("TUprints")
gettext(
"TUprints is the open access repository for all current and former members of the Technical University Darmstadt."
)
gettext("Institutional Repository of TU Braunschweig")
gettext(
"Researchers at TU Braunschweig can publish their first and second (self archiving) publications Open Access on the official publication server of TU Braunschweig."
)
|
aliceVision | PanoramaPostProcessing | __version__ = "2.0"
import json
import os
from meshroom.core import desc
class PanoramaPostProcessing(desc.CommandLineNode):
commandLine = "aliceVision_panoramaPostProcessing {allParams}"
cpu = desc.Level.NORMAL
ram = desc.Level.INTENSIVE
category = "Panorama HDR"
documentation = """
Post process the panorama.
"""
inputs = [
desc.File(
name="inputPanorama",
label="Input Panorama",
description="Input panorama image.",
value="",
uid=[0],
),
desc.BoolParam(
name="fillHoles",
label="Fill Holes Algorithm",
description="Fill the non attributed pixels with push pull algorithm if set.",
value=False,
uid=[0],
),
desc.BoolParam(
name="exportLevels",
label="Export Downscaled Levels",
description="Export downscaled panorama levels.",
value=False,
uid=[0],
),
desc.IntParam(
name="lastLevelMaxSize",
label="Last Level Max Size",
description="Maximum width of smallest downscaled panorama level.",
value=3840,
range=(1, 100000),
uid=[0],
),
desc.IntParam(
name="previewSize",
label="Panorama Preview Width",
description="The width (in pixels) of the output panorama preview.",
value=1000,
range=(0, 5000, 100),
uid=[0],
),
desc.ChoiceParam(
name="outputColorSpace",
label="Output Color Space",
description="The color space of the output image.",
value="Linear",
values=["sRGB", "rec709", "Linear", "ACES2065-1", "ACEScg"],
exclusive=True,
uid=[0],
),
desc.ChoiceParam(
name="compressionMethod",
label="Compression Method",
description="Compression method for output EXR image.",
value="auto",
values=[
"none",
"auto",
"rle",
"zip",
"zips",
"piz",
"pxr24",
"b44",
"b44a",
"dwaa",
"dwab",
],
exclusive=True,
uid=[0],
),
desc.IntParam(
name="compressionLevel",
label="Compression Level",
description="Level of compression for the output EXR image. The range depends on method used.\n"
"For zip/zips methods, values must be between 1 and 9.\n"
"A value of 0 will be ignored, default value for the selected method will be used.",
value=0,
range=(0, 500, 1),
uid=[0],
enabled=lambda node: node.compressionMethod.value
in ["dwaa", "dwab", "zip", "zips"],
),
desc.StringParam(
name="panoramaName",
label="Output Panorama Name",
description="Name of the output panorama.",
value="panorama.exr",
uid=[],
group=None,
advanced=True,
),
desc.StringParam(
name="previewName",
label="Panorama Preview Name",
description="Name of the preview of the output panorama.",
value="panoramaPreview.jpg",
uid=[],
group=None,
advanced=True,
),
desc.ChoiceParam(
name="verboseLevel",
label="Verbose Level",
description="Verbosity level (fatal, error, warning, info, debug, trace).",
value="info",
values=["fatal", "error", "warning", "info", "debug", "trace"],
exclusive=True,
uid=[],
),
]
outputs = [
desc.File(
name="outputPanorama",
label="Output Panorama",
description="Generated panorama in EXR format.",
semantic="image",
value=lambda attr: desc.Node.internalFolder + attr.node.panoramaName.value,
uid=[],
),
desc.File(
name="outputPanoramaPreview",
label="Output Panorama Preview",
description="Preview of the generated panorama in JPG format.",
semantic="image",
value=lambda attr: desc.Node.internalFolder + attr.node.previewName.value,
uid=[],
),
desc.File(
name="downscaledPanoramaLevels",
label="Downscaled Panorama Levels",
description="Downscaled versions of the generated panorama.",
value=lambda attr: desc.Node.internalFolder
+ os.path.splitext(attr.node.panoramaName.value)[0]
+ "_level_*.exr",
uid=[],
group="",
),
]
|
gui | import_network_panel | # --------------------------------------------------------------------------
# Software: InVesalius - Software de Reconstrucao 3D de Imagens Medicas
# Copyright: (C) 2001 Centro de Pesquisas Renato Archer
# Homepage: http://www.softwarepublico.gov.br
# Contact: invesalius@cti.gov.br
# License: GNU - GPL 2 (LICENSE.txt/LICENCA.txt)
# --------------------------------------------------------------------------
# Este programa e software livre; voce pode redistribui-lo e/ou
# modifica-lo sob os termos da Licenca Publica Geral GNU, conforme
# publicada pela Free Software Foundation; de acordo com a versao 2
# da Licenca.
#
# Este programa eh distribuido na expectativa de ser util, mas SEM
# QUALQUER GARANTIA; sem mesmo a garantia implicita de
# COMERCIALIZACAO ou de ADEQUACAO A QUALQUER PROPOSITO EM
# PARTICULAR. Consulte a Licenca Publica Geral GNU para obter mais
# detalhes.
# --------------------------------------------------------------------------
import sys
import invesalius.constants as const
import invesalius.gui.dialogs as dlg
import invesalius.net.dicom as dcm_net
# import invesalius.gui.dicom_preview_panel as dpp
import invesalius.reader.dicom_grouper as dcm
import wx
import wx.gizmos as gizmos
# from dicionario import musicdata
import wx.lib.mixins.listctrl as listmix
import wx.lib.splitter as spl
from invesalius.pubsub import pub as Publisher
from wx.lib.mixins.listctrl import CheckListCtrlMixin
myEVT_SELECT_SERIE = wx.NewEventType()
EVT_SELECT_SERIE = wx.PyEventBinder(myEVT_SELECT_SERIE, 1)
myEVT_SELECT_SLICE = wx.NewEventType()
EVT_SELECT_SLICE = wx.PyEventBinder(myEVT_SELECT_SLICE, 1)
myEVT_SELECT_PATIENT = wx.NewEventType()
EVT_SELECT_PATIENT = wx.PyEventBinder(myEVT_SELECT_PATIENT, 1)
myEVT_SELECT_SERIE_TEXT = wx.NewEventType()
EVT_SELECT_SERIE_TEXT = wx.PyEventBinder(myEVT_SELECT_SERIE_TEXT, 1)
class SelectEvent(wx.PyCommandEvent):
def __init__(self, evtType, id):
super(SelectEvent, self).__init__(evtType, id)
def GetSelectID(self):
return self.SelectedID
def SetSelectedID(self, id):
self.SelectedID = id
def GetItemData(self):
return self.data
def SetItemData(self, data):
self.data = data
class Panel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent, pos=wx.Point(5, 5)) # ,
# size=wx.Size(280, 656))
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(InnerPanel(self), 1, wx.EXPAND | wx.GROW | wx.ALL, 5)
self.SetSizer(sizer)
sizer.Fit(self)
self.Layout()
self.Update()
self.SetAutoLayout(1)
# Inner fold panel
class InnerPanel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent, pos=wx.Point(5, 5)) # ,
# size=wx.Size(680, 656))
self.patients = []
self.first_image_selection = None
self.last_image_selection = None
self._init_ui()
self._bind_events()
self._bind_pubsubevt()
def _init_ui(self):
splitter = spl.MultiSplitterWindow(self, style=wx.SP_LIVE_UPDATE)
splitter.SetOrientation(wx.VERTICAL)
self.splitter = splitter
panel = wx.Panel(self)
self.btn_cancel = wx.Button(panel, wx.ID_CANCEL)
self.btn_ok = wx.Button(panel, wx.ID_OK, _("Import"))
btnsizer = wx.StdDialogButtonSizer()
btnsizer.AddButton(self.btn_ok)
btnsizer.AddButton(self.btn_cancel)
btnsizer.Realize()
self.combo_interval = wx.ComboBox(
panel,
-1,
"",
choices=const.IMPORT_INTERVAL,
style=wx.CB_DROPDOWN | wx.CB_READONLY,
)
self.combo_interval.SetSelection(0)
inner_sizer = wx.BoxSizer(wx.HORIZONTAL)
inner_sizer.Add(btnsizer, 0, wx.LEFT | wx.TOP, 5)
inner_sizer.Add(self.combo_interval, 0, wx.LEFT | wx.RIGHT | wx.TOP, 5)
panel.SetSizer(inner_sizer)
inner_sizer.Fit(panel)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(splitter, 20, wx.EXPAND)
sizer.Add(panel, 1, wx.EXPAND | wx.LEFT, 90)
self.SetSizer(sizer)
sizer.Fit(self)
self.image_panel = HostFindPanel(splitter)
splitter.AppendWindow(self.image_panel, 250)
self.text_panel = TextPanel(splitter)
splitter.AppendWindow(self.text_panel, 250)
self.Layout()
self.Update()
self.SetAutoLayout(1)
def _bind_pubsubevt(self):
# Publisher.subscribe(self.ShowDicomPreview, "Load import panel")
# Publisher.subscribe(self.GetSelectedImages ,"Selected Import Images")
pass
def GetSelectedImages(self, pubsub_evt):
self.first_image_selection = pubsub_evt.data[0]
self.last_image_selection = pubsub_evt.data[1]
def _bind_events(self):
self.Bind(EVT_SELECT_SERIE, self.OnSelectSerie)
self.Bind(EVT_SELECT_SLICE, self.OnSelectSlice)
self.Bind(EVT_SELECT_PATIENT, self.OnSelectPatient)
self.btn_ok.Bind(wx.EVT_BUTTON, self.OnClickOk)
self.btn_cancel.Bind(wx.EVT_BUTTON, self.OnClickCancel)
self.text_panel.Bind(EVT_SELECT_SERIE_TEXT, self.OnDblClickTextPanel)
def ShowDicomPreview(self, pubsub_evt):
dicom_groups = pubsub_evt.data
self.patients.extend(dicom_groups)
self.text_panel.Populate(dicom_groups)
def OnSelectSerie(self, evt):
patient_id, serie_number = evt.GetSelectID()
self.text_panel.SelectSerie(evt.GetSelectID())
for patient in self.patients:
if patient_id == patient.GetDicomSample().patient.id:
for group in patient.GetGroups():
if serie_number == group.GetDicomSample().acquisition.serie_number:
self.image_panel.SetSerie(group)
def OnSelectSlice(self, evt):
pass
def OnSelectPatient(self, evt):
pass
def OnDblClickTextPanel(self, evt):
group = evt.GetItemData()
self.LoadDicom(group)
def OnClickOk(self, evt):
group = self.text_panel.GetSelection()
if group:
self.LoadDicom(group)
def OnClickCancel(self, evt):
# Publisher.sendMessage("Cancel DICOM load")
pass
def LoadDicom(self, group):
interval = self.combo_interval.GetSelection()
if not isinstance(group, dcm.DicomGroup):
group = max(group.GetGroups(), key=lambda g: g.nslices)
slice_amont = group.nslices
if (self.first_image_selection != None) and (
self.first_image_selection != self.last_image_selection
):
slice_amont = (self.last_image_selection) - self.first_image_selection
slice_amont += 1
if slice_amont == 0:
slice_amont = group.nslices
nslices_result = slice_amont / (interval + 1)
if nslices_result > 1:
# Publisher.sendMessage('Open DICOM group', (group, interval,
# [self.first_image_selection, self.last_image_selection]))
pass
else:
dlg.MissingFilesForReconstruction()
class TextPanel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent, -1)
self._selected_by_user = True
self.idserie_treeitem = {}
self.treeitem_idpatient = {}
self.__init_gui()
self.__bind_events_wx()
self.__bind_pubsub_evt()
def __bind_pubsub_evt(self):
# Publisher.subscribe(self.SelectSeries, 'Select series in import panel')
Publisher.subscribe(self.Populate, "Populate tree")
Publisher.subscribe(self.SetHostsList, "Set FindPanel hosts list")
def __bind_events_wx(self):
self.Bind(wx.EVT_SIZE, self.OnSize)
def __init_gui(self):
tree = gizmos.TreeListCtrl(
self,
-1,
style=wx.TR_DEFAULT_STYLE
| wx.TR_HIDE_ROOT
| wx.TR_ROW_LINES
# | wx.TR_COLUMN_LINES
| wx.TR_FULL_ROW_HIGHLIGHT
| wx.TR_SINGLE,
)
tree.AddColumn(_("Patient name"))
tree.AddColumn(_("Patient ID"))
tree.AddColumn(_("Age"))
tree.AddColumn(_("Gender"))
tree.AddColumn(_("Study description"))
tree.AddColumn(_("Modality"))
tree.AddColumn(_("Date acquired"))
tree.AddColumn(_("# Images"))
tree.AddColumn(_("Institution"))
tree.AddColumn(_("Date of birth"))
tree.AddColumn(_("Accession Number"))
tree.AddColumn(_("Referring physician"))
tree.SetMainColumn(0) # the one with the tree in it...
tree.SetColumnWidth(0, 280) # Patient name
tree.SetColumnWidth(1, 110) # Patient ID
tree.SetColumnWidth(2, 40) # Age
tree.SetColumnWidth(3, 60) # Gender
tree.SetColumnWidth(4, 160) # Study description
tree.SetColumnWidth(5, 70) # Modality
tree.SetColumnWidth(6, 200) # Date acquired
tree.SetColumnWidth(7, 70) # Number Images
tree.SetColumnWidth(8, 130) # Institution
tree.SetColumnWidth(9, 100) # Date of birth
tree.SetColumnWidth(10, 140) # Accession Number
tree.SetColumnWidth(11, 160) # Referring physician
self.root = tree.AddRoot(_("InVesalius Database"))
self.tree = tree
def SelectSeries(self, group_index):
pass
def Populate(self, pubsub_evt):
tree = self.tree
# print ">>>>>>>>>>>>>>>>>>>>>>>>>>", dir(tree.GetRootItem())
# print ">>>>>>>>>>>>",dir(self.tree)
patients = pubsub_evt.data
first = 0
self.idserie_treeitem = {}
for patient in patients.keys():
# ngroups = patient.ngroups
# dicom = patient.GetDicomSample()
# title = dicom.patient.name + " (%d series)"%(ngroups)
# date_time = "%s %s"%(dicom.acquisition.date,
# dicom.acquisition.time)
first_serie = patients[patient].keys()[0]
title = patients[patient][first_serie]["name"]
p = patients[patient][first_serie]
p_id = patient
age = p["age"]
gender = p["gender"]
study_description = p["study_description"]
modality = p["modality"]
date = p["acquisition_date"]
time = p["acquisition_time"]
institution = p["institution"]
birthdate = p["date_of_birth"]
acession_number = p["acession_number"]
physician = p["ref_physician"]
parent = tree.AppendItem(self.root, title)
n_amount_images = 0
for se in patients[patient]:
n_amount_images = n_amount_images + patients[patient][se]["n_images"]
tree.SetItemPyData(parent, patient)
tree.SetItemText(parent, "%s" % p_id, 1)
tree.SetItemText(parent, "%s" % age, 2)
tree.SetItemText(parent, "%s" % gender, 3)
tree.SetItemText(parent, "%s" % study_description, 4)
tree.SetItemText(parent, "%s" % "", 5)
tree.SetItemText(parent, "%s" % date + " " + time, 6)
tree.SetItemText(parent, "%s" % str(n_amount_images), 7)
tree.SetItemText(parent, "%s" % institution, 8)
tree.SetItemText(parent, "%s" % birthdate, 9)
tree.SetItemText(parent, "%s" % acession_number, 10)
tree.SetItemText(parent, "%s" % physician, 11)
for series in patients[patient].keys():
serie_description = patients[patient][series]["serie_description"]
n_images = patients[patient][series]["n_images"]
date = patients[patient][series]["acquisition_date"]
time = patients[patient][series]["acquisition_time"]
modality = patients[patient][series]["modality"]
child = tree.AppendItem(parent, series)
tree.SetItemPyData(child, series)
tree.SetItemText(child, "%s" % serie_description, 0)
# tree.SetItemText(child, "%s" % dicom.acquisition.protocol_name, 4)
tree.SetItemText(child, "%s" % modality, 5)
tree.SetItemText(child, "%s" % date + " " + time, 6)
tree.SetItemText(child, "%s" % n_images, 7)
self.idserie_treeitem[(patient, series)] = child
tree.Expand(self.root)
# tree.SelectItem(parent_select)
tree.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.OnActivate)
# tree.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnSelChanged)
"""
for patient in patient_list:
if not isinstance(patient, dcm.PatientGroup):
return None
ngroups = patient.ngroups
dicom = patient.GetDicomSample()
title = dicom.patient.name + " (%d series)"%(ngroups)
date_time = "%s %s"%(dicom.acquisition.date,
dicom.acquisition.time)
parent = tree.AppendItem(self.root, title)
if not first:
parent_select = parent
first += 1
tree.SetItemPyData(parent, patient)
tree.SetItemText(parent, "%s" % dicom.patient.id, 1)
tree.SetItemText(parent, "%s" % dicom.patient.age, 2)
tree.SetItemText(parent, "%s" % dicom.patient.gender, 3)
tree.SetItemText(parent, "%s" % dicom.acquisition.study_description, 4)
tree.SetItemText(parent, "%s" % dicom.acquisition.modality, 5)
tree.SetItemText(parent, "%s" % date_time, 6)
tree.SetItemText(parent, "%s" % patient.nslices, 7)
tree.SetItemText(parent, "%s" % dicom.acquisition.institution, 8)
tree.SetItemText(parent, "%s" % dicom.patient.birthdate, 9)
tree.SetItemText(parent, "%s" % dicom.acquisition.accession_number, 10)
tree.SetItemText(parent, "%s" % dicom.patient.physician, 11)
group_list = patient.GetGroups()
for n, group in enumerate(group_list):
dicom = group.GetDicomSample()
child = tree.AppendItem(parent, group.title)
tree.SetItemPyData(child, group)
tree.SetItemText(child, "%s" % group.title, 0)
tree.SetItemText(child, "%s" % dicom.acquisition.protocol_name, 4)
tree.SetItemText(child, "%s" % dicom.acquisition.modality, 5)
tree.SetItemText(child, "%s" % date_time, 6)
tree.SetItemText(child, "%s" % group.nslices, 7)
self.idserie_treeitem[(dicom.patient.id,
dicom.acquisition.serie_number)] = child
tree.Expand(self.root)
tree.SelectItem(parent_select)
tree.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.OnActivate)
tree.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnSelChanged)"""
def SetHostsList(self, evt_pub):
self.hosts = evt_pub.data
def GetHostList(self):
Publisher.sendMessage("Get NodesPanel host list")
return self.hosts
def OnSelChanged(self, evt):
item = self.tree.GetSelection()
if self._selected_by_user:
group = self.tree.GetItemPyData(item)
if isinstance(group, dcm.DicomGroup):
# Publisher.sendMessage('Load group into import panel',
# group)
pass
elif isinstance(group, dcm.PatientGroup):
id = group.GetDicomSample().patient.id
my_evt = SelectEvent(myEVT_SELECT_PATIENT, self.GetId())
my_evt.SetSelectedID(id)
self.GetEventHandler().ProcessEvent(my_evt)
# Publisher.sendMessage('Load patient into import panel',
# group)
else:
parent_id = self.tree.GetItemParent(item)
self.tree.Expand(parent_id)
evt.Skip()
def OnActivate(self, evt):
item = evt.GetItem()
item_parent = self.tree.GetItemParent(item)
patient_id = self.tree.GetItemPyData(item_parent)
serie_id = self.tree.GetItemPyData(item)
hosts = self.GetHostList()
for key in hosts.keys():
if key != 0:
dn = dcm_net.DicomNet()
dn.SetHost(self.hosts[key][1])
dn.SetPort(self.hosts[key][2])
dn.SetAETitleCall(self.hosts[key][3])
dn.SetAETitle(self.hosts[0][3])
dn.RunCMove((patient_id, serie_id))
# dn.SetSearchWord(self.find_txt.GetValue())
# Publisher.sendMessage('Populate tree', dn.RunCFind())
# my_evt = SelectEvent(myEVT_SELECT_SERIE_TEXT, self.GetId())
# my_evt.SetItemData(group)
# self.GetEventHandler().ProcessEvent(my_evt)
def OnSize(self, evt):
self.tree.SetSize(self.GetSize())
def SelectSerie(self, serie):
self._selected_by_user = False
item = self.idserie_treeitem[serie]
self.tree.SelectItem(item)
self._selected_by_user = True
def GetSelection(self):
"""Get selected item"""
item = self.tree.GetSelection()
group = self.tree.GetItemPyData(item)
return group
class FindPanel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent, -1)
self.sizer = wx.BoxSizer(wx.VERTICAL)
sizer_word_label = wx.BoxSizer(wx.HORIZONTAL)
sizer_word_label.Add((5, 0), 0, wx.EXPAND | wx.HORIZONTAL)
find_label = wx.StaticText(self, -1, _("Word"))
sizer_word_label.Add(find_label)
sizer_txt_find = wx.BoxSizer(wx.HORIZONTAL)
sizer_txt_find.Add((5, 0), 0, wx.EXPAND | wx.HORIZONTAL)
self.find_txt = wx.TextCtrl(self, -1, size=(225, -1))
self.btn_find = wx.Button(self, -1, _("Search"))
sizer_txt_find.Add(self.find_txt)
sizer_txt_find.Add(self.btn_find)
self.sizer.Add((0, 5), 0, wx.EXPAND | wx.HORIZONTAL)
self.sizer.Add(sizer_word_label)
self.sizer.Add(sizer_txt_find)
# self.sizer.Add(self.serie_preview, 1, wx.EXPAND | wx.ALL, 5)
# self.sizer.Add(self.dicom_preview, 1, wx.EXPAND | wx.ALL, 5)
self.sizer.Fit(self)
self.SetSizer(self.sizer)
self.Layout()
self.Update()
self.SetAutoLayout(1)
self.__bind_evt()
self._bind_gui_evt()
def __bind_evt(self):
Publisher.subscribe(self.SetHostsList, "Set FindPanel hosts list")
# Publisher.subscribe(self.ShowDicomSeries, 'Load dicom preview')
# Publisher.subscribe(self.SetDicomSeries, 'Load group into import panel')
# Publisher.subscribe(self.SetPatientSeries, 'Load patient into import panel')
pass
def _bind_gui_evt(self):
# self.serie_preview.Bind(dpp.EVT_CLICK_SERIE, self.OnSelectSerie)
# self.dicom_preview.Bind(dpp.EVT_CLICK_SLICE, self.OnSelectSlice)
self.Bind(wx.EVT_BUTTON, self.OnButtonFind, self.btn_find)
def OnButtonFind(self, evt):
hosts = self.GetHostList()
for key in hosts.keys():
if key != 0:
dn = dcm_net.DicomNet()
dn.SetHost(self.hosts[key][1])
dn.SetPort(self.hosts[key][2])
dn.SetAETitleCall(self.hosts[key][3])
dn.SetAETitle(self.hosts[0][3])
dn.SetSearchWord(self.find_txt.GetValue())
Publisher.sendMessage("Populate tree", dn.RunCFind())
def SetHostsList(self, evt_pub):
self.hosts = evt_pub.data
def GetHostList(self):
Publisher.sendMessage("Get NodesPanel host list")
return self.hosts
class HostFindPanel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent, -1)
self._init_ui()
self._bind_events()
def _init_ui(self):
splitter = spl.MultiSplitterWindow(self, style=wx.SP_LIVE_UPDATE)
splitter.SetOrientation(wx.HORIZONTAL)
self.splitter = splitter
# TODO: Rever isso
# splitter.ContainingSizer = wx.BoxSizer(wx.HORIZONTAL)
sizer = wx.BoxSizer(wx.HORIZONTAL)
sizer.Add(splitter, 1, wx.EXPAND)
self.SetSizer(sizer)
self.image_panel = NodesPanel(splitter)
splitter.AppendWindow(self.image_panel, 500)
self.text_panel = FindPanel(splitter)
splitter.AppendWindow(self.text_panel, 750)
self.SetSizer(sizer)
sizer.Fit(self)
self.Layout()
self.Update()
self.SetAutoLayout(1)
def _bind_events(self):
self.text_panel.Bind(EVT_SELECT_SERIE, self.OnSelectSerie)
self.text_panel.Bind(EVT_SELECT_SLICE, self.OnSelectSlice)
def OnSelectSerie(self, evt):
evt.Skip()
def OnSelectSlice(self, evt):
self.image_panel.dicom_preview.ShowSlice(evt.GetSelectID())
evt.Skip()
def SetSerie(self, serie):
self.image_panel.dicom_preview.SetDicomGroup(serie)
class NodesTree(
wx.ListCtrl,
CheckListCtrlMixin,
listmix.ListCtrlAutoWidthMixin,
listmix.TextEditMixin,
):
def __init__(self, parent):
self.item = 0
self.col_locs = [0]
self.editorBgColour = wx.Colour(255, 255, 255, 255)
wx.ListCtrl.__init__(self, parent, -1, style=wx.LC_REPORT | wx.LC_HRULES)
listmix.CheckListCtrlMixin.__init__(self)
listmix.TextEditMixin.__init__(self)
def OnCheckItem(self, index, flag):
Publisher.sendMessage("Check item dict", [index, flag])
def OpenEditor(self, col, row):
if col >= 1 and col < 4:
listmix.TextEditMixin.OpenEditor(self, col, row)
else:
listmix.CheckListCtrlMixin.ToggleItem(self, self.item)
def SetSelected(self, item):
self.item = item
def SetDeselected(self, item):
self.item = item
class NodesPanel(wx.Panel):
def __init__(self, parent):
self.selected_item = None
self.hosts = {}
wx.Panel.__init__(self, parent, -1)
self.__init_gui()
self.__bind_evt()
def __bind_evt(self):
self.Bind(wx.EVT_COMMAND_RIGHT_CLICK, self.RightButton, self.tree_node)
self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnItemSelected, self.tree_node)
self.Bind(wx.EVT_LIST_ITEM_DESELECTED, self.OnItemDeselected, self.tree_node)
self.Bind(wx.EVT_BUTTON, self.OnButtonAdd, self.btn_add)
self.Bind(wx.EVT_BUTTON, self.OnButtonRemove, self.btn_remove)
self.Bind(wx.EVT_BUTTON, self.OnButtonCheck, self.btn_check)
self.Bind(wx.EVT_LIST_END_LABEL_EDIT, self.EndEdition, self.tree_node)
Publisher.subscribe(self.CheckItemDict, "Check item dict")
Publisher.subscribe(self.GetHostsList, "Get NodesPanel host list")
# Publisher.subscribe(self.UnCheckItemDict, "Uncheck item dict")
def __init_gui(self):
self.tree_node = NodesTree(self)
self.tree_node.InsertColumn(0, _("Active"))
self.tree_node.InsertColumn(1, _("Host"))
self.tree_node.InsertColumn(2, _("Port"))
self.tree_node.InsertColumn(3, _("AETitle"))
self.tree_node.InsertColumn(4, _("Status"))
self.tree_node.SetColumnWidth(0, 50)
self.tree_node.SetColumnWidth(1, 150)
self.tree_node.SetColumnWidth(2, 50)
self.tree_node.SetColumnWidth(3, 150)
self.tree_node.SetColumnWidth(4, 80)
self.hosts[0] = [True, "localhost", "", "invesalius"]
try:
index = self.tree_node.InsertItem(sys.maxsize, "")
except (OverflowError, AssertionError):
index = self.tree_node.InsertItem(sys.maxint, "")
self.tree_node.SetItem(index, 1, "localhost")
self.tree_node.SetItem(index, 2, "")
self.tree_node.SetItem(index, 3, "invesalius")
self.tree_node.SetItem(index, 4, "ok")
self.tree_node.CheckItem(index)
self.tree_node.SetItemBackgroundColour(index, wx.Colour(245, 245, 245))
# print ">>>>>>>>>>>>>>>>>>>>>", sys.maxint
# index = self.tree_node.InsertItem(sys.maxint, "")#adiciona vazio a coluna de check
# self.tree_node.SetItem(index, 1, "200.144.114.19")
# self.tree_node.SetItem(index, 2, "80")
# self.tree_node.SetItemData(index, 0)
# index2 = self.tree_node.InsertItem(sys.maxint, "")#adiciona vazio a coluna de check
# self.tree_node.SetItem(index2, 1, "200.144.114.19")
# self.tree_node.SetItem(index2, 2, "80")
# self.tree_node.SetItemData(index2, 0)
self.btn_add = wx.Button(self, -1, _("Add"))
self.btn_remove = wx.Button(self, -1, _("Remove"))
self.btn_check = wx.Button(self, -1, _("Check status"))
sizer_btn = wx.BoxSizer(wx.HORIZONTAL)
sizer_btn.Add((90, 0), 0, wx.EXPAND | wx.HORIZONTAL)
sizer_btn.Add(self.btn_add, 10)
sizer_btn.Add(self.btn_remove, 10)
sizer_btn.Add(self.btn_check, 0, wx.ALIGN_CENTER_HORIZONTAL)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.tree_node, 85, wx.GROW | wx.EXPAND)
sizer.Add(sizer_btn, 15)
sizer.Fit(self)
self.SetSizer(sizer)
self.Layout()
self.Update()
self.SetAutoLayout(1)
self.sizer = sizer
def GetHostsList(self, pub_evt):
Publisher.sendMessage("Set FindPanel hosts list", self.hosts)
def EndEdition(self, evt):
index = evt.m_itemIndex
item = evt.m_item
col = item.GetColumn()
txt = item.GetText()
values = self.hosts[index]
values[col] = str(txt)
self.hosts[index] = values
def OnButtonAdd(self, evt):
# adiciona vazio a coluna de check
index = self.tree_node.InsertItem(sys.maxsize, "")
self.hosts[index] = [True, "localhost", "80", ""]
self.tree_node.SetItem(index, 1, "localhost")
self.tree_node.SetItem(index, 2, "80")
self.tree_node.SetItem(index, 3, "")
self.tree_node.CheckItem(index)
def OnLeftDown(self, evt):
evt.Skip()
def OnButtonRemove(self, evt):
if self.selected_item != None and self.selected_item != 0:
self.tree_node.DeleteItem(self.selected_item)
self.hosts.pop(self.selected_item)
self.selected_item = None
k = self.hosts.keys()
tmp_cont = 0
tmp_host = {}
for x in k:
tmp_host[tmp_cont] = self.hosts[x]
tmp_cont += 1
self.hosts = tmp_host
def OnButtonCheck(self, evt):
for key in self.hosts.keys():
if key != 0:
dn = dcm_net.DicomNet()
dn.SetHost(self.hosts[key][1])
dn.SetPort(self.hosts[key][2])
dn.SetAETitleCall(self.hosts[key][3])
dn.SetAETitle(self.hosts[0][3])
if dn.RunCEcho():
self.tree_node.SetItem(key, 4, _("ok"))
else:
self.tree_node.SetItem(key, 4, _("error"))
def RightButton(self, evt):
event.Skip()
def OnItemSelected(self, evt):
self.selected_item = evt.m_itemIndex
self.tree_node.SetSelected(evt.m_itemIndex)
def OnItemDeselected(self, evt):
if evt.m_itemIndex != 0:
self.tree_node.SetDeselected(evt.m_itemIndex)
def CheckItemDict(self, evt_pub):
index, flag = evt_pub.data
if index != 0:
self.hosts[index][0] = flag
else:
self.tree_node.CheckItem(0)
|
minimode | minimode_preferences | # Copyright (C) 2009-2010 Mathias Brodala
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import os.path
from xl import providers
from xl.nls import gettext as _
from xlgui import icons
from xlgui.preferences import widgets
name = _("Mini Mode")
basedir = os.path.dirname(os.path.realpath(__file__))
ui = os.path.join(basedir, "minimode_preferences.ui")
icons.MANAGER.add_icon_name_from_directory(
"exaile-minimode", os.path.join(basedir, "icons")
)
icon = "exaile-minimode"
class AlwaysOnTopPreference(widgets.CheckPreference):
name = "plugin/minimode/always_on_top"
default = True
class ShowInPanelPreference(widgets.CheckPreference):
name = "plugin/minimode/show_in_panel"
default = False
class OnAllDesktopsPreference(widgets.CheckPreference):
name = "plugin/minimode/on_all_desktops"
default = True
class ButtonInMainWindowPreference(widgets.CheckPreference):
name = "plugin/minimode/button_in_mainwindow"
default = False
class DisplayWindowDecorationsPreference(widgets.CheckPreference):
name = "plugin/minimode/display_window_decorations"
default = True
class WindowDecorationTypePreference(widgets.ComboPreference, widgets.CheckConditional):
name = "plugin/minimode/window_decoration_type"
default = "full"
condition_preference_name = "plugin/minimode/display_window_decorations"
def __init__(self, preferences, widget):
widgets.ComboPreference.__init__(self, preferences, widget)
widgets.CheckConditional.__init__(self)
class UseAlphaTransparencyPreference(widgets.CheckPreference):
default = False
name = "plugin/minimode/use_alpha"
class TransparencyPreference(widgets.ScalePreference, widgets.CheckConditional):
default = 0.3
name = "plugin/minimode/transparency"
condition_preference_name = "plugin/minimode/use_alpha"
def __init__(self, preferences, widget):
widgets.ScalePreference.__init__(self, preferences, widget)
widgets.CheckConditional.__init__(self)
class SelectedControlsPreference(widgets.SelectionListPreference):
name = "plugin/minimode/selected_controls"
default = [
"previous",
"play_pause",
"next",
"playlist_button",
"progress_bar",
"restore",
]
def __init__(self, preferences, widget):
self.items = [
self.Item(p.name, p.title, p.description, p.fixed)
for p in providers.get("minimode-controls")
]
widgets.SelectionListPreference.__init__(self, preferences, widget)
class TrackTitleFormatPreference(widgets.ComboEntryPreference):
name = "plugin/minimode/track_title_format"
completion_items = {
"$tracknumber": _("Track number"),
"$title": _("Title"),
"$artist": _("Artist"),
"$composer": _("Composer"),
"$album": _("Album"),
"$__length": _("Length"),
"$discnumber": _("Disc number"),
"$__rating": _("Rating"),
"$date": _("Date"),
"$genre": _("Genre"),
"$bitrate": _("Bitrate"),
"$__loc": _("Location"),
"$filename": _("Filename"),
"$__playcount": _("Play count"),
"$__last_played": _("Last played"),
"$bpm": _("BPM"),
}
preset_items = [
# TRANSLATORS: Mini mode track selector title preset
_("$tracknumber - $title"),
# TRANSLATORS: Mini mode track selector title preset
_("$title by $artist"),
# TRANSLATORS: Mini mode track selector title preset
_("$title ($__length)"),
]
default = _("$tracknumber - $title")
|
gamedata | metaData | # ===============================================================================
# Copyright (C) 2010 Diego Duclos
#
# This file is part of eos.
#
# eos is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# eos is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with eos. If not, see <http://www.gnu.org/licenses/>.
# ===============================================================================
from eos.db import gamedata_meta
from eos.gamedata import MetaData
from sqlalchemy import Column, String, Table
from sqlalchemy.orm import mapper
metadata_table = Table(
"metadata",
gamedata_meta,
Column("field_name", String, primary_key=True),
Column("field_value", String),
)
mapper(MetaData, metadata_table)
|
installer | fix_qt5_rpath | """Methods to fix Mac OS X @rpath and /usr/local dependencies, and analyze the
app bundle for OpenShot to find all external dependencies"""
import os
import re
import shutil
import subprocess
from subprocess import call
# Ignore non library/executable extensions
non_executables = [
".py",
".svg",
".png",
".blend",
".a",
".pak",
".qm",
".pyc",
".txt",
".jpg",
".zip",
".dat",
".conf",
".xml",
".h",
".ui",
".json",
".exe",
]
def fix_rpath(PATH):
"""FIX broken @rpath on Qt, PyQt, and /usr/local/ dependencies with no @rpath"""
# Cleanup duplicate folder and files (that cx_freeze creates)
duplicate_path = os.path.join(PATH, "lib", "openshot_qt")
if os.path.exists(duplicate_path):
shutil.rmtree(duplicate_path)
# Find files matching patterns
for root, dirs, files in os.walk(PATH):
for basename in files:
file_path = os.path.join(root, basename)
relative_path = os.path.relpath(root, PATH)
# Skip common file extensions (speed things up)
if (
os.path.splitext(file_path)[-1] in non_executables
or basename.startswith(".")
or "profiles" in file_path
):
continue
# Build exe path (relative from the app dir)
executable_path = os.path.join("@executable_path", relative_path, basename)
if relative_path == ".":
executable_path = os.path.join("@executable_path", basename)
# Change ID path of library files
# Sometimes, the ID has an absolute path or invalid @rpath embedded in it, which breaks our frozen exe
call(["install_name_tool", file_path, "-id", executable_path])
# Loop through all dependencies of each library/executable
raw_output = (
subprocess.Popen(["oTool", "-L", file_path], stdout=subprocess.PIPE)
.communicate()[0]
.decode("utf-8")
)
for output in raw_output.split("\n")[1:-1]:
if (
output
and "is not an object file" not in output
and ".o):" not in output
):
dependency_path = output.split("\t")[1].split(" ")[0]
dependency_base_path, dependency_name = os.path.split(
dependency_path
)
# If @rpath or /usr/local found in dependency path, update with @executable_path instead
if "/usr/local" in dependency_path or "@rpath" in dependency_path:
dependency_exe_path = os.path.join(
"@executable_path", dependency_name
)
if not os.path.exists(os.path.join(PATH, dependency_name)):
print(
"ERROR: /usr/local PATH not found in EXE folder: %s"
% dependency_path
)
else:
call(
[
"install_name_tool",
file_path,
"-change",
dependency_path,
dependency_exe_path,
]
)
def print_min_versions(PATH):
"""Print ALL MINIMUM and SDK VERSIONS for files in OpenShot build folder.
This does not list all dependent libraries though, and sometimes one of those can cause issues.
"""
# Use 2 different matches, due to different output from different libraries (depending on compiler)
REGEX_SDK_MATCH = re.compile(
r".*(LC_VERSION_MIN_MACOSX).*version (\d+\.\d+).*sdk (\d+\.\d+).*(cmd)",
re.DOTALL,
)
REGEX_SDK_MATCH2 = re.compile(r".*sdk\s(.*)\s*minos\s(.*)")
VERSIONS = {}
# Find files matching patterns
for root, dirs, files in os.walk(PATH):
for basename in files:
file_path = os.path.join(root, basename)
file_parts = file_path.split("/")
# Skip common file extensions (speed things up)
if os.path.splitext(file_path)[
-1
] in non_executables or basename.startswith("."):
continue
raw_output = (
subprocess.Popen(["oTool", "-l", file_path], stdout=subprocess.PIPE)
.communicate()[0]
.decode("utf-8")
)
matches = REGEX_SDK_MATCH.findall(raw_output)
matches2 = REGEX_SDK_MATCH2.findall(raw_output)
min_version = None
sdk_version = None
if matches and len(matches[0]) == 4:
min_version = matches[0][1]
sdk_version = matches[0][2]
elif matches2 and len(matches2[0]) == 2:
sdk_version = matches2[0][0]
min_version = matches2[0][1]
if min_version and sdk_version:
print(
"... scanning %s for min version (min: %s, sdk: %s)"
% (file_path.replace(PATH, ""), min_version, sdk_version)
)
# Organize by MIN version
if min_version in VERSIONS:
if file_path not in VERSIONS[min_version]:
VERSIONS[min_version].append(file_path)
else:
VERSIONS[min_version] = [file_path]
if min_version in ["11.0"]:
print("ERROR!!!! Minimum OS X version not met for %s" % file_path)
print("\nSummary of Minimum Mac SDKs for Dependencies:")
for key in sorted(VERSIONS.keys()):
print("\n%s" % key)
for file_path in VERSIONS[key]:
print(" %s" % file_path)
print("\nCount of Minimum Mac SDKs for Dependencies:")
for key in sorted(VERSIONS.keys()):
print("%s (%d)" % (key, len(VERSIONS[key])))
if __name__ == "__main__":
# Run these methods manually for testing
# XXX: This path should be set programmatically, somehow
PATH = "/Users/jonathanthomas/apps/openshot-qt/build/exe.macosx-10.15-x86_64-3.7"
fix_rpath(PATH)
print_min_versions(PATH)
|
gui | optionspanel | # This file is part of MyPaint.
# Copyright (C) 2013-2018 by the MyPaint Development Team.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
"""Dockable panel showing options for the current mode"""
## Imports
from __future__ import division, print_function
import logging
import lib.xml
from lib.gettext import C_
from lib.gibindings import Gtk
from .toolstack import TOOL_WIDGET_NATURAL_HEIGHT_SHORT, SizedVBoxToolWidget
logger = logging.getLogger(__name__)
## Class defs
class ModeOptionsTool(SizedVBoxToolWidget):
"""Dockable panel showing options for the current mode
This panel has a title and an icon reflecting the current mode, and
displays its options widget if it has one: define an object method named
``get_options_widget()`` returning an arbitrary GTK widget. Singletons work
well here, and are encouraged. ``get_options_widget()`` can also return
`None` if the mode is a temporary mode which has no sensible options. In
this case, any widget already displayed will not be replaced, which is
particularly appropriate for modes which only persist for the length of
time the mouse button is held, and stack on top of other modes.
"""
## Class constants
SIZED_VBOX_NATURAL_HEIGHT = TOOL_WIDGET_NATURAL_HEIGHT_SHORT
tool_widget_icon_name = "mypaint-options-symbolic"
tool_widget_title = C_(
"options panel: tab tooltip: title",
"Tool Options",
)
tool_widget_description = C_(
"options panel: tab tooltip: description",
"Specialized settings for the current editing tool",
)
__gtype_name__ = "MyPaintModeOptionsTool"
OPTIONS_MARKUP = C_(
"options panel: header",
"<b>{mode_name}</b>",
)
NO_OPTIONS_MARKUP = C_(
"options panel: body",
"<i>No options available</i>",
)
## Method defs
def __init__(self):
"""Construct, and connect internal signals & callbacks"""
SizedVBoxToolWidget.__init__(self)
from gui.application import get_app
self._app = get_app()
self._app.doc.modes.changed += self._modestack_changed_cb
self.set_border_width(3)
self.set_spacing(6)
# Placeholder in case a mode has no options
label = Gtk.Label()
label.set_markup(self.NO_OPTIONS_MARKUP)
self._no_options_label = label
# Container for an options widget exposed by the current mode
self._mode_icon = Gtk.Image()
label = Gtk.Label()
label.set_text("<options-label>")
self._options_label = label
label.set_alignment(0.0, 0.5)
label_hbox = Gtk.HBox()
label_hbox.set_spacing(3)
label_hbox.set_border_width(3)
label_hbox.pack_start(self._mode_icon, False, False, 0)
label_hbox.pack_start(self._options_label, True, True, 0)
align = Gtk.Alignment.new(0.5, 0.5, 1.0, 1.0)
align.set_padding(0, 0, 0, 0)
align.set_border_width(3)
self._options_bin = align
self.pack_start(label_hbox, False, False, 0)
self.pack_start(align, True, True, 0)
self.connect("show", lambda *a: self._update_ui())
# Fallback
self._update_ui_with_options_widget(
self._no_options_label,
self.tool_widget_title,
self.tool_widget_icon_name,
)
def _modestack_changed_cb(self, modestack, old, new):
"""Update the UI when the mode changes"""
self._update_ui()
def _update_ui(self):
"""Update the UI to show the options widget of the current mode"""
mode = self._app.doc.modes.top
self._update_ui_for_mode(mode)
def _update_ui_for_mode(self, mode):
# Get the new options widget
try:
get_options_widget = mode.get_options_widget
except AttributeError:
get_options_widget = None
if get_options_widget:
new_options = get_options_widget()
else:
new_options = self._no_options_label
if not new_options:
# Leave existing widget as-is, even if it's the default.
# XXX maybe we should be doing something stack-based here?
return
icon_name = mode.get_icon_name()
name = mode.get_name()
self._update_ui_with_options_widget(new_options, name, icon_name)
def _update_ui_with_options_widget(self, new_options, name, icon_name):
old_options = self._options_bin.get_child()
logger.debug("name: %r, icon name: %r", name, icon_name)
if name:
markup = self.OPTIONS_MARKUP.format(
mode_name=lib.xml.escape(name),
)
self._options_label.set_markup(markup)
if icon_name:
self._mode_icon.set_from_icon_name(
icon_name,
Gtk.IconSize.SMALL_TOOLBAR,
)
# Options widget: only update if there's a change
if new_options is not old_options:
if old_options:
old_options.hide()
self._options_bin.remove(old_options)
self._options_bin.add(new_options)
new_options.show()
self._options_bin.show_all()
|
v1 | notifications | from typing import List
from CTFd.api.v1.helpers.request import validate_args
from CTFd.api.v1.helpers.schemas import sqlalchemy_to_pydantic
from CTFd.api.v1.schemas import APIDetailedSuccessResponse, APIListSuccessResponse
from CTFd.constants import RawEnum
from CTFd.models import Notifications, db
from CTFd.schemas.notifications import NotificationSchema
from CTFd.utils.decorators import admins_only
from CTFd.utils.helpers.models import build_model_filters
from flask import current_app, make_response, request
from flask_restx import Namespace, Resource
notifications_namespace = Namespace(
"notifications", description="Endpoint to retrieve Notifications"
)
NotificationModel = sqlalchemy_to_pydantic(Notifications)
TransientNotificationModel = sqlalchemy_to_pydantic(Notifications, exclude=["id"])
class NotificationDetailedSuccessResponse(APIDetailedSuccessResponse):
data: NotificationModel
class NotificationListSuccessResponse(APIListSuccessResponse):
data: List[NotificationModel]
notifications_namespace.schema_model(
"NotificationDetailedSuccessResponse", NotificationDetailedSuccessResponse.apidoc()
)
notifications_namespace.schema_model(
"NotificationListSuccessResponse", NotificationListSuccessResponse.apidoc()
)
@notifications_namespace.route("")
class NotificantionList(Resource):
@notifications_namespace.doc(
description="Endpoint to get notification objects in bulk",
responses={
200: ("Success", "NotificationListSuccessResponse"),
400: (
"An error occured processing the provided or stored data",
"APISimpleErrorResponse",
),
},
)
@validate_args(
{
"title": (str, None),
"content": (str, None),
"user_id": (int, None),
"team_id": (int, None),
"q": (str, None),
"field": (
RawEnum("NotificationFields", {"title": "title", "content": "content"}),
None,
),
"since_id": (int, None),
},
location="query",
)
def get(self, query_args):
q = query_args.pop("q", None)
field = str(query_args.pop("field", None))
filters = build_model_filters(model=Notifications, query=q, field=field)
since_id = query_args.pop("since_id", None)
if since_id:
filters.append((Notifications.id > since_id))
notifications = (
Notifications.query.filter_by(**query_args).filter(*filters).all()
)
schema = NotificationSchema(many=True)
result = schema.dump(notifications)
if result.errors:
return {"success": False, "errors": result.errors}, 400
return {"success": True, "data": result.data}
@notifications_namespace.doc(
description="Endpoint to get statistics for notification objects in bulk",
responses={200: ("Success", "APISimpleSuccessResponse")},
)
@validate_args(
{
"title": (str, None),
"content": (str, None),
"user_id": (int, None),
"team_id": (int, None),
"q": (str, None),
"field": (
RawEnum("NotificationFields", {"title": "title", "content": "content"}),
None,
),
"since_id": (int, None),
},
location="query",
)
def head(self, query_args):
q = query_args.pop("q", None)
field = str(query_args.pop("field", None))
filters = build_model_filters(model=Notifications, query=q, field=field)
since_id = query_args.pop("since_id", None)
if since_id:
filters.append((Notifications.id > since_id))
notification_count = (
Notifications.query.filter_by(**query_args).filter(*filters).count()
)
response = make_response()
response.headers["Result-Count"] = notification_count
return response
@admins_only
@notifications_namespace.doc(
description="Endpoint to create a notification object",
responses={
200: ("Success", "NotificationDetailedSuccessResponse"),
400: (
"An error occured processing the provided or stored data",
"APISimpleErrorResponse",
),
},
)
def post(self):
req = request.get_json()
schema = NotificationSchema()
result = schema.load(req)
if result.errors:
return {"success": False, "errors": result.errors}, 400
db.session.add(result.data)
db.session.commit()
response = schema.dump(result.data)
# Grab additional settings
notif_type = req.get("type", "alert")
notif_sound = req.get("sound", True)
response.data["type"] = notif_type
response.data["sound"] = notif_sound
current_app.events_manager.publish(data=response.data, type="notification")
return {"success": True, "data": response.data}
@notifications_namespace.route("/<notification_id>")
@notifications_namespace.param("notification_id", "A Notification ID")
class Notification(Resource):
@notifications_namespace.doc(
description="Endpoint to get a specific notification object",
responses={
200: ("Success", "NotificationDetailedSuccessResponse"),
400: (
"An error occured processing the provided or stored data",
"APISimpleErrorResponse",
),
},
)
def get(self, notification_id):
notif = Notifications.query.filter_by(id=notification_id).first_or_404()
schema = NotificationSchema()
response = schema.dump(notif)
if response.errors:
return {"success": False, "errors": response.errors}, 400
return {"success": True, "data": response.data}
@admins_only
@notifications_namespace.doc(
description="Endpoint to delete a notification object",
responses={200: ("Success", "APISimpleSuccessResponse")},
)
def delete(self, notification_id):
notif = Notifications.query.filter_by(id=notification_id).first_or_404()
db.session.delete(notif)
db.session.commit()
db.session.close()
return {"success": True}
|
network | vector_source | #!/usr/bin/env python
#
# Copyright 2006,2010,2013 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# SPDX-License-Identifier: GPL-3.0-or-later
#
#
from argparse import ArgumentParser
from gnuradio import blocks, gr
class vector_source(gr.top_block):
def __init__(self, host, port, pkt_size, eof):
gr.top_block.__init__(self, "vector_source")
data = [i * 0.01 for i in range(1000)]
vec = blocks.vector_source_f(data, True)
udp = blocks.udp_sink(gr.sizeof_float, host, port, pkt_size, eof=eof)
self.connect(vec, udp)
if __name__ == "__main__":
parser = ArgumentParser()
parser.add_argument(
"--host",
default="127.0.0.1",
help="Remote host name (domain name or IP address",
)
parser.add_argument(
"--port", type=int, default=65500, help="port number to connect to"
)
parser.add_argument("--packet-size", type=int, default=1471, help="packet size.")
parser.add_argument(
"--no-eof",
action="store_true",
default=False,
help="don't send EOF on disconnect",
)
args = parser.parse_args()
# Create an instance of a hierarchical block
top_block = vector_source(args.host, args.port, args.packet_size, not args.no_eof)
try:
# Run forever
top_block.run()
except KeyboardInterrupt:
# Ctrl-C exits
pass
|
dialogs | detectdialog | # Copyright (C) 2011 Chris Dekter
# Copyright (C) 2018 Thomas Hess <thomas.hess@udo.edu>
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from typing import Tuple
from autokey.qtui import common as ui_common
from PyQt5.QtWidgets import QWidget
logger = ui_common.logger.getChild("DetectDialog")
class DetectDialog(*ui_common.inherits_from_ui_file_with_name("detectdialog")):
"""
The DetectDialog lets the user select window properties of a chosen window.
The dialog shows the window title and window class of the chosen window
and lets the user select one of those two options.
"""
def __init__(self, parent: QWidget):
super(DetectDialog, self).__init__(parent)
self.setupUi(self)
self.window_title = ""
self.window_class = ""
def populate(self, window_info: Tuple[str, str]):
self.window_title, self.window_class = window_info
self.detected_title.setText(self.window_title)
self.detected_class.setText(self.window_class)
logger.info(
"Detected window with properties title: {}, window class: {}".format(
self.window_title, self.window_class
)
)
def get_choice(self) -> str:
# This relies on autoExclusive being set to true in the ui file.
if self.classButton.isChecked():
logger.debug(
"User has chosen the window class: {}".format(self.window_class)
)
return self.window_class
else:
logger.debug(
"User has chosen the window title: {}".format(self.window_title)
)
return self.window_title
|
extractor | parliamentliveuk | from __future__ import unicode_literals
from .common import InfoExtractor
class ParliamentLiveUKIE(InfoExtractor):
IE_NAME = "parliamentlive.tv"
IE_DESC = "UK parliament videos"
_VALID_URL = r"(?i)https?://(?:www\.)?parliamentlive\.tv/Event/Index/(?P<id>[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12})"
_TESTS = [
{
"url": "http://parliamentlive.tv/Event/Index/c1e9d44d-fd6c-4263-b50f-97ed26cc998b",
"info_dict": {
"id": "1_af9nv9ym",
"ext": "mp4",
"title": "Home Affairs Committee",
"uploader_id": "FFMPEG-01",
"timestamp": 1422696664,
"upload_date": "20150131",
},
},
{
"url": "http://parliamentlive.tv/event/index/3f24936f-130f-40bf-9a5d-b3d6479da6a4",
"only_matching": True,
},
]
def _real_extract(self, url):
video_id = self._match_id(url)
webpage = self._download_webpage(
"http://vodplayer.parliamentlive.tv/?mid=" + video_id, video_id
)
widget_config = self._parse_json(
self._search_regex(
r"(?s)kWidgetConfig\s*=\s*({.+});", webpage, "kaltura widget config"
),
video_id,
)
kaltura_url = "kaltura:%s:%s" % (
widget_config["wid"][1:],
widget_config["entry_id"],
)
event_title = self._download_json(
"http://parliamentlive.tv/Event/GetShareVideo/" + video_id, video_id
)["event"]["title"]
return {
"_type": "url_transparent",
"title": event_title,
"description": "",
"url": kaltura_url,
"ie_key": "Kaltura",
}
|
femexamples | constraint_centrif | # ***************************************************************************
# * Copyright (c) 2021 Bernd Hahnebach <bernd@bimstatik.org> *
# * *
# * This file is part of the FreeCAD CAx development system. *
# * *
# * This program is free software; you can redistribute it and/or modify *
# * it under the terms of the GNU Lesser General Public License (LGPL) *
# * as published by the Free Software Foundation; either version 2 of *
# * the License, or (at your option) any later version. *
# * for detail see the LICENCE text file. *
# * *
# * This program is distributed in the hope that it will be useful, *
# * but WITHOUT ANY WARRANTY; without even the implied warranty of *
# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
# * GNU Library General Public License for more details. *
# * *
# * You should have received a copy of the GNU Library General Public *
# * License along with this program; if not, write to the Free Software *
# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
# * USA *
# * *
# ***************************************************************************
import Fem
import FreeCAD
import ObjectsFem
from BasicShapes import Shapes
from Draft import clone
from FreeCAD import Vector as vec
from Part import makeLine
from . import manager
from .manager import get_meshname, init_doc
def get_information():
return {
"name": "Constraint Centrif",
"meshtype": "solid",
"meshelement": "Tet10",
"constraints": ["centrif", "fixed"],
"solvers": ["calculix", "ccxtools"],
"material": "multimaterial",
"equations": ["mechanical"],
}
def get_explanation(header=""):
return (
header
+ """
To run the example from Python console use:
from femexamples.constraint_centrif import setup
setup()
See forum topic post:
https://forum.freecad.org/viewtopic.php?f=18&t=57770
constraint centrif, concerning CENTRIF label from ccx's *DLOAD card
"""
)
def setup(doc=None, solvertype="ccxtools"):
# init FreeCAD document
if doc is None:
doc = init_doc()
# explanation object
# just keep the following line and change text string in get_explanation method
manager.add_explanation_obj(
doc, get_explanation(manager.get_header(get_information()))
)
# geometric objects
# ring
stiffener = doc.addObject("Part::Box", "Stiffener")
stiffener.Length = 10
stiffener.Width = 200
stiffener.Height = 10
stiffener.Placement.Base = (-5, -100, 0)
circumference = Shapes.addTube(doc, "Circumference")
circumference.Height = 10.0
circumference.InnerRadius = 97.5
circumference.OuterRadius = 102.5
doc.recompute()
fusion = doc.addObject("Part::MultiFuse", "Fusion")
fusion.Shapes = [stiffener, circumference]
doc.recompute()
centerhole = doc.addObject("Part::Cylinder", "CenterHole")
centerhole.Radius = 3
centerhole.Height = 20
doc.recompute()
ring_bottom = doc.addObject("Part::Cut", "RingBottom")
ring_bottom.Base = fusion
ring_bottom.Tool = centerhole
doc.recompute()
# standard ring
ring_top = clone(ring_bottom, delta=vec(0, 0, 20))
ring_top.Label = "RingTop"
# compound of both rings
geom_obj = doc.addObject("Part::Compound", "TheRingOfFire")
geom_obj.Links = [ring_bottom, ring_top]
doc.recompute()
if FreeCAD.GuiUp:
geom_obj.ViewObject.Document.activeView().viewAxonometric()
geom_obj.ViewObject.Document.activeView().fitAll()
# line for centrif axis
sh_axis_line = makeLine(vec(0, 0, 0), vec(0, 0, 31))
axis_line = doc.addObject("Part::Feature", "CentrifAxis")
axis_line.Shape = sh_axis_line
doc.recompute()
if FreeCAD.GuiUp:
axis_line.ViewObject.LineWidth = 5.0
axis_line.ViewObject.LineColor = (1.0, 0.0, 0.0)
# analysis
analysis = ObjectsFem.makeAnalysis(doc, "Analysis")
# solver
if solvertype == "calculix":
solver_obj = ObjectsFem.makeSolverCalculix(doc, "SolverCalculiX")
elif solvertype == "ccxtools":
solver_obj = ObjectsFem.makeSolverCalculixCcxTools(doc, "CalculiXccxTools")
solver_obj.WorkingDir = ""
else:
FreeCAD.Console.PrintWarning(
"Unknown or unsupported solver type: {}. "
"No solver object was created.\n".format(solvertype)
)
if solvertype == "calculix" or solvertype == "ccxtools":
solver_obj.AnalysisType = "static"
solver_obj.GeometricalNonlinearity = "linear"
solver_obj.ThermoMechSteadyState = False
solver_obj.MatrixSolverType = "default"
solver_obj.IterationsControlParameterTimeUse = False
solver_obj.SplitInputWriter = False
analysis.addObject(solver_obj)
# materials
material_obj_scotty = ObjectsFem.makeMaterialSolid(doc, "Steel_Scotty")
mat = material_obj_scotty.Material
mat["Name"] = "Steel_Scotty"
mat["YoungsModulus"] = "210000 MPa"
mat["PoissonRatio"] = "0.30"
mat["Density"] = "4000 kg/m^3"
material_obj_scotty.Material = mat
material_obj_scotty.References = [(ring_bottom, "Solid1")]
analysis.addObject(material_obj_scotty)
material_obj_std = ObjectsFem.makeMaterialSolid(doc, "Steel_Std")
mat = material_obj_std.Material
mat["Name"] = "Steel_Std"
mat["YoungsModulus"] = "210000 MPa"
mat["PoissonRatio"] = "0.30"
mat["Density"] = "8000 kg/m^3"
material_obj_std.Material = mat
material_obj_std.References = [(ring_top, "Solid1")]
analysis.addObject(material_obj_std)
# constraint fixed
con_fixed = ObjectsFem.makeConstraintFixed(doc, "ConstraintFixed")
con_fixed.References = [(geom_obj, ("Face4", "Face12"))]
analysis.addObject(con_fixed)
# constraint centrif
con_centrif = ObjectsFem.makeConstraintCentrif(doc, "ConstraintCentrif")
con_centrif.RotationFrequency = "100 Hz"
con_centrif.RotationAxis = [(axis_line, "Edge1")]
analysis.addObject(con_centrif)
# mesh
from .meshes.mesh_constraint_centrif_tetra10 import create_elements, create_nodes
fem_mesh = Fem.FemMesh()
control = create_nodes(fem_mesh)
if not control:
FreeCAD.Console.PrintError("Error on creating nodes.\n")
control = create_elements(fem_mesh)
if not control:
FreeCAD.Console.PrintError("Error on creating elements.\n")
femmesh_obj = analysis.addObject(ObjectsFem.makeMeshGmsh(doc, get_meshname()))[0]
femmesh_obj.FemMesh = fem_mesh
femmesh_obj.Part = geom_obj
femmesh_obj.SecondOrderLinear = False
femmesh_obj.CharacteristicLengthMax = "5.0 mm"
doc.recompute()
return doc
|
components | filepath | #!/usr/bin/env python
# coding:utf-8
import os
from PySide2.QtCore import QFileInfo, QObject, QUrl, Slot
class FilepathHelper(QObject):
"""
FilepathHelper gives access to file path methods not available from JS.
It should be non-instantiable and expose only static methods, but this is not yet
possible in PySide.
"""
@staticmethod
def asStr(path):
"""
Accepts strings and QUrls and always returns 'path' as a string.
Args:
path (str or QUrl): the filepath to consider
Returns:
str: String representation of 'path'
"""
if not isinstance(path, (QUrl, str)):
raise TypeError("Unexpected data type: {}".format(path.__class__))
if isinstance(path, QUrl):
path = path.toLocalFile()
return path
@Slot(str, result=str)
@Slot(QUrl, result=str)
def basename(self, path):
"""Returns the final component of a pathname"""
return os.path.basename(self.asStr(path))
@Slot(str, result=str)
@Slot(QUrl, result=str)
def dirname(self, path):
"""Returns the directory component of a pathname"""
return os.path.dirname(self.asStr(path))
@Slot(str, result=str)
@Slot(QUrl, result=str)
def extension(self, path):
"""Returns the extension (.ext) of a pathname"""
return os.path.splitext(self.asStr(path))[-1]
@Slot(str, result=str)
@Slot(QUrl, result=str)
def removeExtension(self, path):
"""Returns the pathname without its extension (.ext)"""
return os.path.splitext(self.asStr(path))[0]
@Slot(str, result=bool)
@Slot(QUrl, result=bool)
def isFile(self, path):
"""Test whether a path is a regular file"""
return os.path.isfile(self.asStr(path))
@Slot(str, result=bool)
@Slot(QUrl, result=bool)
def exists(self, path):
"""Test whether a path exists"""
return os.path.exists(self.asStr(path))
@Slot(QUrl, result=str)
def urlToString(self, url):
"""Convert QUrl to a string using 'QUrl.toLocalFile' method"""
return self.asStr(url)
@Slot(str, result=QUrl)
def stringToUrl(self, path):
"""Convert a path (string) to a QUrl using 'QUrl.fromLocalFile' method"""
return QUrl.fromLocalFile(path)
@Slot(str, result=str)
@Slot(QUrl, result=str)
def normpath(self, path):
"""Returns native normalized path"""
return os.path.normpath(self.asStr(path))
@Slot(str, result=str)
@Slot(QUrl, result=str)
def globFirst(self, path):
"""Returns the first from a list of paths matching a pathname pattern."""
import glob
fileList = glob.glob(self.asStr(path))
fileList.sort()
if fileList:
return fileList[0]
return ""
@Slot(QUrl, result=int)
def fileSizeMB(self, path):
"""Returns the file size in MB."""
return QFileInfo(self.asStr(path)).size() / (1024 * 1024)
|
lib | portable | """
Library functions related to special features of the Windows portable
flash drive install.
"""
import os
import pathlib
from sglib.constants import IS_MACOS, IS_WINDOWS, USER_HOME
from sglib.log import LOG
def escape_path(path):
if IS_WINDOWS:
folder_drive = pathlib.Path(path).drive.upper()
user_drive = pathlib.Path(USER_HOME).drive.upper()
assert folder_drive and user_drive, (path, USER_HOME)
if user_drive == folder_drive:
relpath = os.path.relpath(path, USER_HOME)
path = os.path.join("{{ USER_HOME }}", relpath)
else:
LOG.warning(
"Path set to a different drive than portable install at "
f'"{USER_HOME}". "{path}" will not be accessible on '
"another computer"
)
if IS_MACOS:
path_split = os.path.split(path)
home_split = os.path.split(USER_HOME)
if path_split[0] == "Volumes" and path_split[1] == home_split[1]:
relpath = os.path.relpath(path, USER_HOME)
path = os.path.join("{{ USER_HOME }}", relpath)
else:
LOG.warning(
"Path set to a different storage device than portable "
f'install at "{USER_HOME}". "{path}" will not be '
"accessible on another computer"
)
return path
def unescape_path(path):
path = path.replace("{{ USER_HOME }}", USER_HOME)
path = os.path.abspath(path)
return path
|
backend | utils | # -*- encoding: utf-8 -*-
# Dissemin: open access policy enforcement tool
# Copyright (C) 2014 Antonin Delpeuch
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
import logging
from datetime import datetime, timedelta
from time import sleep
import requests
import requests.exceptions
from dissemin.settings import redis_client
from memoize import memoize
logger = logging.getLogger("dissemin." + __name__)
# Run a task at most one at a time
class run_only_once(object):
def __init__(self, base_id, **kwargs):
self.base_id = base_id
self.keys = kwargs.get("keys", [])
self.timeout = int(kwargs.get("timeout", 60 * 10))
def __call__(self, f):
def inner(*args, **kwargs):
lock_id = (
self.base_id
+ "-"
+ ("-".join([str(kwargs.get(key, "none")) for key in self.keys]))
)
lock = redis_client.lock(lock_id, timeout=self.timeout)
have_lock = False
result = None
try:
have_lock = lock.acquire(blocking=False)
if have_lock:
result = f(*args, **kwargs)
finally:
if have_lock:
lock.release()
return result
return inner
# Open an URL with retries
def request_retry(url, **kwargs):
"""
Retries a request, with throttling and exponential back-off.
:param url: the URL to fetch
:param data: the GET parameters
:param headers: the HTTP headers
:param timeout: the number of seconds to wait before declaring that an individual request timed out (default 10)
:param retries: the number of times to retry a query (default 3)
:param delay: the minimum delay between requests (default 5)
:param backoff: the multiple used when raising the delay after an unsuccessful query (default 2)
:param session: A session to use
"""
params = kwargs.get("params", None)
timeout = kwargs.get("timeout", 10)
retries = kwargs.get("retries", 5)
delay = kwargs.get("delay", 5)
backoff = kwargs.get("backoff", 2)
headers = kwargs.get("headers", {})
session = kwargs.get("session", requests.Session())
try:
r = session.get(
url, params=params, timeout=timeout, headers=headers, allow_redirects=True
)
r.raise_for_status()
return r
except requests.exceptions.RequestException:
if retries <= 0:
raise
logger.info("Retrying in " + str(delay) + " seconds with url " + url)
sleep(delay)
return request_retry(
url,
params=params,
timeout=timeout,
retries=retries - 1,
delay=delay * backoff,
backoff=backoff,
session=session,
)
def urlopen_retry(url, **kwargs):
return request_retry(url, **kwargs).text
@memoize(timeout=86400) # 1 day
def cached_urlopen_retry(*args, **kwargs):
return urlopen_retry(*args, **kwargs)
def utf8_truncate(s, length=1024):
"""
Truncates a string to given length when converted to utf8.
:param s: string to truncate
:param length: Desired length, default 1024
:returns: String of utf8-length with at most 1024
We cannot convert to utf8 and slice, since this might yield incomplete characters when decoding back.
"""
s = s[:1024]
while len(s.encode("utf-8")) > length:
s = s[:-1]
return s
def with_speed_report(generator, name=None, report_delay=timedelta(seconds=10)):
"""
Periodically reports the speed at which we are enumerating the items
of a generator.
:param name: a name to use in the reports (eg "papers from Crossref API")
:param report_delay: print a report every so often
"""
if name is None:
name = getattr(generator, "__name__", "")
last_report = datetime.now()
nb_records_since_last_report = 0
for idx, record in enumerate(generator):
yield record
nb_records_since_last_report += 1
now = datetime.now()
if last_report + report_delay < now:
rate = nb_records_since_last_report / float(
(now - last_report).total_seconds()
)
logger.info("{}: {}, {} records/sec".format(name, idx, rate))
last_report = now
nb_records_since_last_report = 0
def report_speed(name=None, report_delay=timedelta(seconds=10)):
"""
Decorator for a function that returns a generator, see with_speed_report
"""
def decorator(func):
logging_name = name
if logging_name is None:
logging_name = getattr(func, "__name__", "")
def wrapped_generator(*args, **kwargs):
return with_speed_report(
func(*args, **kwargs), name=logging_name, report_delay=report_delay
)
return wrapped_generator
return decorator
|
gui-qt | dictionary_editor | from collections import namedtuple
from itertools import chain
from operator import attrgetter, itemgetter
from plover import _
from plover.gui_qt.dictionary_editor_ui import Ui_DictionaryEditor
from plover.gui_qt.steno_validator import StenoValidator
from plover.gui_qt.utils import ToolBar, WindowState
from plover.misc import expand_path, shorten_path
from plover.steno import normalize_steno, steno_to_sort_key
from plover.translation import escape_translation, unescape_translation
from PyQt5.QtCore import QAbstractTableModel, QModelIndex, Qt
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QComboBox, QDialog, QStyledItemDelegate
_COL_STENO, _COL_TRANS, _COL_DICT, _COL_COUNT = range(3 + 1)
class DictionaryItem(namedtuple("DictionaryItem", "steno translation dictionary")):
@property
def strokes(self):
return normalize_steno(self.steno, strict=False)
@property
def dictionary_path(self):
return self.dictionary.path
class DictionaryItemDelegate(QStyledItemDelegate):
def __init__(self, dictionary_list):
super().__init__()
self._dictionary_list = dictionary_list
def createEditor(self, parent, option, index):
if index.column() == _COL_DICT:
dictionary_paths = [
shorten_path(dictionary.path)
for dictionary in self._dictionary_list
if not dictionary.readonly
]
combo = QComboBox(parent)
combo.addItems(dictionary_paths)
return combo
widget = super().createEditor(parent, option, index)
if index.column() == _COL_STENO:
widget.setValidator(StenoValidator())
return widget
class DictionaryItemModel(QAbstractTableModel):
def __init__(self, dictionary_list, sort_column, sort_order):
super().__init__()
self._error_icon = QIcon(":/dictionary_error.svg")
self._dictionary_list = dictionary_list
self._operations = []
self._entries = []
self._sort_column = sort_column
self._sort_order = sort_order
self._update_entries()
def _update_entries(self, strokes_filter=None, translation_filter=None):
self._entries = []
for dictionary in self._dictionary_list:
for strokes, translation in dictionary.items():
steno = "/".join(strokes)
if strokes_filter is not None and not steno.startswith(strokes_filter):
continue
if translation_filter is not None and not translation.startswith(
translation_filter
):
continue
item = DictionaryItem(steno, translation, dictionary)
self._entries.append(item)
self.sort(self._sort_column, self._sort_order)
@property
def has_undo(self):
return bool(self._operations)
@property
def modified(self):
paths = set()
dictionary_list = []
for op_list in self._operations:
if not isinstance(op_list, list):
op_list = (op_list,)
for item in chain(*op_list):
if item is None:
continue
dictionary = item.dictionary
if dictionary.path in paths:
continue
paths.add(dictionary.path)
dictionary_list.append(dictionary)
return dictionary_list
# Note:
# - since switching from a dictionary to a table does not enforce the
# unicity of keys, a deletion can fail when one of the duplicate has
# already been deleted.
# - when undoing an operation at the table level, the item may have
# been filtered-out and not present
def _undo(self, old_item, new_item):
if old_item is None:
# Undo addition.
try:
del new_item.dictionary[new_item.strokes]
except KeyError:
pass
try:
row = self._entries.index(new_item)
except ValueError:
# Happen if the item is filtered-out.
pass
else:
self.remove_rows([row], record=False)
return
if new_item is None:
# Undo deletion.
self.new_row(0, item=old_item, record=False)
return
# Undo update.
try:
del new_item.dictionary[new_item.strokes]
except KeyError:
pass
try:
row = self._entries.index(new_item)
except ValueError:
# Happen if the item is filtered-out,
# "create" a new row so the user see
# the result of the undo.
self.new_row(0, item=old_item, record=False)
else:
old_item.dictionary[old_item.strokes] = old_item.translation
self._entries[row] = old_item
self.dataChanged.emit(
self.index(row, _COL_STENO), self.index(row, _COL_TRANS)
)
def undo(self, op=None):
op = self._operations.pop()
if isinstance(op, list):
for old_item, new_item in op:
self._undo(old_item, new_item)
else:
self._undo(*op)
def rowCount(self, parent):
return 0 if parent.isValid() else len(self._entries)
def columnCount(self, parent):
return _COL_COUNT
def headerData(self, section, orientation, role):
if orientation != Qt.Horizontal or role != Qt.DisplayRole:
return None
if section == _COL_STENO:
# i18n: Widget: “DictionaryEditor”.
return _("Strokes")
if section == _COL_TRANS:
# i18n: Widget: “DictionaryEditor”.
return _("Translation")
if section == _COL_DICT:
# i18n: Widget: “DictionaryEditor”.
return _("Dictionary")
def data(self, index, role):
if not index.isValid() or role not in (
Qt.EditRole,
Qt.DisplayRole,
Qt.DecorationRole,
):
return None
item = self._entries[index.row()]
column = index.column()
if role == Qt.DecorationRole:
if column == _COL_STENO:
try:
normalize_steno(item.steno)
except ValueError:
return self._error_icon
return None
if column == _COL_STENO:
return item.steno
if column == _COL_TRANS:
return escape_translation(item.translation)
if column == _COL_DICT:
return shorten_path(item.dictionary.path)
def flags(self, index):
if not index.isValid():
return Qt.NoItemFlags
f = Qt.ItemIsEnabled | Qt.ItemIsSelectable
item = self._entries[index.row()]
if not item.dictionary.readonly:
f |= Qt.ItemIsEditable
return f
def filter(self, strokes_filter=None, translation_filter=None):
self.modelAboutToBeReset.emit()
self._update_entries(strokes_filter, translation_filter)
self.modelReset.emit()
@staticmethod
def _item_steno_sort_key(item):
return steno_to_sort_key(item[_COL_STENO], strict=False)
def sort(self, column, order):
self.layoutAboutToBeChanged.emit()
if column == _COL_DICT:
key = attrgetter("dictionary_path")
elif column == _COL_STENO:
key = self._item_steno_sort_key
else:
key = itemgetter(column)
self._entries.sort(key=key, reverse=(order == Qt.DescendingOrder))
self._sort_column = column
self._sort_order = order
self.layoutChanged.emit()
def setData(self, index, value, role=Qt.EditRole, record=True):
assert role == Qt.EditRole
row = index.row()
column = index.column()
old_item = self._entries[row]
strokes = old_item.strokes
steno, translation, dictionary = old_item
if column == _COL_STENO:
strokes = normalize_steno(value.strip(), strict=False)
steno = "/".join(strokes)
if not steno or steno == old_item.steno:
return False
elif column == _COL_TRANS:
translation = unescape_translation(value.strip())
if translation == old_item.translation:
return False
elif column == _COL_DICT:
path = expand_path(value)
for dictionary in self._dictionary_list:
if dictionary.path == path:
break
if dictionary == old_item.dictionary:
return False
try:
del old_item.dictionary[old_item.strokes]
except KeyError:
pass
if not old_item.strokes and not old_item.translation:
# Merge operations when editing a newly added row.
if self._operations and self._operations[-1] == [(None, old_item)]:
self._operations.pop()
old_item = None
new_item = DictionaryItem(steno, translation, dictionary)
self._entries[row] = new_item
dictionary[strokes] = translation
if record:
self._operations.append((old_item, new_item))
self.dataChanged.emit(index, index)
return True
def new_row(self, row, item=None, record=True):
if item is None:
if row == 0 and not self._entries:
dictionary = self._dictionary_list[0]
else:
dictionary = self._entries[row].dictionary
item = DictionaryItem("", "", dictionary)
self.beginInsertRows(QModelIndex(), row, row)
self._entries.insert(row, item)
if record:
self._operations.append((None, item))
self.endInsertRows()
def remove_rows(self, row_list, record=True):
assert row_list
operations = []
for row in sorted(row_list, reverse=True):
self.beginRemoveRows(QModelIndex(), row, row)
item = self._entries.pop(row)
self.endRemoveRows()
try:
del item.dictionary[item.strokes]
except KeyError:
pass
else:
operations.append((item, None))
if record:
self._operations.append(operations)
class DictionaryEditor(QDialog, Ui_DictionaryEditor, WindowState):
ROLE = "dictionary_editor"
def __init__(self, engine, dictionary_paths):
super().__init__()
self.setupUi(self)
self._engine = engine
with engine:
dictionary_list = [
dictionary
for dictionary in engine.dictionaries.dicts
if dictionary.path in dictionary_paths
]
sort_column, sort_order = _COL_STENO, Qt.AscendingOrder
self._model = DictionaryItemModel(dictionary_list, sort_column, sort_order)
self._model.dataChanged.connect(self.on_data_changed)
self.table.sortByColumn(sort_column, sort_order)
self.table.setSortingEnabled(True)
self.table.setModel(self._model)
self.table.resizeColumnsToContents()
self.table.setItemDelegate(DictionaryItemDelegate(dictionary_list))
self.table.selectionModel().selectionChanged.connect(self.on_selection_changed)
background = self.table.palette().highlightedText().color().name()
text_color = self.table.palette().highlight().color().name()
self.table.setStyleSheet(
"""
QTableView::item:focus {
background-color: %s;
color: %s;
}"""
% (background, text_color)
)
self.table.setFocus()
for action in (
self.action_Undo,
self.action_Delete,
):
action.setEnabled(False)
# Toolbar.
self.layout().addWidget(
ToolBar(
self.action_Undo,
self.action_Delete,
self.action_New,
)
)
self.strokes_filter.setValidator(StenoValidator())
self.restore_state()
self.finished.connect(self.save_state)
@property
def _selection(self):
return list(
sorted(index.row() for index in self.table.selectionModel().selectedRows(0))
)
def _select(self, row, edit=False):
row = min(row, self._model.rowCount(QModelIndex()) - 1)
index = self._model.index(row, 0)
self.table.setCurrentIndex(index)
if edit:
self.table.edit(index)
def on_data_changed(self, top_left, bottom_right):
self.table.setCurrentIndex(top_left)
self.action_Undo.setEnabled(self._model.has_undo)
def on_selection_changed(self):
enabled = bool(self._selection)
for action in (self.action_Delete,):
action.setEnabled(enabled)
def on_undo(self):
assert self._model.has_undo
self._model.undo()
self.action_Undo.setEnabled(self._model.has_undo)
def on_delete(self):
selection = self._selection
assert selection
self._model.remove_rows(selection)
self._select(selection[0])
self.action_Undo.setEnabled(self._model.has_undo)
def on_new(self):
selection = self._selection
if selection:
row = self._selection[0]
else:
row = 0
self.table.reset()
self._model.new_row(row)
self._select(row, edit=True)
self.action_Undo.setEnabled(self._model.has_undo)
def on_apply_filter(self):
self.table.selectionModel().clear()
strokes_filter = "/".join(normalize_steno(self.strokes_filter.text().strip()))
translation_filter = unescape_translation(
self.translation_filter.text().strip()
)
self._model.filter(
strokes_filter=strokes_filter, translation_filter=translation_filter
)
def on_clear_filter(self):
self.strokes_filter.setText("")
self.translation_filter.setText("")
self._model.filter(strokes_filter=None, translation_filter=None)
def on_finished(self, result):
with self._engine:
self._engine.dictionaries.save(
dictionary.path for dictionary in self._model.modified
)
|
downloaders | FilefoxCc | # -*- coding: utf-8 -*-
import re
import urllib.parse
import pycurl
from ..anticaptchas.HCaptcha import HCaptcha
from ..anticaptchas.ReCaptcha import ReCaptcha
from ..base.xfs_downloader import XFSDownloader
from ..helpers import parse_html_tag_attr_value
class FilefoxCc(XFSDownloader):
__name__ = "FilefoxCc"
__type__ = "downloader"
__version__ = "0.02"
__status__ = "testing"
__pattern__ = r"https?://(?:www\.)?filefox\.cc/(?P<ID>\w{12})"
__config__ = [
("enabled", "bool", "Activated", True),
("use_premium", "bool", "Use premium account if available", True),
("fallback", "bool", "Fallback to free download if premium fails", True),
("chk_filesize", "bool", "Check file size", True),
("max_wait", "int", "Reconnect if waiting time is greater than minutes", 10),
]
__description__ = """Filefox.cc downloader plugin"""
__license__ = "GPLv3"
__authors__ = [("GammaC0de", "nitzo2001[AT]yahoo[DOT]com")]
PLUGIN_DOMAIN = "filefox.cc"
DL_LIMIT_PATTERN = r"Wait [\w ]+? or <a href='//filefox.cc/premium'"
WAIT_PATTERN = r'<span class="time-remain">(\d+)<'
INFO_PATTERN = (
r'<p>(?P<N>.+?)</p>\s*<p class="file-size">(?P<S>[\d.,]+) (?P<U>[\w^_]+)</p>'
)
NAME_PATTERN = r"^unmatchable$"
SIZE_REPLACEMENTS = [("Kb", "KB"), ("Mb", "MB"), ("Gb", "GB")]
LINK_PATTERN = r'<a class="btn btn-default" href="(https://s\d+.filefox.cc/.+?)"'
@staticmethod
def filter_form(tag):
action = parse_html_tag_attr_value("action", tag)
return ".js" not in action if action else False
FORM_PATTERN = filter_form
FORM_INPUTS_MAP = {"op": re.compile(r"^download")}
def handle_captcha(self, inputs):
m = re.search(r'\$\.post\( "/ddl",\s*\{(.+?) \} \);', self.data, re.S)
if m is not None:
recaptcha = ReCaptcha(self.pyfile)
captcha_key = recaptcha.detect_key()
if captcha_key:
self.captcha = recaptcha
response = recaptcha.challenge(captcha_key)
else:
hcaptcha = HCaptcha(self.pyfile)
captcha_key = hcaptcha.detect_key()
if captcha_key:
self.captcha = hcaptcha
response = hcaptcha.challenge(captcha_key)
if captcha_key:
captcha_inputs = {}
for _i in m.group(1).split(","):
_k, _v = _i.split(":", 1)
_k = _k.strip('\n" ')
if _k == "g-recaptcha-response":
_v = response
captcha_inputs[_k] = _v.strip('" ')
self.req.http.c.setopt(
pycurl.HTTPHEADER, ["X-Requested-With: XMLHttpRequest"]
)
html = self.load(
urllib.parse.urljoin(self.pyfile.url, "/ddl"), post=captcha_inputs
)
self.req.http.c.setopt(pycurl.HTTPHEADER, ["X-Requested-With:"])
if html == "OK":
self.captcha.correct()
else:
self.retry_captcha()
|
PyObjCTest | test_specialtypecodes_charint | """
Test handling of the private typecodes: _C_CHAR_AS_INT
This typecode doesn't actually exists in the ObjC runtime but
are private to PyObjC. We use these to simplify the bridge code
while at the same time getting a higher fidelity bridge.
- Add tests for calling methods from ObjC
"""
import array
import weakref
from PyObjCTest.fnd import NSObject
from PyObjCTest.specialtypecodes import *
from PyObjCTools.TestSupport import *
def setupMetaData():
objc.registerMetaDataForSelector(
b"OC_TestSpecialTypeCode",
b"int8Value",
dict(
retval=dict(type=objc._C_CHAR_AS_INT),
),
)
objc.registerMetaDataForSelector(
b"OC_TestSpecialTypeCode",
b"int8Array",
dict(
retval=dict(
type=objc._C_PTR + objc._C_CHAR_AS_INT, c_array_of_fixed_length=4
),
),
)
objc.registerMetaDataForSelector(
b"OC_TestSpecialTypeCode",
b"int8String",
dict(
retval=dict(
type=objc._C_PTR + objc._C_CHAR_AS_INT, c_array_delimited_by_null=True
),
),
)
objc.registerMetaDataForSelector(
b"OC_TestSpecialTypeCode",
b"int8StringArg:",
dict(
arguments={
2: dict(
type=objc._C_PTR + objc._C_CHAR_AS_INT,
c_array_delimited_by_null=True,
type_modifier=objc._C_IN,
),
}
),
)
objc.registerMetaDataForSelector(
b"OC_TestSpecialTypeCode",
b"int8Arg:andint8Arg:",
dict(
arguments={
2: dict(type=objc._C_CHAR_AS_INT),
3: dict(type=objc._C_CHAR_AS_INT),
}
),
)
objc.registerMetaDataForSelector(
b"OC_TestSpecialTypeCode",
b"int8ArrayOf4In:",
dict(
arguments={
2: dict(
type=objc._C_PTR + objc._C_CHAR_AS_INT,
type_modifier=objc._C_IN,
c_array_of_fixed_length=4,
),
}
),
)
objc.registerMetaDataForSelector(
b"OC_TestSpecialTypeCode",
b"int8ArrayOf4Out:",
dict(
arguments={
2: dict(
type=objc._C_PTR + objc._C_CHAR_AS_INT,
type_modifier=objc._C_OUT,
c_array_of_fixed_length=4,
),
}
),
)
objc.registerMetaDataForSelector(
b"OC_TestSpecialTypeCode",
b"int8ArrayOf4InOut:",
dict(
arguments={
2: dict(
type=objc._C_PTR + objc._C_CHAR_AS_INT,
type_modifier=objc._C_INOUT,
c_array_of_fixed_length=4,
),
}
),
)
objc.registerMetaDataForSelector(
b"OC_TestSpecialTypeCode",
b"int8ArrayOfCount:In:",
dict(
arguments={
3: dict(
type=objc._C_PTR + objc._C_CHAR_AS_INT,
type_modifier=objc._C_IN,
c_array_of_lenght_in_arg=2,
),
}
),
)
objc.registerMetaDataForSelector(
b"OC_TestSpecialTypeCode",
b"int8ArrayOfCount:Out:",
dict(
arguments={
3: dict(
type=objc._C_PTR + objc._C_CHAR_AS_INT,
type_modifier=objc._C_OUT,
c_array_of_lenght_in_arg=2,
),
}
),
)
objc.registerMetaDataForSelector(
b"OC_TestSpecialTypeCode",
b"int8ArrayOfCount:InOut:",
dict(
arguments={
3: dict(
type=objc._C_PTR + objc._C_CHAR_AS_INT,
type_modifier=objc._C_INOUT,
c_array_of_lenght_in_arg=2,
),
}
),
)
setupMetaData()
class TestTypeCode_int8(TestCase):
def testReturnValue(self):
o = OC_TestSpecialTypeCode.alloc().init()
self.assertEqual(o.int8Value(), 1)
self.assertEqual(o.int8Value(), 2)
self.assertEqual(o.int8Value(), 3)
self.assertEqual(o.int8Value(), 4)
def testReturnValueArray(self):
o = OC_TestSpecialTypeCode.alloc().init()
v = o.int8Array()
self.assertEqual(len(v), 4)
self.assertEqual(v[0], 100)
self.assertEqual(v[1], -56)
self.assertEqual(v[2], -106)
self.assertEqual(v[3], 99)
def testReturnValueString(self):
o = OC_TestSpecialTypeCode.alloc().init()
v = o.int8String()
self.assertIsInstance(v, (list, tuple))
self.assertEqual(len(v), 5)
self.assertEqual(v[0], ord("h"))
self.assertEqual(v[1], ord("e"))
self.assertEqual(v[2], ord("l"))
self.assertEqual(v[3], ord("l"))
self.assertEqual(v[4], ord("o"))
def testSimpleArg(self):
o = OC_TestSpecialTypeCode.alloc().init()
v = o.int8Arg_andint8Arg_(44, 127)
self.assertEqual(v, (44, 127))
v = o.int8Arg_andint8Arg_(ord("a"), ord("b"))
self.assertEqual(v, (ord("a"), ord("b")))
self.assertRaises(ValueError, o.int8Arg_andint8Arg_, "a", "b")
def testStringArgument(self):
o = OC_TestSpecialTypeCode.alloc().init()
v = o.int8StringArg_([1, 2, 3, 4])
self.assertEqual(v, [1, 2, 3, 4])
self.assertRaises(ValueError, o.int8StringArg_, "abc")
self.assertRaises(ValueError, o.int8StringArg_, ["a", "b"])
def testFixedArrayIn(self):
o = OC_TestSpecialTypeCode.alloc().init()
v = o.int8ArrayOf4In_([1, 2, 3, 4])
self.assertEqual(v, [1, 2, 3, 4])
a = array.array("B", [200, 150, 80, 20])
v = o.int8ArrayOf4In_(a)
self.assertEqual(v, (-56, -106, 80, 20))
def testFixedArrayOut(self):
o = OC_TestSpecialTypeCode.alloc().init()
v = o.int8ArrayOf4Out_(None)
self.assertEqual(v, (ord("b"), ord("o"), ord("a"), ord("t")))
o = OC_TestSpecialTypeCode.alloc().init()
a = array.array("b", [0] * 4)
v = o.int8ArrayOf4Out_(a)
self.assertIs(v, a)
self.assertEqual(v[0], ord("b"))
self.assertEqual(v[1], ord("o"))
self.assertEqual(v[2], ord("a"))
self.assertEqual(v[3], ord("t"))
def testFixedArrayInOut_(self):
o = OC_TestSpecialTypeCode.alloc().init()
v, w = o.int8ArrayOf4InOut_([1, 2, 3, 4])
self.assertEqual(v, [1, 2, 3, 4])
self.assertEqual(w, (ord("h"), ord("a"), ord("n"), ord("d")))
if __name__ == "__main__":
main()
|
vidcutter | videocutter | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#######################################################################
#
# VidCutter - media cutter & joiner
#
# copyright © 2018 Pete Alexandrou
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#######################################################################
import logging
import os
import re
import sys
import time
from datetime import timedelta
from functools import partial
from typing import Callable, List, Optional, Union
import sip
import vidcutter
from PyQt5.QtCore import (
QBuffer,
QByteArray,
QDir,
QFile,
QFileInfo,
QModelIndex,
QPoint,
QSize,
Qt,
QTextStream,
QTime,
QTimer,
QUrl,
pyqtSignal,
pyqtSlot,
)
from PyQt5.QtGui import (
QDesktopServices,
QFont,
QFontDatabase,
QIcon,
QKeyEvent,
QPixmap,
QShowEvent,
)
from PyQt5.QtWidgets import (
QAction,
QApplication,
QDialog,
QFileDialog,
QFrame,
QGroupBox,
QHBoxLayout,
QLabel,
QListWidgetItem,
QMainWindow,
QMenu,
QMessageBox,
QPushButton,
QSizePolicy,
QStyleFactory,
QVBoxLayout,
QWidget,
qApp,
)
# noinspection PyUnresolvedReferences
from vidcutter import resources
from vidcutter.about import About
from vidcutter.changelog import Changelog
from vidcutter.libs.config import Config, InvalidMediaException, VideoFilter
from vidcutter.libs.mpvwidget import mpvWidget
from vidcutter.libs.munch import Munch
from vidcutter.libs.notifications import JobCompleteNotification
from vidcutter.libs.taskbarprogress import TaskbarProgress
from vidcutter.libs.videoservice import VideoService
from vidcutter.libs.widgets import (
ClipErrorsDialog,
VCBlinkText,
VCDoubleInputDialog,
VCFilterMenuAction,
VCFrameCounter,
VCInputDialog,
VCMessageBox,
VCProgressDialog,
VCTimeCounter,
VCToolBarButton,
VCVolumeSlider,
)
from vidcutter.mediainfo import MediaInfo
from vidcutter.mediastream import StreamSelector
from vidcutter.settings import SettingsDialog
from vidcutter.updater import Updater
from vidcutter.videolist import VideoList
from vidcutter.videoslider import VideoSlider
from vidcutter.videosliderwidget import VideoSliderWidget
from vidcutter.videostyle import VideoStyleDark, VideoStyleLight
class VideoCutter(QWidget):
errorOccurred = pyqtSignal(str)
timeformat = "hh:mm:ss.zzz"
runtimeformat = "hh:mm:ss"
def __init__(self, parent: QMainWindow):
super(VideoCutter, self).__init__(parent)
self.setObjectName("videocutter")
self.logger = logging.getLogger(__name__)
self.parent = parent
self.theme = self.parent.theme
self.workFolder = self.parent.WORKING_FOLDER
self.settings = self.parent.settings
self.filter_settings = Config.filter_settings()
self.currentMedia, self.mediaAvailable, self.mpvError = None, False, False
self.projectDirty, self.projectSaved, self.debugonstart = False, False, False
self.smartcut_monitor, self.notify = None, None
self.fonts = []
self.initTheme()
self.updater = Updater(self.parent)
self.seekSlider = VideoSlider(self)
self.seekSlider.sliderMoved.connect(self.setPosition)
self.sliderWidget = VideoSliderWidget(self, self.seekSlider)
self.sliderWidget.setLoader(True)
self.taskbar = TaskbarProgress(self.parent)
self.clipTimes = []
self.inCut, self.newproject = False, False
self.finalFilename = ""
self.totalRuntime, self.frameRate = 0, 0
self.notifyInterval = 1000
self.createChapters = self.settings.value("chapters", "on", type=str) in {
"on",
"true",
}
self.enableOSD = self.settings.value("enableOSD", "on", type=str) in {
"on",
"true",
}
self.hardwareDecoding = self.settings.value("hwdec", "on", type=str) in {
"on",
"auto",
}
self.enablePBO = self.settings.value("enablePBO", "off", type=str) in {
"on",
"true",
}
self.keepRatio = self.settings.value("aspectRatio", "keep", type=str) == "keep"
self.keepClips = self.settings.value("keepClips", "off", type=str) in {
"on",
"true",
}
self.nativeDialogs = self.settings.value("nativeDialogs", "on", type=str) in {
"on",
"true",
}
self.indexLayout = self.settings.value("indexLayout", "right", type=str)
self.timelineThumbs = self.settings.value("timelineThumbs", "on", type=str) in {
"on",
"true",
}
self.showConsole = self.settings.value("showConsole", "off", type=str) in {
"on",
"true",
}
self.smartcut = self.settings.value("smartcut", "off", type=str) in {
"on",
"true",
}
self.level1Seek = self.settings.value("level1Seek", 2, type=float)
self.level2Seek = self.settings.value("level2Seek", 5, type=float)
self.verboseLogs = self.parent.verboseLogs
self.lastFolder = self.settings.value("lastFolder", QDir.homePath(), type=str)
self.videoService = VideoService(self.settings, self)
self.videoService.progress.connect(self.seekSlider.updateProgress)
self.videoService.finished.connect(self.smartmonitor)
self.videoService.error.connect(self.completeOnError)
self.videoService.addScenes.connect(self.addScenes)
self.project_files = {
"edl": re.compile(r"(\d+(?:\.?\d+)?)\t(\d+(?:\.?\d+)?)\t([01])"),
"vcp": re.compile(r'(\d+(?:\.?\d+)?)\t(\d+(?:\.?\d+)?)\t([01])\t(".*")$'),
}
self._initIcons()
self._initActions()
self.appmenu = QMenu(self.parent)
self.clipindex_removemenu, self.clipindex_contextmenu = QMenu(self), QMenu(self)
self._initMenus()
self._initNoVideo()
self.cliplist = VideoList(self)
self.cliplist.customContextMenuRequested.connect(self.itemMenu)
self.cliplist.currentItemChanged.connect(self.selectClip)
self.cliplist.model().rowsInserted.connect(self.setProjectDirty)
self.cliplist.model().rowsRemoved.connect(self.setProjectDirty)
self.cliplist.model().rowsMoved.connect(self.setProjectDirty)
self.cliplist.model().rowsMoved.connect(self.syncClipList)
self.listHeaderButtonL = QPushButton(self)
self.listHeaderButtonL.setObjectName("listheaderbutton-left")
self.listHeaderButtonL.setFlat(True)
self.listHeaderButtonL.clicked.connect(self.setClipIndexLayout)
self.listHeaderButtonL.setCursor(Qt.PointingHandCursor)
self.listHeaderButtonL.setFixedSize(14, 14)
self.listHeaderButtonL.setToolTip("Move to left")
self.listHeaderButtonL.setStatusTip(
"Move the Clip Index list to the left side of player"
)
self.listHeaderButtonR = QPushButton(self)
self.listHeaderButtonR.setObjectName("listheaderbutton-right")
self.listHeaderButtonR.setFlat(True)
self.listHeaderButtonR.clicked.connect(self.setClipIndexLayout)
self.listHeaderButtonR.setCursor(Qt.PointingHandCursor)
self.listHeaderButtonR.setFixedSize(14, 14)
self.listHeaderButtonR.setToolTip("Move to right")
self.listHeaderButtonR.setStatusTip(
"Move the Clip Index list to the right side of player"
)
listheaderLayout = QHBoxLayout()
listheaderLayout.setContentsMargins(6, 5, 6, 5)
listheaderLayout.addWidget(self.listHeaderButtonL)
listheaderLayout.addStretch(1)
listheaderLayout.addWidget(self.listHeaderButtonR)
self.listheader = QWidget(self)
self.listheader.setObjectName("listheader")
self.listheader.setFixedWidth(self.cliplist.width())
self.listheader.setLayout(listheaderLayout)
self._initClipIndexHeader()
self.runtimeLabel = QLabel('<div align="right">00:00:00</div>', self)
self.runtimeLabel.setObjectName("runtimeLabel")
self.runtimeLabel.setToolTip("total runtime: 00:00:00")
self.runtimeLabel.setStatusTip("total running time: 00:00:00")
self.clipindex_add = QPushButton(self)
self.clipindex_add.setObjectName("clipadd")
self.clipindex_add.clicked.connect(self.addExternalClips)
self.clipindex_add.setToolTip("Add clips")
self.clipindex_add.setStatusTip(
"Add one or more files to an existing project or an empty list if you are only "
"joining files"
)
self.clipindex_add.setCursor(Qt.PointingHandCursor)
self.clipindex_remove = QPushButton(self)
self.clipindex_remove.setObjectName("clipremove")
self.clipindex_remove.setToolTip("Remove clips")
self.clipindex_remove.setStatusTip("Remove clips from your index")
self.clipindex_remove.setLayoutDirection(Qt.RightToLeft)
self.clipindex_remove.setMenu(self.clipindex_removemenu)
self.clipindex_remove.setCursor(Qt.PointingHandCursor)
if sys.platform in {"win32", "darwin"}:
self.clipindex_add.setStyle(QStyleFactory.create("Fusion"))
self.clipindex_remove.setStyle(QStyleFactory.create("Fusion"))
clipindex_layout = QHBoxLayout()
clipindex_layout.setSpacing(1)
clipindex_layout.setContentsMargins(0, 0, 0, 0)
clipindex_layout.addWidget(self.clipindex_add)
clipindex_layout.addSpacing(1)
clipindex_layout.addWidget(self.clipindex_remove)
clipindexTools = QWidget(self)
clipindexTools.setObjectName("clipindextools")
clipindexTools.setLayout(clipindex_layout)
self.clipindexLayout = QVBoxLayout()
self.clipindexLayout.setSpacing(0)
self.clipindexLayout.setContentsMargins(0, 0, 0, 0)
self.clipindexLayout.addWidget(self.listheader)
self.clipindexLayout.addWidget(self.cliplist)
self.clipindexLayout.addWidget(self.runtimeLabel)
self.clipindexLayout.addSpacing(3)
self.clipindexLayout.addWidget(clipindexTools)
self.videoLayout = QHBoxLayout()
self.videoLayout.setContentsMargins(0, 0, 0, 0)
if self.indexLayout == "left":
self.videoLayout.addLayout(self.clipindexLayout)
self.videoLayout.addSpacing(10)
self.videoLayout.addWidget(self.novideoWidget)
else:
self.videoLayout.addWidget(self.novideoWidget)
self.videoLayout.addSpacing(10)
self.videoLayout.addLayout(self.clipindexLayout)
self.timeCounter = VCTimeCounter(self)
self.timeCounter.timeChanged.connect(
lambda newtime: self.setPosition(newtime.msecsSinceStartOfDay())
)
self.frameCounter = VCFrameCounter(self)
self.frameCounter.setReadOnly(True)
countersLayout = QHBoxLayout()
countersLayout.setContentsMargins(0, 0, 0, 0)
countersLayout.addStretch(1)
# noinspection PyArgumentList
countersLayout.addWidget(QLabel("TIME:", objectName="tcLabel"))
countersLayout.addWidget(self.timeCounter)
countersLayout.addStretch(1)
# noinspection PyArgumentList
countersLayout.addWidget(QLabel("FRAME:", objectName="fcLabel"))
countersLayout.addWidget(self.frameCounter)
countersLayout.addStretch(1)
countersWidget = QWidget(self)
countersWidget.setObjectName("counterwidgets")
countersWidget.setContentsMargins(0, 0, 0, 0)
countersWidget.setLayout(countersLayout)
countersWidget.setMaximumHeight(28)
self.mpvWidget = self.getMPV(self)
self.videoplayerLayout = QVBoxLayout()
self.videoplayerLayout.setSpacing(0)
self.videoplayerLayout.setContentsMargins(0, 0, 0, 0)
self.videoplayerLayout.addWidget(self.mpvWidget)
self.videoplayerLayout.addWidget(countersWidget)
self.videoplayerWidget = QFrame(self)
self.videoplayerWidget.setObjectName("videoplayer")
self.videoplayerWidget.setFrameStyle(QFrame.Box | QFrame.Sunken)
self.videoplayerWidget.setLineWidth(0)
self.videoplayerWidget.setMidLineWidth(0)
self.videoplayerWidget.setVisible(False)
self.videoplayerWidget.setLayout(self.videoplayerLayout)
# noinspection PyArgumentList
self.thumbnailsButton = QPushButton(
self,
flat=True,
checkable=True,
objectName="thumbnailsButton",
statusTip="Toggle timeline thumbnails",
cursor=Qt.PointingHandCursor,
toolTip="Toggle thumbnails",
)
self.thumbnailsButton.setFixedSize(32, 29 if self.theme == "dark" else 31)
self.thumbnailsButton.setChecked(self.timelineThumbs)
self.thumbnailsButton.toggled.connect(self.toggleThumbs)
if self.timelineThumbs:
self.seekSlider.setObjectName("nothumbs")
# noinspection PyArgumentList
self.osdButton = QPushButton(
self,
flat=True,
checkable=True,
objectName="osdButton",
toolTip="Toggle OSD",
statusTip="Toggle on-screen display",
cursor=Qt.PointingHandCursor,
)
self.osdButton.setFixedSize(31, 29 if self.theme == "dark" else 31)
self.osdButton.setChecked(self.enableOSD)
self.osdButton.toggled.connect(self.toggleOSD)
# noinspection PyArgumentList
self.consoleButton = QPushButton(
self,
flat=True,
checkable=True,
objectName="consoleButton",
statusTip="Toggle console window",
toolTip="Toggle console",
cursor=Qt.PointingHandCursor,
)
self.consoleButton.setFixedSize(31, 29 if self.theme == "dark" else 31)
self.consoleButton.setChecked(self.showConsole)
self.consoleButton.toggled.connect(self.toggleConsole)
if self.showConsole:
self.mpvWidget.setLogLevel("v")
os.environ["DEBUG"] = "1"
self.parent.console.show()
# noinspection PyArgumentList
self.chaptersButton = QPushButton(
self,
flat=True,
checkable=True,
objectName="chaptersButton",
statusTip="Automatically create chapters per clip",
toolTip="Create chapters",
cursor=Qt.PointingHandCursor,
)
self.chaptersButton.setFixedSize(31, 29 if self.theme == "dark" else 31)
self.chaptersButton.setChecked(self.createChapters)
self.chaptersButton.toggled.connect(self.toggleChapters)
# noinspection PyArgumentList
self.smartcutButton = QPushButton(
self,
flat=True,
checkable=True,
objectName="smartcutButton",
toolTip="Toggle SmartCut",
statusTip="Toggle frame accurate cutting",
cursor=Qt.PointingHandCursor,
)
self.smartcutButton.setFixedSize(32, 29 if self.theme == "dark" else 31)
self.smartcutButton.setChecked(self.smartcut)
self.smartcutButton.toggled.connect(self.toggleSmartCut)
# noinspection PyArgumentList
self.muteButton = QPushButton(
objectName="muteButton",
icon=self.unmuteIcon,
flat=True,
toolTip="Mute",
statusTip="Toggle audio mute",
iconSize=QSize(16, 16),
clicked=self.muteAudio,
cursor=Qt.PointingHandCursor,
)
# noinspection PyArgumentList
self.volSlider = VCVolumeSlider(
orientation=Qt.Horizontal,
toolTip="Volume",
statusTip="Adjust volume level",
cursor=Qt.PointingHandCursor,
value=self.parent.startupvol,
minimum=0,
maximum=130,
minimumHeight=22,
sliderMoved=self.setVolume,
)
# noinspection PyArgumentList
self.fullscreenButton = QPushButton(
objectName="fullscreenButton",
icon=self.fullscreenIcon,
flat=True,
toolTip="Toggle fullscreen",
statusTip="Switch to fullscreen video",
iconSize=QSize(14, 14),
clicked=self.toggleFullscreen,
cursor=Qt.PointingHandCursor,
enabled=False,
)
# noinspection PyArgumentList
self.settingsButton = QPushButton(
self,
toolTip="Settings",
cursor=Qt.PointingHandCursor,
flat=True,
statusTip="Configure application settings",
objectName="settingsButton",
clicked=self.showSettings,
)
self.settingsButton.setFixedSize(QSize(33, 32))
# noinspection PyArgumentList
self.streamsButton = QPushButton(
self,
toolTip="Media streams",
cursor=Qt.PointingHandCursor,
flat=True,
statusTip="Select the media streams to be included",
objectName="streamsButton",
clicked=self.selectStreams,
enabled=False,
)
self.streamsButton.setFixedSize(QSize(33, 32))
# noinspection PyArgumentList
self.mediainfoButton = QPushButton(
self,
toolTip="Media information",
cursor=Qt.PointingHandCursor,
flat=True,
statusTip="View technical details about current media",
objectName="mediainfoButton",
clicked=self.mediaInfo,
enabled=False,
)
self.mediainfoButton.setFixedSize(QSize(33, 32))
# noinspection PyArgumentList
self.menuButton = QPushButton(
self,
toolTip="Menu",
cursor=Qt.PointingHandCursor,
flat=True,
objectName="menuButton",
clicked=self.showAppMenu,
statusTip="View menu options",
)
self.menuButton.setFixedSize(QSize(33, 32))
audioLayout = QHBoxLayout()
audioLayout.setContentsMargins(0, 0, 0, 0)
audioLayout.addWidget(self.muteButton)
audioLayout.addSpacing(5)
audioLayout.addWidget(self.volSlider)
audioLayout.addSpacing(5)
audioLayout.addWidget(self.fullscreenButton)
self.toolbar_open = VCToolBarButton(
"Open Media", "Open and load a media file to begin", parent=self
)
self.toolbar_open.clicked.connect(self.openMedia)
self.toolbar_play = VCToolBarButton(
"Play Media", "Play currently loaded media file", parent=self
)
self.toolbar_play.setEnabled(False)
self.toolbar_play.clicked.connect(self.playMedia)
self.toolbar_start = VCToolBarButton(
"Start Clip",
"Start a new clip from the current timeline position",
parent=self,
)
self.toolbar_start.setEnabled(False)
self.toolbar_start.clicked.connect(self.clipStart)
self.toolbar_end = VCToolBarButton(
"End Clip", "End a new clip at the current timeline position", parent=self
)
self.toolbar_end.setEnabled(False)
self.toolbar_end.clicked.connect(self.clipEnd)
self.toolbar_save = VCToolBarButton(
"Save Media", "Save clips to a new media file", parent=self
)
self.toolbar_save.setObjectName("savebutton")
self.toolbar_save.setEnabled(False)
self.toolbar_save.clicked.connect(self.saveMedia)
toolbarLayout = QHBoxLayout()
toolbarLayout.setContentsMargins(0, 0, 0, 0)
toolbarLayout.addStretch(1)
toolbarLayout.addWidget(self.toolbar_open)
toolbarLayout.addStretch(1)
toolbarLayout.addWidget(self.toolbar_play)
toolbarLayout.addStretch(1)
toolbarLayout.addWidget(self.toolbar_start)
toolbarLayout.addStretch(1)
toolbarLayout.addWidget(self.toolbar_end)
toolbarLayout.addStretch(1)
toolbarLayout.addWidget(self.toolbar_save)
toolbarLayout.addStretch(1)
self.toolbarGroup = QGroupBox()
self.toolbarGroup.setLayout(toolbarLayout)
self.toolbarGroup.setStyleSheet("QGroupBox { border: 0; }")
self.setToolBarStyle(self.settings.value("toolbarLabels", "beside", type=str))
togglesLayout = QHBoxLayout()
togglesLayout.setSpacing(0)
togglesLayout.setContentsMargins(0, 0, 0, 0)
togglesLayout.addWidget(self.consoleButton)
togglesLayout.addWidget(self.osdButton)
togglesLayout.addWidget(self.thumbnailsButton)
togglesLayout.addWidget(self.chaptersButton)
togglesLayout.addWidget(self.smartcutButton)
togglesLayout.addStretch(1)
settingsLayout = QHBoxLayout()
settingsLayout.setSpacing(0)
settingsLayout.setContentsMargins(0, 0, 0, 0)
settingsLayout.addWidget(self.settingsButton)
settingsLayout.addSpacing(5)
settingsLayout.addWidget(self.streamsButton)
settingsLayout.addSpacing(5)
settingsLayout.addWidget(self.mediainfoButton)
settingsLayout.addSpacing(5)
settingsLayout.addWidget(self.menuButton)
groupLayout = QVBoxLayout()
groupLayout.addLayout(audioLayout)
groupLayout.addSpacing(10)
groupLayout.addLayout(settingsLayout)
controlsLayout = QHBoxLayout()
if sys.platform != "darwin":
controlsLayout.setContentsMargins(0, 0, 0, 0)
controlsLayout.addSpacing(5)
else:
controlsLayout.setContentsMargins(10, 10, 10, 0)
controlsLayout.addLayout(togglesLayout)
controlsLayout.addSpacing(20)
controlsLayout.addStretch(1)
controlsLayout.addWidget(self.toolbarGroup)
controlsLayout.addStretch(1)
controlsLayout.addSpacing(20)
controlsLayout.addLayout(groupLayout)
if sys.platform != "darwin":
controlsLayout.addSpacing(5)
layout = QVBoxLayout()
layout.setSpacing(0)
layout.setContentsMargins(10, 10, 10, 0)
layout.addLayout(self.videoLayout)
layout.addWidget(self.sliderWidget)
layout.addSpacing(5)
layout.addLayout(controlsLayout)
self.setLayout(layout)
self.seekSlider.initStyle()
@pyqtSlot()
def showAppMenu(self) -> None:
pos = self.menuButton.mapToGlobal(self.menuButton.rect().topLeft())
pos.setX(pos.x() - self.appmenu.sizeHint().width() + 30)
pos.setY(pos.y() - 28)
self.appmenu.popup(pos, self.quitAction)
def initTheme(self) -> None:
qApp.setStyle(VideoStyleDark() if self.theme == "dark" else VideoStyleLight())
self.fonts = [
QFontDatabase.addApplicationFont(":/fonts/FuturaLT.ttf"),
QFontDatabase.addApplicationFont(":/fonts/NotoSans-Bold.ttf"),
QFontDatabase.addApplicationFont(":/fonts/NotoSans-Regular.ttf"),
]
self.style().loadQSS(self.theme)
QApplication.setFont(
QFont("Noto Sans", 12 if sys.platform == "darwin" else 10, 300)
)
def getMPV(
self,
parent: QWidget = None,
file: str = None,
start: float = 0,
pause: bool = True,
mute: bool = False,
volume: int = None,
) -> mpvWidget:
widget = mpvWidget(
parent=parent,
file=file,
# vo='opengl-cb',
pause=pause,
start=start,
mute=mute,
keep_open="always",
idle=True,
osd_font=self._osdfont,
osd_level=0,
osd_align_x="left",
osd_align_y="top",
cursor_autohide=False,
input_cursor=False,
input_default_bindings=False,
stop_playback_on_init_failure=False,
input_vo_keyboard=False,
sub_auto=False,
sid=False,
video_sync="display-vdrop",
audio_file_auto=False,
quiet=True,
volume=volume if volume is not None else self.parent.startupvol,
opengl_pbo=self.enablePBO,
keepaspect=self.keepRatio,
hwdec=("auto" if self.hardwareDecoding else "no"),
)
widget.durationChanged.connect(self.on_durationChanged)
widget.positionChanged.connect(self.on_positionChanged)
return widget
def _initNoVideo(self) -> None:
self.novideoWidget = QWidget(self)
self.novideoWidget.setObjectName("novideoWidget")
self.novideoWidget.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
openmediaLabel = VCBlinkText("open media to begin", self)
openmediaLabel.setAlignment(Qt.AlignHCenter)
_version = "v{}".format(qApp.applicationVersion())
if self.parent.flatpak:
_version += ' <font size="-1">- FLATPAK</font>'
versionLabel = QLabel(_version, self)
versionLabel.setObjectName("novideoversion")
versionLabel.setAlignment(Qt.AlignRight)
versionLayout = QHBoxLayout()
versionLayout.setSpacing(0)
versionLayout.setContentsMargins(0, 0, 10, 8)
versionLayout.addWidget(versionLabel)
novideoLayout = QVBoxLayout(self.novideoWidget)
novideoLayout.setSpacing(0)
novideoLayout.setContentsMargins(0, 0, 0, 0)
novideoLayout.addStretch(20)
novideoLayout.addWidget(openmediaLabel)
novideoLayout.addStretch(1)
novideoLayout.addLayout(versionLayout)
def _initIcons(self) -> None:
self.appIcon = qApp.windowIcon()
self.muteIcon = QIcon(":/images/{}/muted.png".format(self.theme))
self.unmuteIcon = QIcon(":/images/{}/unmuted.png".format(self.theme))
self.chapterIcon = QIcon(":/images/chapters.png")
self.upIcon = QIcon(":/images/up.png")
self.downIcon = QIcon(":/images/down.png")
self.removeIcon = QIcon(":/images/remove.png")
self.removeAllIcon = QIcon(":/images/remove-all.png")
self.openProjectIcon = QIcon(":/images/open.png")
self.saveProjectIcon = QIcon(":/images/save.png")
self.filtersIcon = QIcon(":/images/filters.png")
self.mediaInfoIcon = QIcon(":/images/info.png")
self.streamsIcon = QIcon(":/images/streams.png")
self.changelogIcon = QIcon(":/images/changelog.png")
self.viewLogsIcon = QIcon(":/images/viewlogs.png")
self.updateCheckIcon = QIcon(":/images/update.png")
self.keyRefIcon = QIcon(":/images/keymap.png")
self.fullscreenIcon = QIcon(":/images/{}/fullscreen.png".format(self.theme))
self.settingsIcon = QIcon(":/images/settings.png")
self.quitIcon = QIcon(":/images/quit.png")
# noinspection PyArgumentList
def _initActions(self) -> None:
self.moveItemUpAction = QAction(
self.upIcon,
"Move clip up",
self,
statusTip="Move clip position up in list",
triggered=self.moveItemUp,
enabled=False,
)
self.moveItemDownAction = QAction(
self.downIcon,
"Move clip down",
self,
triggered=self.moveItemDown,
statusTip="Move clip position down in list",
enabled=False,
)
self.removeItemAction = QAction(
self.removeIcon,
"Remove selected clip",
self,
triggered=self.removeItem,
statusTip="Remove selected clip from list",
enabled=False,
)
self.removeAllAction = QAction(
self.removeAllIcon,
"Remove all clips",
self,
triggered=self.clearList,
statusTip="Remove all clips from list",
enabled=False,
)
self.editChapterAction = QAction(
self.chapterIcon,
"Edit chapter name",
self,
triggered=self.editChapter,
statusTip="Edit the selected chapter name",
enabled=False,
)
self.streamsAction = QAction(
self.streamsIcon,
"Media streams",
self,
triggered=self.selectStreams,
statusTip="Select the media streams to be included",
enabled=False,
)
self.mediainfoAction = QAction(
self.mediaInfoIcon,
"Media information",
self,
triggered=self.mediaInfo,
statusTip="View technical details about current media",
enabled=False,
)
self.openProjectAction = QAction(
self.openProjectIcon,
"Open project file",
self,
triggered=self.openProject,
statusTip="Open a previously saved project file (*.vcp or *.edl)",
enabled=True,
)
self.saveProjectAction = QAction(
self.saveProjectIcon,
"Save project file",
self,
triggered=self.saveProject,
statusTip="Save current work to a project file (*.vcp or *.edl)",
enabled=False,
)
self.changelogAction = QAction(
self.changelogIcon,
"View changelog",
self,
triggered=self.viewChangelog,
statusTip="View log of changes",
)
self.viewLogsAction = QAction(
self.viewLogsIcon,
"View log file",
self,
triggered=VideoCutter.viewLogs,
statusTip="View the application's log file",
)
self.updateCheckAction = QAction(
self.updateCheckIcon,
"Check for updates...",
self,
statusTip="Check for application updates",
triggered=self.updater.check,
)
self.aboutQtAction = QAction(
"About Qt", self, triggered=qApp.aboutQt, statusTip="About Qt"
)
self.aboutAction = QAction(
"About {}".format(qApp.applicationName()),
self,
triggered=self.aboutApp,
statusTip="About {}".format(qApp.applicationName()),
)
self.keyRefAction = QAction(
self.keyRefIcon,
"Keyboard shortcuts",
self,
triggered=self.showKeyRef,
statusTip="View shortcut key bindings",
)
self.settingsAction = QAction(
self.settingsIcon,
"Settings",
self,
triggered=self.showSettings,
statusTip="Configure application settings",
)
self.fullscreenAction = QAction(
self.fullscreenIcon,
"Toggle fullscreen",
self,
triggered=self.toggleFullscreen,
statusTip="Toggle fullscreen display mode",
enabled=False,
)
self.quitAction = QAction(
self.quitIcon,
"Quit",
self,
triggered=self.parent.close,
statusTip="Quit the application",
)
@property
def _filtersMenu(self) -> QMenu:
menu = QMenu("Video filters", self)
self.blackdetectAction = VCFilterMenuAction(
QPixmap(":/images/blackdetect.png"),
"BLACKDETECT",
"Create clips via black frame detection",
"Useful for skipping commercials or detecting scene transitions",
self,
)
if sys.platform == "darwin":
self.blackdetectAction.triggered.connect(
lambda: self.configFilters(VideoFilter.BLACKDETECT), Qt.QueuedConnection
)
else:
self.blackdetectAction.triggered.connect(
lambda: self.configFilters(VideoFilter.BLACKDETECT), Qt.DirectConnection
)
self.blackdetectAction.setEnabled(False)
menu.setIcon(self.filtersIcon)
menu.addAction(self.blackdetectAction)
return menu
def _initMenus(self) -> None:
self.appmenu.addAction(self.openProjectAction)
self.appmenu.addAction(self.saveProjectAction)
self.appmenu.addSeparator()
self.appmenu.addMenu(self._filtersMenu)
self.appmenu.addSeparator()
self.appmenu.addAction(self.fullscreenAction)
self.appmenu.addAction(self.streamsAction)
self.appmenu.addAction(self.mediainfoAction)
self.appmenu.addAction(self.keyRefAction)
self.appmenu.addSeparator()
self.appmenu.addAction(self.settingsAction)
self.appmenu.addSeparator()
self.appmenu.addAction(self.viewLogsAction)
self.appmenu.addAction(self.updateCheckAction)
self.appmenu.addSeparator()
self.appmenu.addAction(self.changelogAction)
self.appmenu.addAction(self.aboutQtAction)
self.appmenu.addAction(self.aboutAction)
self.appmenu.addSeparator()
self.appmenu.addAction(self.quitAction)
self.clipindex_contextmenu.addAction(self.editChapterAction)
self.clipindex_contextmenu.addSeparator()
self.clipindex_contextmenu.addAction(self.moveItemUpAction)
self.clipindex_contextmenu.addAction(self.moveItemDownAction)
self.clipindex_contextmenu.addSeparator()
self.clipindex_contextmenu.addAction(self.removeItemAction)
self.clipindex_contextmenu.addAction(self.removeAllAction)
self.clipindex_removemenu.addActions(
[self.removeItemAction, self.removeAllAction]
)
self.clipindex_removemenu.aboutToShow.connect(self.initRemoveMenu)
if sys.platform in {"win32", "darwin"}:
self.appmenu.setStyle(QStyleFactory.create("Fusion"))
self.clipindex_contextmenu.setStyle(QStyleFactory.create("Fusion"))
self.clipindex_removemenu.setStyle(QStyleFactory.create("Fusion"))
def _initClipIndexHeader(self) -> None:
if self.indexLayout == "left":
self.listHeaderButtonL.setVisible(False)
self.listHeaderButtonR.setVisible(True)
else:
self.listHeaderButtonL.setVisible(True)
self.listHeaderButtonR.setVisible(False)
@pyqtSlot()
def setClipIndexLayout(self) -> None:
self.indexLayout = "left" if self.indexLayout == "right" else "right"
self.settings.setValue("indexLayout", self.indexLayout)
left = self.videoLayout.takeAt(0)
spacer = self.videoLayout.takeAt(0)
right = self.videoLayout.takeAt(0)
if isinstance(left, QVBoxLayout):
if self.indexLayout == "left":
self.videoLayout.addItem(left)
self.videoLayout.addItem(spacer)
self.videoLayout.addItem(right)
else:
self.videoLayout.addItem(right)
self.videoLayout.addItem(spacer)
self.videoLayout.addItem(left)
else:
if self.indexLayout == "left":
self.videoLayout.addItem(right)
self.videoLayout.addItem(spacer)
self.videoLayout.addItem(left)
else:
self.videoLayout.addItem(left)
self.videoLayout.addItem(spacer)
self.videoLayout.addItem(right)
self._initClipIndexHeader()
def setToolBarStyle(self, labelstyle: str = "beside") -> None:
buttonlist = self.toolbarGroup.findChildren(VCToolBarButton)
[button.setLabelStyle(labelstyle) for button in buttonlist]
def setRunningTime(self, runtime: str) -> None:
self.runtimeLabel.setText('<div align="right">{}</div>'.format(runtime))
self.runtimeLabel.setToolTip("total runtime: {}".format(runtime))
self.runtimeLabel.setStatusTip("total running time: {}".format(runtime))
def getFileDialogOptions(self) -> QFileDialog.Options:
options = QFileDialog.HideNameFilterDetails
if not self.nativeDialogs:
options |= QFileDialog.DontUseNativeDialog
# noinspection PyTypeChecker
return options
@pyqtSlot()
def showSettings(self):
settingsDialog = SettingsDialog(self.videoService, self)
settingsDialog.exec_()
@pyqtSlot()
def initRemoveMenu(self):
self.removeItemAction.setEnabled(False)
self.removeAllAction.setEnabled(False)
if self.cliplist.count():
self.removeAllAction.setEnabled(True)
if len(self.cliplist.selectedItems()):
self.removeItemAction.setEnabled(True)
def itemMenu(self, pos: QPoint) -> None:
globalPos = self.cliplist.mapToGlobal(pos)
self.editChapterAction.setEnabled(False)
self.moveItemUpAction.setEnabled(False)
self.moveItemDownAction.setEnabled(False)
self.initRemoveMenu()
index = self.cliplist.currentRow()
if index != -1:
if len(self.cliplist.selectedItems()):
self.editChapterAction.setEnabled(self.createChapters)
if not self.inCut:
if index > 0:
self.moveItemUpAction.setEnabled(True)
if index < self.cliplist.count() - 1:
self.moveItemDownAction.setEnabled(True)
self.clipindex_contextmenu.exec_(globalPos)
def editChapter(self) -> None:
index = self.cliplist.currentRow()
name = self.clipTimes[index][4]
name = name if name is not None else "Chapter {}".format(index + 1)
dialog = VCInputDialog(self, "Edit chapter name", "Chapter name:", name)
dialog.accepted.connect(lambda: self.on_editChapter(index, dialog.input.text()))
dialog.exec_()
def on_editChapter(self, index: int, text: str) -> None:
self.clipTimes[index][4] = text
self.renderClipIndex()
def moveItemUp(self) -> None:
index = self.cliplist.currentRow()
if index != -1:
tmpItem = self.clipTimes[index]
del self.clipTimes[index]
self.clipTimes.insert(index - 1, tmpItem)
self.showText("clip moved up")
self.renderClipIndex()
def moveItemDown(self) -> None:
index = self.cliplist.currentRow()
if index != -1:
tmpItem = self.clipTimes[index]
del self.clipTimes[index]
self.clipTimes.insert(index + 1, tmpItem)
self.showText("clip moved down")
self.renderClipIndex()
def removeItem(self) -> None:
index = self.cliplist.currentRow()
if self.mediaAvailable:
if self.inCut and index == self.cliplist.count() - 1:
self.inCut = False
self.initMediaControls()
elif len(self.clipTimes) == 0:
self.initMediaControls(False)
del self.clipTimes[index]
self.cliplist.takeItem(index)
self.showText("clip removed")
self.renderClipIndex()
def clearList(self) -> None:
self.clipTimes.clear()
self.cliplist.clear()
self.showText("all clips cleared")
if self.mediaAvailable:
self.inCut = False
self.initMediaControls(True)
else:
self.initMediaControls(False)
self.renderClipIndex()
def projectFilters(self, savedialog: bool = False) -> str:
if savedialog:
return "VidCutter Project (*.vcp);;MPlayer EDL (*.edl)"
elif self.mediaAvailable:
return "Project files (*.edl *.vcp);;VidCutter Project (*.vcp);;MPlayer EDL (*.edl);;All files (*)"
else:
return "VidCutter Project (*.vcp);;All files (*)"
@staticmethod
def mediaFilters(initial: bool = False) -> str:
filters = "All media files (*.{})".format(
" *.".join(VideoService.config.filters.get("all"))
)
if initial:
return filters
filters += ";;{};;All files (*)".format(
";;".join(VideoService.config.filters.get("types"))
)
return filters
def openMedia(self) -> Optional[Callable]:
cancel, callback = self.saveWarning()
if cancel:
if callback is not None:
return callback()
else:
return
filename, _ = QFileDialog.getOpenFileName(
parent=self.parent,
caption="Open media file",
filter=self.mediaFilters(),
initialFilter=self.mediaFilters(True),
directory=(
self.lastFolder if os.path.exists(self.lastFolder) else QDir.homePath()
),
options=self.getFileDialogOptions(),
)
if filename is not None and len(filename.strip()):
self.lastFolder = QFileInfo(filename).absolutePath()
self.loadMedia(filename)
# noinspection PyUnusedLocal
def openProject(
self, checked: bool = False, project_file: str = None
) -> Optional[Callable]:
cancel, callback = self.saveWarning()
if cancel:
if callback is not None:
return callback()
else:
return
initialFilter = (
"Project files (*.edl *.vcp)"
if self.mediaAvailable
else "VidCutter Project (*.vcp)"
)
if project_file is None:
project_file, _ = QFileDialog.getOpenFileName(
parent=self.parent,
caption="Open project file",
filter=self.projectFilters(),
initialFilter=initialFilter,
directory=(
self.lastFolder
if os.path.exists(self.lastFolder)
else QDir.homePath()
),
options=self.getFileDialogOptions(),
)
if project_file is not None and len(project_file.strip()):
if project_file != os.path.join(
QDir.tempPath(), self.parent.TEMP_PROJECT_FILE
):
self.lastFolder = QFileInfo(project_file).absolutePath()
file = QFile(project_file)
info = QFileInfo(file)
project_type = info.suffix()
if not file.open(QFile.ReadOnly | QFile.Text):
QMessageBox.critical(
self.parent,
"Open project file",
"Cannot read project file {0}:\n\n{1}".format(
project_file, file.errorString()
),
)
return
qApp.setOverrideCursor(Qt.WaitCursor)
self.clipTimes.clear()
linenum = 1
while not file.atEnd():
# noinspection PyUnresolvedReferences
line = file.readLine().trimmed()
if line.length() > 0:
try:
line = line.data().decode()
except UnicodeDecodeError:
qApp.restoreOverrideCursor()
self.logger.error(
"Invalid project file was selected", exc_info=True
)
sys.stderr.write("Invalid project file was selected")
QMessageBox.critical(
self.parent,
"Invalid project file",
"Could not make sense of the selected project file. Try viewing it in a "
"text editor to ensure it is valid and not corrupted.",
)
return
if project_type == "vcp" and linenum == 1:
self.loadMedia(line)
time.sleep(1)
else:
mo = self.project_files[project_type].match(line)
if mo:
start, stop, _, chapter = mo.groups()
clip_start = self.delta2QTime(float(start))
clip_end = self.delta2QTime(float(stop))
clip_image = self.captureImage(
self.currentMedia, clip_start
)
if (
project_type == "vcp"
and self.createChapters
and len(chapter)
):
chapter = chapter[1 : len(chapter) - 1]
if not len(chapter):
chapter = None
else:
chapter = None
self.clipTimes.append(
[clip_start, clip_end, clip_image, "", chapter]
)
else:
qApp.restoreOverrideCursor()
QMessageBox.critical(
self.parent,
"Invalid project file",
"Invalid entry at line {0}:\n\n{1}".format(
linenum, line
),
)
return
linenum += 1
self.toolbar_start.setEnabled(True)
self.toolbar_end.setDisabled(True)
self.seekSlider.setRestrictValue(0, False)
self.blackdetectAction.setEnabled(True)
self.inCut = False
self.newproject = True
QTimer.singleShot(2000, self.selectClip)
qApp.restoreOverrideCursor()
if project_file != os.path.join(
QDir.tempPath(), self.parent.TEMP_PROJECT_FILE
):
self.showText("project loaded")
def saveProject(self, reboot: bool = False) -> None:
if self.currentMedia is None:
return
if self.hasExternals():
h2color = "#C681D5" if self.theme == "dark" else "#642C68"
acolor = "#EA95FF" if self.theme == "dark" else "#441D4E"
nosavetext = """
<style>
h2 {{
color: {h2color};
font-family: "Futura LT", sans-serif;
font-weight: normal;
}}
a {{
color: {acolor};
text-decoration: none;
font-weight: bold;
}}
</style>
<table border="0" cellpadding="6" cellspacing="0" width="350">
<tr>
<td><h2>Cannot save your current project</h2></td>
</tr>
<tr>
<td>
<p>Cannot save project containing external media files. Remove
all media files you have externally added and try again.</p>
</td>
</tr>
</table>""".format(**locals())
nosave = QMessageBox(
QMessageBox.Critical,
"Cannot save project",
nosavetext,
parent=self.parent,
)
nosave.setStandardButtons(QMessageBox.Ok)
nosave.exec_()
return
project_file, _ = os.path.splitext(self.currentMedia)
if reboot:
project_save = os.path.join(QDir.tempPath(), self.parent.TEMP_PROJECT_FILE)
ptype = "VidCutter Project (*.vcp)"
else:
project_save, ptype = QFileDialog.getSaveFileName(
parent=self.parent,
caption="Save project",
directory="{}.vcp".format(project_file),
filter=self.projectFilters(True),
initialFilter="VidCutter Project (*.vcp)",
options=self.getFileDialogOptions(),
)
if project_save is not None and len(project_save.strip()):
file = QFile(project_save)
if not file.open(QFile.WriteOnly | QFile.Text):
QMessageBox.critical(
self.parent,
"Cannot save project",
"Cannot save project file at {0}:\n\n{1}".format(
project_save, file.errorString()
),
)
return
qApp.setOverrideCursor(Qt.WaitCursor)
if ptype == "VidCutter Project (*.vcp)":
# noinspection PyUnresolvedReferences
QTextStream(file) << "{}\n".format(self.currentMedia)
for clip in self.clipTimes:
start_time = timedelta(
hours=clip[0].hour(),
minutes=clip[0].minute(),
seconds=clip[0].second(),
milliseconds=clip[0].msec(),
)
stop_time = timedelta(
hours=clip[1].hour(),
minutes=clip[1].minute(),
seconds=clip[1].second(),
milliseconds=clip[1].msec(),
)
if ptype == "VidCutter Project (*.vcp)":
if self.createChapters:
chapter = (
'"{}"'.format(clip[4]) if clip[4] is not None else '""'
)
else:
chapter = ""
# noinspection PyUnresolvedReferences
QTextStream(file) << "{0}\t{1}\t{2}\t{3}\n".format(
self.delta2String(start_time),
self.delta2String(stop_time),
0,
chapter,
)
else:
# noinspection PyUnresolvedReferences
QTextStream(file) << "{0}\t{1}\t{2}\n".format(
self.delta2String(start_time), self.delta2String(stop_time), 0
)
qApp.restoreOverrideCursor()
self.projectSaved = True
if not reboot:
self.showText("project file saved")
def loadMedia(self, filename: str) -> None:
if not os.path.isfile(filename):
return
self.currentMedia = filename
self.initMediaControls(True)
self.projectDirty, self.projectSaved = False, False
self.cliplist.clear()
self.clipTimes.clear()
self.totalRuntime = 0
self.setRunningTime(
self.delta2QTime(self.totalRuntime).toString(self.runtimeformat)
)
self.seekSlider.clearRegions()
self.taskbar.init()
self.parent.setWindowTitle(
"{0} - {1}".format(
qApp.applicationName(), os.path.basename(self.currentMedia)
)
)
if not self.mediaAvailable:
self.videoLayout.replaceWidget(self.novideoWidget, self.videoplayerWidget)
self.novideoWidget.hide()
self.novideoWidget.deleteLater()
self.videoplayerWidget.show()
self.mediaAvailable = True
try:
self.videoService.setMedia(self.currentMedia)
self.seekSlider.setFocus()
self.mpvWidget.play(self.currentMedia)
except InvalidMediaException:
qApp.restoreOverrideCursor()
self.initMediaControls(False)
self.logger.error("Could not load media file", exc_info=True)
QMessageBox.critical(
self.parent,
"Could not load media file",
"<h3>Invalid media file selected</h3><p>All attempts to make sense of the file have "
"failed. Try viewing it in another media player and if it plays as expected please "
"report it as a bug. Use the link in the About VidCutter menu option for details "
"and make sure to include your operating system, video card, the invalid media file "
"and the version of VidCutter you are currently using.</p>",
)
def setPlayButton(self, playing: bool = False) -> None:
self.toolbar_play.setup(
"{} Media".format("Pause" if playing else "Play"),
"Pause currently playing media"
if playing
else "Play currently loaded media",
True,
)
def playMedia(self) -> None:
playstate = self.mpvWidget.property("pause")
self.setPlayButton(playstate)
self.taskbar.setState(playstate)
self.timeCounter.clearFocus()
self.frameCounter.clearFocus()
self.mpvWidget.pause()
def showText(self, text: str, duration: int = 3, override: bool = False) -> None:
if self.mediaAvailable:
if not self.osdButton.isChecked() and not override:
return
if len(text.strip()):
self.mpvWidget.showText(text, duration)
def initMediaControls(self, flag: bool = True) -> None:
self.toolbar_play.setEnabled(flag)
self.toolbar_start.setEnabled(flag)
self.toolbar_end.setEnabled(False)
self.toolbar_save.setEnabled(False)
self.streamsAction.setEnabled(flag)
self.streamsButton.setEnabled(flag)
self.mediainfoAction.setEnabled(flag)
self.mediainfoButton.setEnabled(flag)
self.fullscreenButton.setEnabled(flag)
self.fullscreenAction.setEnabled(flag)
self.seekSlider.clearRegions()
self.blackdetectAction.setEnabled(flag)
if flag:
self.seekSlider.setRestrictValue(0)
else:
self.seekSlider.setValue(0)
self.seekSlider.setRange(0, 0)
self.timeCounter.reset()
self.frameCounter.reset()
self.openProjectAction.setEnabled(flag)
self.saveProjectAction.setEnabled(False)
@pyqtSlot(int)
def setPosition(self, position: int) -> None:
if position >= self.seekSlider.restrictValue:
self.mpvWidget.seek(position / 1000)
@pyqtSlot(float, int)
def on_positionChanged(self, progress: float, frame: int) -> None:
progress *= 1000
if self.seekSlider.restrictValue < progress or progress == 0:
self.seekSlider.setValue(int(progress))
self.timeCounter.setTime(
self.delta2QTime(round(progress)).toString(self.timeformat)
)
self.frameCounter.setFrame(frame)
if self.seekSlider.maximum() > 0:
self.taskbar.setProgress(
float(progress / self.seekSlider.maximum()), True
)
@pyqtSlot(float, int)
def on_durationChanged(self, duration: float, frames: int) -> None:
duration *= 1000
self.seekSlider.setRange(0, int(duration))
self.timeCounter.setDuration(
self.delta2QTime(round(duration)).toString(self.timeformat)
)
self.frameCounter.setFrameCount(frames)
@pyqtSlot()
@pyqtSlot(QListWidgetItem)
def selectClip(self, item: QListWidgetItem = None) -> None:
# noinspection PyBroadException
try:
row = self.cliplist.row(item) if item is not None else 0
if item is None:
self.cliplist.item(row).setSelected(True)
if not len(self.clipTimes[row][3]):
self.seekSlider.selectRegion(row)
self.setPosition(self.clipTimes[row][0].msecsSinceStartOfDay())
except Exception:
self.doPass()
def muteAudio(self) -> None:
if self.mpvWidget.property("mute"):
self.showText("audio enabled")
self.muteButton.setIcon(self.unmuteIcon)
self.muteButton.setToolTip("Mute")
else:
self.showText("audio disabled")
self.muteButton.setIcon(self.muteIcon)
self.muteButton.setToolTip("Unmute")
self.mpvWidget.mute()
def setVolume(self, vol: int) -> None:
self.settings.setValue("volume", vol)
if self.mediaAvailable:
self.mpvWidget.volume(vol)
@pyqtSlot(bool)
def toggleThumbs(self, checked: bool) -> None:
self.seekSlider.showThumbs = checked
self.saveSetting("timelineThumbs", checked)
if checked:
self.showText("thumbnails enabled")
self.seekSlider.initStyle()
if self.mediaAvailable:
self.seekSlider.reloadThumbs()
else:
self.showText("thumbnails disabled")
self.seekSlider.removeThumbs()
self.seekSlider.initStyle()
@pyqtSlot(bool)
def toggleConsole(self, checked: bool) -> None:
if not hasattr(self, "debugonstart"):
self.debugonstart = os.getenv("DEBUG", False)
if checked:
self.mpvWidget.setLogLevel("v")
os.environ["DEBUG"] = "1"
self.parent.console.show()
else:
if not self.debugonstart:
os.environ["DEBUG"] = "0"
self.mpvWidget.setLogLevel("error")
self.parent.console.hide()
self.saveSetting("showConsole", checked)
@pyqtSlot(bool)
def toggleChapters(self, checked: bool) -> None:
self.createChapters = checked
self.saveSetting("chapters", self.createChapters)
self.chaptersButton.setChecked(self.createChapters)
self.showText("chapters {}".format("enabled" if checked else "disabled"))
if checked:
exist = False
for clip in self.clipTimes:
if clip[4] is not None:
exist = True
break
if exist:
chapterswarn = VCMessageBox(
"Restore chapter names",
"Chapter names found in memory",
"Would you like to restore previously set chapter names?",
buttons=QMessageBox.Yes | QMessageBox.No,
parent=self,
)
if chapterswarn.exec_() == QMessageBox.No:
for clip in self.clipTimes:
clip[4] = None
self.renderClipIndex()
@pyqtSlot(bool)
def toggleSmartCut(self, checked: bool) -> None:
self.smartcut = checked
self.saveSetting("smartcut", self.smartcut)
self.smartcutButton.setChecked(self.smartcut)
self.showText("SmartCut {}".format("enabled" if checked else "disabled"))
@pyqtSlot(list)
def addScenes(self, scenes: List[list]) -> None:
if len(scenes):
[
self.clipTimes.append(
[
scene[0],
scene[1],
self.captureImage(self.currentMedia, scene[0]),
"",
None,
]
)
for scene in scenes
if len(scene)
]
self.renderClipIndex()
self.filterProgressBar.done(VCProgressDialog.Accepted)
@pyqtSlot(VideoFilter)
def configFilters(self, name: VideoFilter) -> None:
if name == VideoFilter.BLACKDETECT:
desc = (
"<p>Detect video intervals that are (almost) completely black. Can be useful to detect chapter "
"transitions, commercials, or invalid recordings. You can set the minimum duration of "
"a detected black interval above to adjust the sensitivity.</p>"
"<p><b>WARNING:</b> this can take a long time to complete depending on the length and quality "
"of the source media.</p>"
)
d = VCDoubleInputDialog(
self,
"BLACKDETECT - Filter settings",
"Minimum duration for black scenes:",
self.filter_settings.blackdetect.default_duration,
self.filter_settings.blackdetect.min_duration,
999.9,
1,
0.1,
desc,
"secs",
)
d.buttons.accepted.connect(
lambda: self.startFilters(
"detecting scenes (press ESC to cancel)",
partial(self.videoService.blackdetect, d.value),
d,
)
)
d.setFixedSize(435, d.sizeHint().height())
d.exec_()
@pyqtSlot(str, partial, QDialog)
def startFilters(
self, progress_text: str, filter_func: partial, config_dialog: QDialog
) -> None:
config_dialog.close()
self.parent.lock_gui(True)
self.filterProgress(progress_text)
filter_func()
@pyqtSlot()
def stopFilters(self) -> None:
self.videoService.killFilterProc()
self.parent.lock_gui(False)
def filterProgress(self, msg: str) -> None:
self.filterProgressBar = VCProgressDialog(self, modal=False)
self.filterProgressBar.finished.connect(self.stopFilters)
self.filterProgressBar.setText(msg)
self.filterProgressBar.setMinimumWidth(600)
self.filterProgressBar.show()
@pyqtSlot()
def addExternalClips(self) -> None:
clips, _ = QFileDialog.getOpenFileNames(
parent=self.parent,
caption="Add media files",
filter=self.mediaFilters(),
initialFilter=self.mediaFilters(True),
directory=(
self.lastFolder if os.path.exists(self.lastFolder) else QDir.homePath()
),
options=self.getFileDialogOptions(),
)
if clips is not None and len(clips):
self.lastFolder = QFileInfo(clips[0]).absolutePath()
filesadded = False
cliperrors = list()
for file in clips:
if len(self.clipTimes) > 0:
lastItem = self.clipTimes[len(self.clipTimes) - 1]
file4Test = lastItem[3] if len(lastItem[3]) else self.currentMedia
if self.videoService.testJoin(file4Test, file):
self.clipTimes.append(
[
QTime(0, 0),
self.videoService.duration(file),
self.captureImage(file, QTime(0, 0, second=2), True),
file,
]
)
filesadded = True
else:
cliperrors.append(
(
file,
(
self.videoService.lastError
if len(self.videoService.lastError)
else ""
),
)
)
self.videoService.lastError = ""
else:
self.clipTimes.append(
[
QTime(0, 0),
self.videoService.duration(file),
self.captureImage(file, QTime(0, 0, second=2), True),
file,
]
)
filesadded = True
if len(cliperrors):
detailedmsg = """<p>The file(s) listed were found to be incompatible for inclusion to the clip index as
they failed to join in simple tests used to ensure their compatibility. This is
commonly due to differences in frame size, audio/video formats (codecs), or both.</p>
<p>You can join these files as they currently are using traditional video editors like
OpenShot, Kdenlive, ShotCut, Final Cut Pro or Adobe Premiere. They can re-encode media
files with mixed properties so that they are then matching and able to be joined but
be aware that this can be a time consuming process and almost always results in
degraded video quality.</p>
<p>Re-encoding video is not going to ever be supported by VidCutter because those tools
are already available for you both free and commercially.</p>"""
errordialog = ClipErrorsDialog(cliperrors, self)
errordialog.setDetailedMessage(detailedmsg)
errordialog.show()
if filesadded:
self.showText("media added to index")
self.renderClipIndex()
def hasExternals(self) -> bool:
return True in [len(item[3]) > 0 for item in self.clipTimes]
def clipStart(self) -> None:
starttime = self.delta2QTime(self.seekSlider.value())
self.clipTimes.append(
[starttime, "", self.captureImage(self.currentMedia, starttime), "", None]
)
self.timeCounter.setMinimum(starttime.toString(self.timeformat))
self.frameCounter.lockMinimum()
self.toolbar_start.setDisabled(True)
self.toolbar_end.setEnabled(True)
self.clipindex_add.setDisabled(True)
self.seekSlider.setRestrictValue(self.seekSlider.value(), True)
self.blackdetectAction.setDisabled(True)
self.inCut = True
self.showText("clip started at {}".format(starttime.toString(self.timeformat)))
self.renderClipIndex()
self.cliplist.scrollToBottom()
def clipEnd(self) -> None:
item = self.clipTimes[len(self.clipTimes) - 1]
endtime = self.delta2QTime(self.seekSlider.value())
if endtime.__lt__(item[0]):
QMessageBox.critical(
self.parent,
"Invalid END Time",
"The clip end time must come AFTER it's start time. Please try again.",
)
return
item[1] = endtime
self.toolbar_start.setEnabled(True)
self.toolbar_end.setDisabled(True)
self.clipindex_add.setEnabled(True)
self.timeCounter.setMinimum()
self.seekSlider.setRestrictValue(0, False)
self.blackdetectAction.setEnabled(True)
self.inCut = False
self.showText("clip ends at {}".format(endtime.toString(self.timeformat)))
self.renderClipIndex()
self.cliplist.scrollToBottom()
@pyqtSlot()
@pyqtSlot(bool)
def setProjectDirty(self, dirty: bool = True) -> None:
self.projectDirty = dirty
# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal
@pyqtSlot(QModelIndex, int, int, QModelIndex, int)
def syncClipList(
self,
parent: QModelIndex,
start: int,
end: int,
destination: QModelIndex,
row: int,
) -> None:
index = row - 1 if start < row else row
clip = self.clipTimes.pop(start)
self.clipTimes.insert(index, clip)
if not len(clip[3]):
self.seekSlider.switchRegions(start, index)
self.showText("clip order updated")
self.renderClipIndex()
def renderClipIndex(self) -> None:
self.seekSlider.clearRegions()
self.totalRuntime = 0
externals = self.cliplist.renderClips(self.clipTimes)
if len(self.clipTimes) and not self.inCut and externals != 1:
self.toolbar_save.setEnabled(True)
self.saveProjectAction.setEnabled(True)
if (
self.inCut
or len(self.clipTimes) == 0
or not isinstance(self.clipTimes[0][1], QTime)
):
self.toolbar_save.setEnabled(False)
self.saveProjectAction.setEnabled(False)
self.setRunningTime(
self.delta2QTime(self.totalRuntime).toString(self.runtimeformat)
)
@staticmethod
def delta2QTime(msecs: Union[float, int]) -> QTime:
if isinstance(msecs, float):
msecs = round(msecs * 1000)
t = QTime(0, 0)
return t.addMSecs(msecs)
@staticmethod
def qtime2delta(qtime: QTime) -> float:
return timedelta(
hours=qtime.hour(),
minutes=qtime.minute(),
seconds=qtime.second(),
milliseconds=qtime.msec(),
).total_seconds()
@staticmethod
def delta2String(td: timedelta) -> str:
if td is None or td == timedelta.max:
return ""
else:
return "%f" % (td.days * 86400 + td.seconds + td.microseconds / 1000000.0)
def captureImage(
self, source: str, frametime: QTime, external: bool = False
) -> QPixmap:
return VideoService.captureFrame(
self.settings,
source,
frametime.toString(self.timeformat),
external=external,
)
def saveMedia(self) -> None:
clips = len(self.clipTimes)
source_file, source_ext = os.path.splitext(
self.currentMedia if self.currentMedia is not None else self.clipTimes[0][3]
)
suggestedFilename = "{0}_EDIT{1}".format(source_file, source_ext)
filefilter = "Video files (*{0})".format(source_ext)
if clips > 0:
self.finalFilename, _ = QFileDialog.getSaveFileName(
parent=self.parent,
caption="Save media file",
directory=suggestedFilename,
filter=filefilter,
options=self.getFileDialogOptions(),
)
if self.finalFilename is None or not len(self.finalFilename.strip()):
return
file, ext = os.path.splitext(self.finalFilename)
if len(ext) == 0 and len(source_ext):
self.finalFilename += source_ext
self.lastFolder = QFileInfo(self.finalFilename).absolutePath()
self.toolbar_save.setDisabled(True)
if not os.path.isdir(self.workFolder):
os.mkdir(self.workFolder)
if self.smartcut:
self.seekSlider.showProgress(6 if clips > 1 else 5)
self.parent.lock_gui(True)
self.videoService.smartinit(clips)
self.smartcutter(file, source_file, source_ext)
return
steps = 3 if clips > 1 else 2
self.seekSlider.showProgress(steps)
self.parent.lock_gui(True)
filename, filelist = "", []
for index, clip in enumerate(self.clipTimes):
self.seekSlider.updateProgress(index)
if len(clip[3]):
filelist.append(clip[3])
else:
duration = self.delta2QTime(clip[0].msecsTo(clip[1])).toString(
self.timeformat
)
filename = "{0}_{1}{2}".format(
file, "{0:0>2}".format(index), source_ext
)
if not self.keepClips:
filename = os.path.join(
self.workFolder, os.path.basename(filename)
)
filename = QDir.toNativeSeparators(filename)
filelist.append(filename)
if not self.videoService.cut(
source="{0}{1}".format(source_file, source_ext),
output=filename,
frametime=clip[0].toString(self.timeformat),
duration=duration,
allstreams=True,
):
self.completeOnError(
"<p>Failed to cut media file, assuming media is invalid or corrupt. "
"Attempts are made to work around problematic media files, even "
"when keyframes are incorrectly set or missing.</p><p>If you feel this "
"is a bug in the software then please take the time to report it "
'at our <a href="{}">GitHub Issues page</a> so that it can be fixed.</p>'.format(
vidcutter.__bugreport__
)
)
return
self.joinMedia(filelist)
def smartcutter(self, file: str, source_file: str, source_ext: str) -> None:
self.smartcut_monitor = Munch(clips=[], results=[], externals=0)
for index, clip in enumerate(self.clipTimes):
if len(clip[3]):
self.smartcut_monitor.clips.append(clip[3])
self.smartcut_monitor.externals += 1
if index == len(self.clipTimes):
self.smartmonitor()
else:
filename = "{0}_{1}{2}".format(
file, "{0:0>2}".format(index), source_ext
)
if not self.keepClips:
filename = os.path.join(self.workFolder, os.path.basename(filename))
filename = QDir.toNativeSeparators(filename)
self.smartcut_monitor.clips.append(filename)
self.videoService.smartcut(
index=index,
source="{0}{1}".format(source_file, source_ext),
output=filename,
start=VideoCutter.qtime2delta(clip[0]),
end=VideoCutter.qtime2delta(clip[1]),
allstreams=True,
)
@pyqtSlot(bool, str)
def smartmonitor(self, success: bool = None, outputfile: str = None) -> None:
if success is not None:
if not success:
self.logger.error("SmartCut failed for {}".format(outputfile))
self.smartcut_monitor.results.append(success)
if (
len(self.smartcut_monitor.results)
== len(self.smartcut_monitor.clips) - self.smartcut_monitor.externals
):
if False not in self.smartcut_monitor.results:
self.joinMedia(self.smartcut_monitor.clips)
def joinMedia(self, filelist: list) -> None:
if len(filelist) > 1:
self.seekSlider.updateProgress()
rc = False
chapters = None
if self.createChapters:
chapters = []
[
chapters.append(
clip[4]
if clip[4] is not None
else "Chapter {}".format(index + 1)
)
for index, clip in enumerate(self.clipTimes)
]
if self.videoService.isMPEGcodec(filelist[0]):
self.logger.info("source file is MPEG based so join via MPEG-TS")
rc = self.videoService.mpegtsJoin(
filelist, self.finalFilename, chapters
)
if not rc or QFile(self.finalFilename).size() < 1000:
self.logger.info(
"MPEG-TS based join failed, will retry using standard concat"
)
rc = self.videoService.join(
filelist, self.finalFilename, True, chapters
)
if not rc or QFile(self.finalFilename).size() < 1000:
self.logger.info(
"join resulted in 0 length file, trying again without all stream mapping"
)
self.videoService.join(filelist, self.finalFilename, False, chapters)
if not self.keepClips:
for f in filelist:
clip = self.clipTimes[filelist.index(f)]
if not len(clip[3]) and os.path.isfile(f):
QFile.remove(f)
self.complete(False)
else:
self.complete(True, filelist[-1])
def complete(self, rename: bool = True, filename: str = None) -> None:
if rename and filename is not None:
# noinspection PyCallByClass
QFile.remove(self.finalFilename)
# noinspection PyCallByClass
QFile.rename(filename, self.finalFilename)
self.videoService.finalize(self.finalFilename)
self.seekSlider.updateProgress()
self.toolbar_save.setEnabled(True)
self.parent.lock_gui(False)
self.notify = JobCompleteNotification(
self.finalFilename,
self.sizeof_fmt(int(QFileInfo(self.finalFilename).size())),
self.delta2QTime(self.totalRuntime).toString(self.runtimeformat),
self.getAppIcon(encoded=True),
self,
)
self.notify.closed.connect(self.seekSlider.clearProgress)
self.notify.show()
if self.smartcut:
QTimer.singleShot(1000, self.cleanup)
self.setProjectDirty(False)
@pyqtSlot(str)
def completeOnError(self, errormsg: str) -> None:
if self.smartcut:
self.videoService.smartabort()
QTimer.singleShot(1500, self.cleanup)
self.parent.lock_gui(False)
self.seekSlider.clearProgress()
self.toolbar_save.setEnabled(True)
self.parent.errorHandler(errormsg)
def cleanup(self) -> None:
if hasattr(self.videoService, "smartcut_jobs"):
delattr(self.videoService, "smartcut_jobs")
if hasattr(self, "smartcut_monitor"):
delattr(self, "smartcut_monitor")
self.videoService.smartcutError = False
def saveSetting(self, setting: str, checked: bool) -> None:
self.settings.setValue(setting, "on" if checked else "off")
@pyqtSlot()
def mediaInfo(self) -> None:
if self.mediaAvailable:
if self.videoService.backends.mediainfo is None:
self.logger.error("mediainfo could not be found on the system")
QMessageBox.critical(
self.parent,
"Missing mediainfo utility",
"The <b>mediainfo</b> command could not be found on your system which "
"is required for this feature to work.<br/><br/>Linux users can simply "
"install the <b>mediainfo</b> package using the package manager you use to "
"install software (e.g. apt, pacman, dnf, zypper, etc.)",
)
return
mediainfo = MediaInfo(media=self.currentMedia, parent=self)
mediainfo.show()
@pyqtSlot()
def selectStreams(self) -> None:
if self.mediaAvailable and self.videoService.streams:
if self.hasExternals():
nostreamstext = """
<style>
h2 {{
color: {0};
font-family: "Futura LT", sans-serif;
font-weight: normal;
}}
</style>
<table border="0" cellpadding="6" cellspacing="0" width="350">
<tr>
<td><h2>Cannot configure stream selection</h2></td>
</tr>
<tr>
<td>
Stream selection cannot be configured when external media files
are added to your clip index. Remove all external files from your
clip index and try again.
</td>
</tr>
</table>""".format("#C681D5" if self.theme == "dark" else "#642C68")
nostreams = QMessageBox(
QMessageBox.Critical,
"Stream selection is unavailable",
nostreamstext,
parent=self.parent,
)
nostreams.setStandardButtons(QMessageBox.Ok)
nostreams.exec_()
return
streamSelector = StreamSelector(self.videoService, self)
streamSelector.show()
def saveWarning(self) -> tuple:
if self.mediaAvailable and self.projectDirty and not self.projectSaved:
savewarn = VCMessageBox(
"Warning",
"Unsaved changes found in project",
"Would you like to save your project?",
parent=self,
)
savebutton = savewarn.addButton("Save project", QMessageBox.YesRole)
savewarn.addButton("Do not save", QMessageBox.NoRole)
cancelbutton = savewarn.addButton("Cancel", QMessageBox.RejectRole)
savewarn.exec_()
res = savewarn.clickedButton()
if res == savebutton:
return True, self.saveProject
elif res == cancelbutton:
return True, None
return False, None
@pyqtSlot()
def showKeyRef(self) -> None:
msgtext = '<img src=":/images/{}/shortcuts.png" />'.format(self.theme)
msgbox = QMessageBox(
QMessageBox.NoIcon,
"Keyboard shortcuts",
msgtext,
QMessageBox.Ok,
self,
Qt.Window | Qt.Dialog | Qt.WindowCloseButtonHint,
)
msgbox.setObjectName("shortcuts")
msgbox.setContentsMargins(10, 10, 10, 10)
msgbox.setMinimumWidth(400 if self.parent.scale == "LOW" else 600)
msgbox.exec_()
@pyqtSlot()
def aboutApp(self) -> None:
about = About(self.videoService, self.mpvWidget, self)
about.exec_()
@staticmethod
def getAppIcon(encoded: bool = False):
icon = QIcon.fromTheme(
qApp.applicationName().lower(), QIcon(":/images/vidcutter-small.png")
)
if not encoded:
return icon
iconimg = icon.pixmap(82, 82).toImage()
data = QByteArray()
buffer = QBuffer(data)
buffer.open(QBuffer.WriteOnly)
iconimg.save(buffer, "PNG")
base64enc = str(data.toBase64().data(), "latin1")
icon = "data:vidcutter.png;base64,{}".format(base64enc)
return icon
@staticmethod
def sizeof_fmt(num: float, suffix: chr = "B") -> str:
for unit in ["", "K", "M", "G", "T", "P", "E", "Z"]:
if abs(num) < 1024.0:
return "%3.1f %s%s" % (num, unit, suffix)
num /= 1024.0
return "%.1f %s%s" % (num, "Y", suffix)
@pyqtSlot()
def viewChangelog(self) -> None:
changelog = Changelog(self)
changelog.exec_()
@staticmethod
@pyqtSlot()
def viewLogs() -> None:
QDesktopServices.openUrl(
QUrl.fromLocalFile(logging.getLoggerClass().root.handlers[0].baseFilename)
)
@pyqtSlot()
def toggleFullscreen(self) -> None:
if self.mediaAvailable:
pause = self.mpvWidget.property("pause")
mute = self.mpvWidget.property("mute")
vol = self.mpvWidget.property("volume")
pos = self.seekSlider.value() / 1000
if self.mpvWidget.originalParent is not None:
self.mpvWidget.shutdown()
sip.delete(self.mpvWidget)
del self.mpvWidget
self.mpvWidget = self.getMPV(
parent=self,
file=self.currentMedia,
start=pos,
pause=pause,
mute=mute,
volume=vol,
)
self.videoplayerLayout.insertWidget(0, self.mpvWidget)
self.mpvWidget.originalParent = None
self.parent.show()
elif self.mpvWidget.parentWidget() != 0:
self.parent.hide()
self.mpvWidget.shutdown()
self.videoplayerLayout.removeWidget(self.mpvWidget)
sip.delete(self.mpvWidget)
del self.mpvWidget
self.mpvWidget = self.getMPV(
file=self.currentMedia,
start=pos,
pause=pause,
mute=mute,
volume=vol,
)
self.mpvWidget.originalParent = self
self.mpvWidget.setGeometry(qApp.desktop().screenGeometry(self))
self.mpvWidget.showFullScreen()
def toggleOSD(self, checked: bool) -> None:
self.showText(
"on-screen display {}".format("enabled" if checked else "disabled"),
override=True,
)
self.saveSetting("enableOSD", checked)
@property
def _osdfont(self) -> str:
fontdb = QFontDatabase()
return (
"DejaVu Sans"
if "DejaVu Sans" in fontdb.families(QFontDatabase.Latin)
else "Noto Sans"
)
def doPass(self) -> None:
pass
def keyPressEvent(self, event: QKeyEvent) -> None:
if (
event.key() in {Qt.Key_Q, Qt.Key_W}
and event.modifiers() == Qt.ControlModifier
):
self.parent.close()
return
if self.mediaAvailable:
if event.key() == Qt.Key_Space:
self.playMedia()
return
if event.key() == Qt.Key_Escape and self.isFullScreen():
self.toggleFullscreen()
return
if event.key() == Qt.Key_F:
self.toggleFullscreen()
return
if event.key() == Qt.Key_Home:
self.setPosition(self.seekSlider.minimum())
return
if event.key() == Qt.Key_End:
self.setPosition(self.seekSlider.maximum())
return
if event.key() == Qt.Key_Left:
self.mpvWidget.frameBackStep()
self.setPlayButton(False)
return
if event.key() == Qt.Key_Down:
if qApp.queryKeyboardModifiers() == Qt.ShiftModifier:
self.mpvWidget.seek(-self.level2Seek, "relative+exact")
else:
self.mpvWidget.seek(-self.level1Seek, "relative+exact")
return
if event.key() == Qt.Key_Right:
self.mpvWidget.frameStep()
self.setPlayButton(False)
return
if event.key() == Qt.Key_Up:
if qApp.queryKeyboardModifiers() == Qt.ShiftModifier:
self.mpvWidget.seek(self.level2Seek, "relative+exact")
else:
self.mpvWidget.seek(self.level1Seek, "relative+exact")
return
if event.key() in {Qt.Key_Return, Qt.Key_Enter} and (
not self.timeCounter.hasFocus() and not self.frameCounter.hasFocus()
):
if self.toolbar_start.isEnabled():
self.clipStart()
elif self.toolbar_end.isEnabled():
self.clipEnd()
return
super(VideoCutter, self).keyPressEvent(event)
def showEvent(self, event: QShowEvent) -> None:
if hasattr(self, "filterProgressBar") and self.filterProgressBar.isVisible():
self.filterProgressBar.update()
super(VideoCutter, self).showEvent(event)
|
photocollage | render | # Copyright (C) 2014 Adrien Vergé
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import random
import time
from threading import Thread
import PIL.Image
import PIL.ImageDraw
import PIL.ImageFile
from photocollage.collage import Photo
QUALITY_SKEL = 0
QUALITY_FAST = 1
QUALITY_BEST = 2
# Try to continue even if the input file is corrupted.
# See issue at https://github.com/adrienverge/PhotoCollage/issues/65
PIL.ImageFile.LOAD_TRUNCATED_IMAGES = True
class PIL_SUPPORTED_EXTS:
"""File extensions supported by PIL
Compiled from:
- http://pillow.readthedocs.org/en/2.3.0/handbook/image-file-formats.html
- https://github.com/python-imaging/Pillow/blob/master/PIL/*ImagePlugin.py
"""
RW = {
"BMP": ("bmp",),
# "EPS": ("ps", "eps",), # doesn't seem to work
"GIF": ("gif",),
"IM": ("im",),
"JPEG": (
"jfif",
"jpe",
"jpg",
"jpeg",
),
"MSP": ("msp",),
"PCX": ("pcx",),
"PNG": ("png",),
"PPM": (
"pbm",
"pgm",
"ppm",
),
"TGA": ("tga",),
"TIFF": (
"tif",
"tiff",
),
"WebP": ("webp",),
"XBM": ("xbm",),
}
RO = {
"CUR": ("cur",),
"DCX": ("dcx",),
"FLI": (
"fli",
"flc",
),
"FPX": ("fpx",),
"GBR": ("gbr",),
"ICO": ("ico",),
"IPTC/NAA": ("iim",),
"PCD": ("pcd",),
"PSD": ("psd",),
"SGI": (
"bw",
"rgb",
"rgba",
"sgi",
),
"XPM": ("xpm",),
}
WO = {
# "PALM": ("palm",), # doesn't seem to work
# "PDF": ("pdf",), # doesn't seem to work
}
def random_color():
r = random.randrange(256)
g = random.randrange(256)
b = random.randrange(256)
if r + g + b > 0.7 * 3 * 256:
r -= 50
g -= 50
b -= 50
return (r, g, b)
class BadPhoto(Exception):
def __init__(self, photoname):
self.photoname = photoname
def build_photolist(filelist):
ret = []
for name in filelist:
try:
img = PIL.Image.open(name)
except OSError:
raise BadPhoto(name)
w, h = img.size
orientation = 0
try:
exif = img._getexif()
if 274 in exif: # orientation tag
orientation = exif[274]
if orientation == 6 or orientation == 8:
w, h = h, w
except Exception:
pass
ret.append(Photo(name, w, h, orientation))
return ret
cache = {}
class RenderingTask(Thread):
"""Execution thread to do the actual poster rendering
Image computation is a heavy task, that can take several seconds. During
this, the program might be unresponding. To avoid this, rendering is done
is a separated thread.
"""
def __init__(
self,
page,
border_width=0.01,
border_color=(0, 0, 0),
quality=QUALITY_FAST,
output_file=None,
on_update=None,
on_complete=None,
on_fail=None,
):
super().__init__()
self.page = page
self.border_width = border_width
self.border_color = border_color
self.quality = quality
self.output_file = output_file
self.on_update = on_update
self.on_complete = on_complete
self.on_fail = on_fail
self.canceled = False
def abort(self):
self.canceled = True
def draw_skeleton(self, canvas):
for col in self.page.cols:
for c in col.cells:
if c.is_extension():
continue
color = random_color()
x, y, w, h = c.content_coords()
xy = (x, y)
xY = (x, y + h - 1)
Xy = (x + w - 1, y)
XY = (x + w - 1, y + h - 1)
draw = PIL.ImageDraw.Draw(canvas)
draw.line(xy + Xy, fill=color)
draw.line(xy + xY, fill=color)
draw.line(xY + XY, fill=color)
draw.line(Xy + XY, fill=color)
draw.line(xy + XY, fill=color)
draw.line(xY + Xy, fill=color)
return canvas
def draw_borders(self, canvas):
if self.border_width == 0:
return
W = self.page.w - 1
H = self.page.h - 1
border = self.border_width - 1
color = self.border_color
draw = PIL.ImageDraw.Draw(canvas)
draw.rectangle((0, 0) + (border, H), color)
draw.rectangle((W - border, 0) + (W, H), color)
draw.rectangle((0, 0) + (W, border), color)
draw.rectangle((0, H - border) + (W, H), color)
for col in self.page.cols:
# Draw horizontal borders
for c in col.cells[1:]:
xy = (col.x, c.y - border / 2)
XY = (col.x + col.w, c.y + border / 2)
draw.rectangle(xy + XY, color)
# Draw vertical borders
if col.x > 0:
for c in col.cells:
if not c.is_extension():
xy = (col.x - border / 2, c.y)
XY = (col.x + border / 2, c.y + c.h)
draw.rectangle(xy + XY, color)
return canvas
def resize_photo(self, cell, use_cache=False):
# If a thumbnail is already in cache, let's use it. But only if it is
# bigger than what we need, because we don't want to lose quality.
if (
use_cache
and cell.photo.filename in cache
and cache[cell.photo.filename].size[0] >= int(round(cell.w))
and cache[cell.photo.filename].size[1] >= int(round(cell.h))
):
img = cache[cell.photo.filename].copy()
else:
img = PIL.Image.open(cell.photo.filename)
# Rotate image is EXIF says so
if cell.photo.orientation == 3:
img = img.rotate(180, expand=True)
elif cell.photo.orientation == 6:
img = img.rotate(270, expand=True)
elif cell.photo.orientation == 8:
img = img.rotate(90, expand=True)
if self.quality == QUALITY_FAST:
method = PIL.Image.NEAREST
else:
method = PIL.Image.ANTIALIAS
shape = img.size[0] * cell.h - img.size[1] * cell.w
if shape > 0: # image is too thick
img = img.resize(
(int(round(cell.h * img.size[0] / img.size[1])), int(round(cell.h))),
method,
)
elif shape < 0: # image is too tall
img = img.resize(
(int(round(cell.w)), int(round(cell.w * img.size[1] / img.size[0]))),
method,
)
else:
img = img.resize((int(round(cell.w)), int(round(cell.h))), method)
# Save this new image to cache (if it is larger than the previous one)
if use_cache and (
cell.photo.filename not in cache
or cache[cell.photo.filename].size[0] < img.size[0]
):
cache[cell.photo.filename] = img
if shape > 0: # image is too thick
width_to_crop = img.size[0] - cell.w
img = img.crop(
(
int(round(width_to_crop * cell.photo.offset_w)),
0,
int(round(img.size[0] - width_to_crop * (1 - cell.photo.offset_w))),
int(round(cell.h)),
)
)
elif shape < 0: # image is too tall
height_to_crop = img.size[1] - cell.h
img = img.crop(
(
0,
int(round(height_to_crop * cell.photo.offset_h)),
int(round(cell.w)),
int(
round(img.size[1] - height_to_crop * (1 - cell.photo.offset_h))
),
)
)
return img
def paste_photo(self, canvas, cell, img):
canvas.paste(img, (int(round(cell.x)), int(round(cell.y))))
return canvas
def run(self):
try:
canvas = PIL.Image.new("RGB", (int(self.page.w), int(self.page.h)), "white")
self.draw_skeleton(canvas)
self.draw_borders(canvas)
if self.quality != QUALITY_SKEL:
n = sum(
[
len([cell for cell in col.cells if not cell.is_extension()])
for col in self.page.cols
]
)
i = 0.0
if self.on_update:
self.on_update(canvas, 0.0)
last_update = time.time()
for col in self.page.cols:
for c in col.cells:
if self.canceled: # someone clicked "abort"
return
if c.is_extension():
continue
img = self.resize_photo(c, use_cache=True)
self.paste_photo(canvas, c, img)
# Only needed for interactive rendering
if self.on_update:
self.draw_borders(canvas)
i += 1
now = time.time()
if self.on_update and now > last_update + 0.1:
self.on_update(canvas, i / n)
last_update = now
self.draw_borders(canvas)
if self.output_file:
canvas.save(self.output_file)
if self.on_complete:
self.on_complete(canvas)
except Exception as e:
if self.on_fail:
self.on_fail(e)
|
draftviewproviders | view_fillet | # ***************************************************************************
# * Copyright (c) 2020 Eliud Cabrera Castillo <e.cabrera-castillo@tum.de> *
# * *
# * This program is free software; you can redistribute it and/or modify *
# * it under the terms of the GNU Lesser General Public License (LGPL) *
# * as published by the Free Software Foundation; either version 2 of *
# * the License, or (at your option) any later version. *
# * for detail see the LICENCE text file. *
# * *
# * This program is distributed in the hope that it will be useful, *
# * but WITHOUT ANY WARRANTY; without even the implied warranty of *
# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
# * GNU Library General Public License for more details. *
# * *
# * You should have received a copy of the GNU Library General Public *
# * License along with this program; if not, write to the Free Software *
# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
# * USA *
# * *
# ***************************************************************************
"""Provides the viewprovider code for the Fillet object.
At the moment this view provider subclasses the Wire view provider,
and behaves the same as it. In the future this could change
if another behavior is desired.
"""
## @package view_fillet
# \ingroup draftviewproviders
# \brief Provides the viewprovider code for the Fillet object.
## \addtogroup draftviewproviders
# @{
from draftviewproviders.view_wire import ViewProviderWire
class ViewProviderFillet(ViewProviderWire):
"""The view provider for the Fillet object."""
def __init__(self, vobj):
super(ViewProviderFillet, self).__init__(vobj)
def doubleClicked(self, vobj):
# See setEdit in ViewProviderDraft.
import FreeCADGui as Gui
Gui.runCommand("Std_TransformManip")
return True
## @}
|
decrypters | GofileIoFolder | # -*- coding: utf-8 -*-
import base64
import json
from pyload.core.network.http.exceptions import BadHeader
from ..base.decrypter import BaseDecrypter
class GofileIoFolder(BaseDecrypter):
__name__ = "GofileIoFolder"
__type__ = "decrypter"
__version__ = "0.02"
__status__ = "testing"
__pattern__ = r"https?://(?:www\.)?gofile\.io/d/(?P<ID>\w+)"
__config__ = [
("enabled", "bool", "Activated", True),
("use_premium", "bool", "Use premium account if available", True),
(
"folder_per_package",
"Default;Yes;No",
"Create folder for each package",
"Default",
),
("max_wait", "int", "Reconnect if waiting time is greater than minutes", 10),
]
__description__ = """Gofile.io decrypter plugin"""
__license__ = "GPLv3"
__authors__ = [("GammaC0de", "nitzo2001[AT]yahoo[DOT]com")]
URL_REPLACEMENTS = [("http://", "https://")]
API_URL = "https://api.gofile.io/"
def api_request(self, method, **kwargs):
try:
json_data = self.load(self.API_URL + method, get=kwargs)
except BadHeader as exc:
json_data = exc.content
return json.loads(json_data)
def decrypt(self, pyfile):
api_data = self.api_request("createAccount")
if api_data["status"] != "ok":
self.fail(
self._("createAccount API failed | {}").format(api_data["status"])
)
token = api_data["data"]["token"]
api_data = self.api_request(
"getContent",
contentId=self.info["pattern"]["ID"],
token=token,
websiteToken=12345,
)
status = api_data["status"]
if status == "ok":
pack_links = [
"https://gofile.io/dl?q={}".format(
base64.b64encode(
json.dumps(
{
"t": token,
"u": file_data["link"],
"n": file_data["name"],
"s": file_data["size"],
"m": file_data["md5"],
}
).encode("utf-8")
).decode("utf-8")
)
for file_data in api_data["data"]["contents"].values()
if file_data["type"] == "file"
]
if pack_links:
self.packages.append(
(pyfile.package().name, pack_links, pyfile.package().folder)
)
else:
self.offline()
elif status == "error-notFound":
self.offline()
elif status == "error-notPremium":
self.fail(self._("File can be downloaded by premium users only"))
else:
self.fail(self._("getContent API failed | {}").format(status))
|
frescobaldi-app | recentfiles | # This file is part of the Frescobaldi project, http://www.frescobaldi.org/
#
# Copyright (c) 2008 - 2014 by Wilbert Berendsen
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
# See http://www.gnu.org/licenses/ for more information.
"""
Recent files handling.
"""
import os
import app
import qsettings
from PyQt5.QtCore import QSettings, QUrl
__all__ = ["urls", "add", "remove"]
_recentfiles = None
# the maximum number of items remembered
MAXLEN = 10
def load():
global _recentfiles
if _recentfiles is not None:
return
_recentfiles = []
urls = qsettings.get_url_list(QSettings(), "recent_files")
for url in urls:
if os.access(url.toLocalFile(), os.R_OK):
_recentfiles.append(url)
del _recentfiles[MAXLEN:]
app.aboutToQuit.connect(save)
def save():
QSettings().setValue("recent_files", _recentfiles)
def urls():
load()
return _recentfiles
def add(url):
load()
if url in _recentfiles:
_recentfiles.remove(url)
_recentfiles.insert(0, url)
del _recentfiles[MAXLEN:]
def remove(url):
load()
if url in _recentfiles:
_recentfiles.remove(url)
|
prefs | prefs_fonts | # -*- coding: utf-8 -*-
#
# Copyright (C) 2016 by Ihor E. Novikov
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
import wal
from generic import PrefPanel
from sk1 import _, config
from sk1.resources import icons
class FontPrefs(PrefPanel):
pid = "Fonts"
name = _("Fonts")
title = _("Font preview preferences")
icon_id = icons.PD_PREFS_FONTS
filler = None
fontsize = None
fontcolor = None
selcolor = None
pwidth = None
def __init__(self, app, dlg, *_args):
PrefPanel.__init__(self, app, dlg)
def build(self):
grid = wal.GridPanel(self, rows=5, cols=2, hgap=5, vgap=5)
grid.add_growable_col(1)
grid.pack(wal.Label(grid, _("Placeholder text:")))
self.filler = wal.Entry(grid, config.font_preview_text)
grid.pack(self.filler, fill=True)
grid.pack(wal.Label(grid, _("Font size:")))
self.fontsize = wal.IntSpin(grid, config.font_preview_size, (5, 50))
grid.pack(self.fontsize)
grid.pack(wal.Label(grid, _("Font color:")))
self.fontcolor = wal.ColorButton(grid, config.font_preview_color)
grid.pack(self.fontcolor)
grid.pack(wal.Label(grid, _("Selection color:")))
color = self.fontcolor.val255_to_dec(wal.UI_COLORS["selected_text_bg"])
self.selcolor = wal.ColorButton(grid, color)
grid.pack(self.selcolor)
grid.pack(wal.Label(grid, _("Preview width:")))
self.pwidth = wal.IntSpin(grid, config.font_preview_width, (100, 1000))
grid.pack(self.pwidth)
self.pack(grid, align_center=False, fill=True, padding=5)
self.built = True
def apply_changes(self):
config.font_preview_text = self.filler.get_value()
config.font_preview_size = self.fontsize.get_value()
config.font_preview_color = self.fontcolor.get_value()
color = self.selcolor.get_value255()
config.selected_text_bg = color
if not color == wal.UI_COLORS["selected_text_bg"]:
wal.UI_COLORS["selected_text_bg"] = self.selcolor.get_value255()
config.font_preview_width = self.pwidth.get_value()
def restore_defaults(self):
defaults = config.get_defaults()
self.filler.set_value(defaults["font_preview_text"])
self.fontsize.set_value(defaults["font_preview_size"])
self.fontcolor.set_value(defaults["font_preview_color"])
self.selcolor.set_value255(wal.get_sel_bg())
self.pwidth.set_value(defaults["font_preview_width"])
|
profiles | extension | """
ExtensionItem -- Graphical representation of an association.
"""
from gaphor import UML
from gaphor.diagram.presentation import LinePresentation, Named
from gaphor.diagram.shapes import Box, Text
from gaphor.diagram.support import represents
from gaphor.UML.recipes import stereotypes_str
@represents(UML.Extension)
class ExtensionItem(Named, LinePresentation):
"""ExtensionItem represents associations.
An ExtensionItem has two ExtensionEnd items. Each ExtensionEnd item
represents a Property (with Property.association == my association).
"""
def __init__(self, diagram, id=None):
super().__init__(
diagram,
id,
shape_middle=Box(
Text(
text=lambda: stereotypes_str(self.subject),
),
Text(text=lambda: self.subject.name or ""),
),
)
self.watch("subject[NamedElement].name")
self.watch("subject.appliedStereotype.classifier.name")
def draw_head(self, context):
cr = context.cairo
cr.move_to(0, 0)
cr.line_to(15, -10)
cr.line_to(15, 10)
cr.line_to(0, 0)
cr.fill_preserve()
cr.move_to(15, 0)
|
archiver | serve_cmd | import argparse
from ..constants import * # NOQA
from ..helpers import EXIT_SUCCESS, parse_storage_quota
from ..logger import create_logger
from ..remote import RepositoryServer
from ._common import Highlander
logger = create_logger()
class ServeMixIn:
def do_serve(self, args):
"""Start in server mode. This command is usually not used manually."""
RepositoryServer(
restrict_to_paths=args.restrict_to_paths,
restrict_to_repositories=args.restrict_to_repositories,
append_only=args.append_only,
storage_quota=args.storage_quota,
use_socket=args.use_socket,
).serve()
return EXIT_SUCCESS
def build_parser_serve(self, subparsers, common_parser, mid_common_parser):
from ._common import process_epilog
serve_epilog = process_epilog(
"""
This command starts a repository server process.
borg serve can currently support:
- Getting automatically started via ssh when the borg client uses a ssh://...
remote repository. In this mode, `borg serve` will live until that ssh connection
gets terminated.
- Getting started by some other means (not by the borg client) as a long-running socket
server to be used for borg clients using a socket://... repository (see the `--socket`
option if you do not want to use the default path for the socket and pid file).
"""
)
subparser = subparsers.add_parser(
"serve",
parents=[common_parser],
add_help=False,
description=self.do_serve.__doc__,
epilog=serve_epilog,
formatter_class=argparse.RawDescriptionHelpFormatter,
help="start repository server process",
)
subparser.set_defaults(func=self.do_serve)
subparser.add_argument(
"--restrict-to-path",
metavar="PATH",
dest="restrict_to_paths",
action="append",
help="restrict repository access to PATH. "
"Can be specified multiple times to allow the client access to several directories. "
"Access to all sub-directories is granted implicitly; PATH doesn't need to point directly to a repository.",
)
subparser.add_argument(
"--restrict-to-repository",
metavar="PATH",
dest="restrict_to_repositories",
action="append",
help="restrict repository access. Only the repository located at PATH "
"(no sub-directories are considered) is accessible. "
"Can be specified multiple times to allow the client access to several repositories. "
"Unlike ``--restrict-to-path`` sub-directories are not accessible; "
"PATH needs to point directly at a repository location. "
"PATH may be an empty directory or the last element of PATH may not exist, in which case "
"the client may initialize a repository there.",
)
subparser.add_argument(
"--append-only",
dest="append_only",
action="store_true",
help="only allow appending to repository segment files. Note that this only "
"affects the low level structure of the repository, and running `delete` "
"or `prune` will still be allowed. See :ref:`append_only_mode` in Additional "
"Notes for more details.",
)
subparser.add_argument(
"--storage-quota",
metavar="QUOTA",
dest="storage_quota",
type=parse_storage_quota,
default=None,
action=Highlander,
help="Override storage quota of the repository (e.g. 5G, 1.5T). "
"When a new repository is initialized, sets the storage quota on the new "
"repository as well. Default: no quota.",
)
|
models | trylater | # The contents of this file are subject to the Common Public Attribution
# License Version 1.0. (the "License"); you may not use this file except in
# compliance with the License. You may obtain a copy of the License at
# http://code.reddit.com/LICENSE. The License is based on the Mozilla Public
# License Version 1.1, but Sections 14 and 15 have been added to cover use of
# software over a computer network and provide for limited attribution for the
# Original Developer. In addition, Exhibit A has been modified to be consistent
# with Exhibit B.
#
# Software distributed under the License is distributed on an "AS IS" basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
# the specific language governing rights and limitations under the License.
#
# The Original Code is reddit.
#
# The Original Developer is the Initial Developer. The Initial Developer of
# the Original Code is reddit Inc.
#
# All portions of the code written by reddit are Copyright (c) 2006-2015 reddit
# Inc. All Rights Reserved.
###############################################################################
"""A delayed execution system.
The ``trylater`` module provides tools for performing an action at a set time
in the future. To use it, you must do two things.
First, make a scheduling call::
from datetime import timedelta
from r2.models.trylater import TryLater
def make_breakfast(spam):
breakfast = cook(spam)
later = timedelta(minutes=45)
# The storage layer only likes strings.
data = json.dumps(breakfast)
TryLater.schedule('wash_dishes', data, later)
Then, write the delayed code and decorate it with a hook, using the same
identifier as you used when you scheduled it::
from r2.lib import hooks
trylater_hooks = hooks.HookRegistrar()
@trylater_hooks.on('trylater.wash_dishes')
def on_dish_washing(data):
# data is an ordered dictionary of timeuuid -> data pairs.
for datum in data.values():
meal = json.loads(datum)
for dish in meal.dishes:
dish.wash()
Note: once you've scheduled a ``TryLater`` task, there's no stopping it! If
you might need to cancel your jobs later, use ``TryLaterBySubject``, which uses
almost the exact same semantics, but has a useful ``unschedule`` method.
"""
import uuid
from collections import OrderedDict
from datetime import datetime, timedelta
from pycassa.system_manager import TIME_UUID_TYPE, UTF8_TYPE
from pycassa.util import convert_uuid_to_time
from pylons import app_globals as g
from r2.lib.db import tdb_cassandra
from r2.lib.utils import tup
class TryLater(tdb_cassandra.View):
_use_db = True
_read_consistency_level = tdb_cassandra.CL.QUORUM
_write_consistency_level = tdb_cassandra.CL.QUORUM
_compare_with = TIME_UUID_TYPE
@classmethod
def process_ready_items(cls, rowkey, ready_fn):
cutoff = datetime.now(g.tz)
columns = cls._cf.xget(rowkey, include_timestamp=True)
ready_items = OrderedDict()
ready_timestamps = []
unripe_timestamps = []
for ready_time_uuid, (data, timestamp) in columns:
ready_time = convert_uuid_to_time(ready_time_uuid)
ready_datetime = datetime.fromtimestamp(ready_time, tz=g.tz)
if ready_datetime <= cutoff:
ready_items[ready_time_uuid] = data
ready_timestamps.append(timestamp)
else:
unripe_timestamps.append(timestamp)
g.stats.simple_event(
"trylater.{system}.ready".format(system=rowkey),
delta=len(ready_items),
)
g.stats.simple_event(
"trylater.{system}.pending".format(system=rowkey),
delta=len(unripe_timestamps),
)
if not ready_items:
return
try:
ready_fn(ready_items)
except:
g.stats.simple_event(
"trylater.{system}.failed".format(system=rowkey),
)
cls.cleanup(rowkey, ready_items, ready_timestamps, unripe_timestamps)
@classmethod
def cleanup(cls, rowkey, ready_items, ready_timestamps, unripe_timestamps):
"""Remove ALL ready items from the C* row"""
if not unripe_timestamps or min(unripe_timestamps) > max(ready_timestamps):
# do a row/timestamp delete to avoid generating column
# tombstones
cls._cf.remove(rowkey, timestamp=max(ready_timestamps))
g.stats.simple_event(
"trylater.{system}.row_delete".format(system=rowkey),
delta=len(ready_items),
)
else:
# the columns weren't created with a fixed delay and there are some
# unripe items with older (lower) timestamps than the items we want
# to delete. fallback to deleting specific columns.
cls._cf.remove(rowkey, ready_items.keys())
g.stats.simple_event(
"trylater.{system}.column_delete".format(system=rowkey),
delta=len(ready_items),
)
@classmethod
def run(cls):
"""Run all ready items through their processing hook."""
from r2.lib import amqp
from r2.lib.hooks import all_hooks
for hook_name, hook in all_hooks().items():
if hook_name.startswith("trylater."):
rowkey = hook_name[len("trylater.") :]
def ready_fn(ready_items):
return hook.call(data=ready_items)
g.log.info("Trying %s", rowkey)
cls.process_ready_items(rowkey, ready_fn)
amqp.worker.join()
g.stats.flush()
@classmethod
def search(cls, rowkey, when):
if isinstance(when, uuid.UUID):
when = convert_uuid_to_time(when)
try:
return cls._cf.get(rowkey, column_start=when, column_finish=when)
except tdb_cassandra.NotFoundException:
return {}
@classmethod
def schedule(cls, system, data, delay=None):
"""Schedule code for later execution.
system: an string identifying the hook to be executed
data: passed to the hook as an argument
delay: (optional) a datetime.timedelta indicating the desired
execution time
"""
if delay is None:
delay = timedelta(minutes=60)
key = datetime.now(g.tz) + delay
scheduled = {key: data}
cls._set_values(system, scheduled)
return scheduled
@classmethod
def unschedule(cls, rowkey, column_keys):
column_keys = tup(column_keys)
return cls._cf.remove(rowkey, column_keys)
class TryLaterBySubject(tdb_cassandra.View):
_use_db = True
_read_consistency_level = tdb_cassandra.CL.QUORUM
_write_consistency_level = tdb_cassandra.CL.QUORUM
_compare_with = UTF8_TYPE
_extra_schema_creation_args = {
"key_validation_class": UTF8_TYPE,
"default_validation_class": TIME_UUID_TYPE,
}
_value_type = "date"
@classmethod
def schedule(cls, system, subject, data, delay, trylater_rowkey=None):
if trylater_rowkey is None:
trylater_rowkey = system
scheduled = TryLater.schedule(trylater_rowkey, data, delay)
when = scheduled.keys()[0]
# TTL 10 minutes after the TryLater runs just in case TryLater
# is running late.
ttl = (delay + timedelta(minutes=10)).total_seconds()
coldict = {subject: when}
cls._set_values(system, coldict, ttl=ttl)
return scheduled
@classmethod
def search(cls, rowkey, subjects=None):
try:
if subjects:
subjects = tup(subjects)
return cls._cf.get(rowkey, subjects)
else:
return cls._cf.get(rowkey)
except tdb_cassandra.NotFoundException:
return {}
@classmethod
def unschedule(cls, rowkey, colkey, schedule_rowkey):
colkey = tup(colkey)
victims = cls.search(rowkey, colkey)
for uu in victims.itervalues():
keys = TryLater.search(schedule_rowkey, uu).keys()
TryLater.unschedule(schedule_rowkey, keys)
cls._cf.remove(rowkey, colkey)
|
rights | ingest_urls | # This file is part of Archivematica.
#
# Copyright 2010-2013 Artefactual Systems Inc. <http://artefactual.com>
#
# Archivematica is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Archivematica is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Archivematica. If not, see <http://www.gnu.org/licenses/>.
from components.rights import views
from django.conf.urls import url
app_name = "rights_ingest"
urlpatterns = [
url(r"^$", views.ingest_rights_list, name="index"),
url(r"^add/$", views.ingest_rights_edit, name="add"),
url(r"^delete/(?P<id>\d+)/$", views.ingest_rights_delete),
url(
r"^grants/(?P<id>\d+)/delete/$",
views.ingest_rights_grant_delete,
name="grant_delete",
),
url(r"^grants/(?P<id>\d+)/$", views.ingest_rights_grants_edit, name="grants_edit"),
url(r"^(?P<id>\d+)/$", views.ingest_rights_edit, name="edit"),
]
|
PyObjCTest | test_list_proxy | """
Minimal tests for sequence proxies
NOTE: this file is very, very incomplete and just tests copying at the moment.
"""
import sys
import objc
from PyObjCTest.fnd import NSArray, NSMutableArray, NSNull, NSObject, NSPredicate
from PyObjCTest.pythonset import OC_TestSet
from PyObjCTools.TestSupport import *
OC_PythonArray = objc.lookUpClass("OC_PythonArray")
class BasicSequenceTests:
# Tests for sets that don't try to mutate the set.
# Shared between tests for set() and frozenset()
seqClass = None
def testProxyClass(self):
# Ensure that the right class is used to proxy sets
self.assertIs(OC_TestSet.classOf_(self.seqClass()), OC_PythonArray)
def testMutableCopy(self):
s = self.seqClass(range(20))
o = OC_TestSet.set_mutableCopyWithZone_(s, None)
self.assertEqual(list(s), o)
self.assertIsNot(s, o)
self.assertIsInstance(o, list)
s = self.seqClass()
o = OC_TestSet.set_mutableCopyWithZone_(s, None)
self.assertEqual(list(s), o)
self.assertIsNot(s, o)
self.assertIsInstance(o, list)
class TestImmutableSequence(TestCase, BasicSequenceTests):
seqClass = tuple
def testCopy(self):
s = self.seqClass()
o = OC_TestSet.set_copyWithZone_(s, None)
self.assertEqual(s, o)
s = self.seqClass(range(20))
o = OC_TestSet.set_copyWithZone_(s, None)
self.assertEqual(s, o)
def testNotMutable(self):
# Ensure that a frozenset cannot be mutated
o = self.seqClass([1, 2, 3])
self.assertRaises((TypeError, AttributeError), OC_TestSet.set_addObject_, o, 4)
class TestMutableSequence(TestCase, BasicSequenceTests):
seqClass = list
def testCopy(self):
s = self.seqClass()
o = OC_TestSet.set_copyWithZone_(s, None)
self.assertEqual(s, o)
self.assertIsNot(s, o)
s = self.seqClass(range(20))
o = OC_TestSet.set_copyWithZone_(s, None)
self.assertEqual(s, o)
self.assertIsNot(s, o)
if __name__ == "__main__":
main()
|
lib | history | #!/usr/bin/env python3
"""
This file is part of the Stargate project, Copyright Stargate Team
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 3 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
"""
import difflib
import os
import time
from sglib.lib import util
class history_file:
def __init__(self, a_folder, a_file_name, a_text_new, a_text_old, a_existed):
self.folder = str(a_folder)
self.file_name = str(a_file_name)
self.new_text = str(a_text_new)
self.old_text = str(a_text_old)
self.existed = int(a_existed)
def __str__(self):
"""Generate a human-readable summary of the changes"""
f_file_name = os.path.join(self.folder, self.file_name)
f_result = "\n\n{}, existed: {}\n".format(f_file_name, self.existed)
for f_line in difflib.unified_diff(
self.old_text.split("\n"),
self.new_text.split("\n"),
f_file_name,
f_file_name,
):
f_result += f_line + "\n"
return f_result
class history_commit:
def __init__(self, a_files, a_message):
self.files = a_files
self.message = a_message
self.timestamp = int(time.time())
def undo(self, a_project_folder):
for f_file in self.files:
f_full_path = os.path.join(
a_project_folder, f_file.folder, f_file.file_name
)
if f_file.existed == 0:
os.remove(f_full_path)
else:
util.write_file_text(f_full_path, f_file.old_text)
def redo(self, a_project_folder):
for f_file in self.files:
f_full_path = os.path.join(
a_project_folder, f_file.folder, f_file.file_name
)
util.write_file_text(f_full_path, f_file.new_text)
|
extractor | shahid | # coding: utf-8
from __future__ import unicode_literals
import json
import math
import re
from ..compat import compat_HTTPError
from ..utils import (
ExtractorError,
InAdvancePagedList,
clean_html,
int_or_none,
parse_iso8601,
str_or_none,
urlencode_postdata,
)
from .aws import AWSIE
class ShahidBaseIE(AWSIE):
_AWS_PROXY_HOST = "api2.shahid.net"
_AWS_API_KEY = "2RRtuMHx95aNI1Kvtn2rChEuwsCogUd4samGPjLh"
_VALID_URL_BASE = r"https?://shahid\.mbc\.net/[a-z]{2}/"
def _handle_error(self, e):
fail_data = self._parse_json(e.cause.read().decode("utf-8"), None, fatal=False)
if fail_data:
faults = fail_data.get("faults", [])
faults_message = ", ".join(
[
clean_html(fault["userMessage"])
for fault in faults
if fault.get("userMessage")
]
)
if faults_message:
raise ExtractorError(faults_message, expected=True)
def _call_api(self, path, video_id, request=None):
query = {}
if request:
query["request"] = json.dumps(request)
try:
return self._aws_execute_api(
{
"uri": "/proxy/v2/" + path,
"access_key": "AKIAI6X4TYCIXM2B7MUQ",
"secret_key": "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",
},
video_id,
query,
)
except ExtractorError as e:
if isinstance(e.cause, compat_HTTPError):
self._handle_error(e)
raise
class ShahidIE(ShahidBaseIE):
_NETRC_MACHINE = "shahid"
_VALID_URL = (
ShahidBaseIE._VALID_URL_BASE
+ r"(?:serie|show|movie)s/[^/]+/(?P<type>episode|clip|movie)-(?P<id>\d+)"
)
_TESTS = [
{
"url": "https://shahid.mbc.net/ar/shows/%D9%85%D8%AA%D8%AD%D9%81-%D8%A7%D9%84%D8%AF%D8%AD%D9%8A%D8%AD-%D8%A7%D9%84%D9%85%D9%88%D8%B3%D9%85-1-%D9%83%D9%84%D9%8A%D8%A8-1/clip-816924",
"info_dict": {
"id": "816924",
"ext": "mp4",
"title": "متحف الدحيح الموسم 1 كليب 1",
"timestamp": 1602806400,
"upload_date": "20201016",
"description": "برومو",
"duration": 22,
"categories": ["كوميديا"],
},
"params": {
# m3u8 download
"skip_download": True,
},
},
{
"url": "https://shahid.mbc.net/ar/movies/%D8%A7%D9%84%D9%82%D9%86%D8%A7%D8%B5%D8%A9/movie-151746",
"only_matching": True,
},
{
# shahid plus subscriber only
"url": "https://shahid.mbc.net/ar/series/%D9%85%D8%B1%D8%A7%D9%8A%D8%A7-2011-%D8%A7%D9%84%D9%85%D9%88%D8%B3%D9%85-1-%D8%A7%D9%84%D8%AD%D9%84%D9%82%D8%A9-1/episode-90511",
"only_matching": True,
},
{
"url": "https://shahid.mbc.net/en/shows/Ramez-Fi-Al-Shallal-season-1-episode-1/episode-359319",
"only_matching": True,
},
]
def _real_initialize(self):
email, password = self._get_login_info()
if email is None:
return
try:
user_data = self._download_json(
"https://shahid.mbc.net/wd/service/users/login",
None,
"Logging in",
data=json.dumps(
{
"email": email,
"password": password,
"basic": "false",
}
).encode("utf-8"),
headers={
"Content-Type": "application/json; charset=UTF-8",
},
)["user"]
except ExtractorError as e:
if isinstance(e.cause, compat_HTTPError):
self._handle_error(e)
raise
self._download_webpage(
"https://shahid.mbc.net/populateContext",
None,
"Populate Context",
data=urlencode_postdata(
{
"firstName": user_data["firstName"],
"lastName": user_data["lastName"],
"userName": user_data["email"],
"csg_user_name": user_data["email"],
"subscriberId": user_data["id"],
"sessionId": user_data["sessionId"],
}
),
)
def _real_extract(self, url):
page_type, video_id = re.match(self._VALID_URL, url).groups()
if page_type == "clip":
page_type = "episode"
playout = self._call_api("playout/new/url/" + video_id, video_id)["playout"]
if playout.get("drm"):
raise ExtractorError("This video is DRM protected.", expected=True)
formats = self._extract_m3u8_formats(
re.sub(
# https://docs.aws.amazon.com/mediapackage/latest/ug/manifest-filtering.html
r"aws\.manifestfilter=[\w:;,-]+&?",
"",
playout["url"],
),
video_id,
"mp4",
)
self._sort_formats(formats)
# video = self._call_api(
# 'product/id', video_id, {
# 'id': video_id,
# 'productType': 'ASSET',
# 'productSubType': page_type.upper()
# })['productModel']
response = self._download_json(
"http://api.shahid.net/api/v1_1/%s/%s" % (page_type, video_id),
video_id,
"Downloading video JSON",
query={
"apiKey": "sh@hid0nlin3",
"hash": "b2wMCTHpSmyxGqQjJFOycRmLSex+BpTK/ooxy6vHaqs=",
},
)
data = response.get("data", {})
error = data.get("error")
if error:
raise ExtractorError(
"%s returned error: %s" % (self.IE_NAME, "\n".join(error.values())),
expected=True,
)
video = data[page_type]
title = video["title"]
categories = [
category["name"]
for category in video.get("genres", [])
if "name" in category
]
return {
"id": video_id,
"title": title,
"description": video.get("description"),
"thumbnail": video.get("thumbnailUrl"),
"duration": int_or_none(video.get("duration")),
"timestamp": parse_iso8601(video.get("referenceDate")),
"categories": categories,
"series": video.get("showTitle") or video.get("showName"),
"season": video.get("seasonTitle"),
"season_number": int_or_none(video.get("seasonNumber")),
"season_id": str_or_none(video.get("seasonId")),
"episode_number": int_or_none(video.get("number")),
"episode_id": video_id,
"formats": formats,
}
class ShahidShowIE(ShahidBaseIE):
_VALID_URL = (
ShahidBaseIE._VALID_URL_BASE
+ r"(?:show|serie)s/[^/]+/(?:show|series)-(?P<id>\d+)"
)
_TESTS = [
{
"url": "https://shahid.mbc.net/ar/shows/%D8%B1%D8%A7%D9%85%D8%B2-%D9%82%D8%B1%D8%B4-%D8%A7%D9%84%D8%A8%D8%AD%D8%B1/show-79187",
"info_dict": {
"id": "79187",
"title": "رامز قرش البحر",
"description": "md5:c88fa7e0f02b0abd39d417aee0d046ff",
},
"playlist_mincount": 32,
},
{
"url": "https://shahid.mbc.net/ar/series/How-to-live-Longer-(The-Big-Think)/series-291861",
"only_matching": True,
},
]
_PAGE_SIZE = 30
def _real_extract(self, url):
show_id = self._match_id(url)
product = self._call_api("playableAsset", show_id, {"showId": show_id})[
"productModel"
]
playlist = product["playlist"]
playlist_id = playlist["id"]
show = product.get("show", {})
def page_func(page_num):
playlist = self._call_api(
"product/playlist",
show_id,
{
"playListId": playlist_id,
"pageNumber": page_num,
"pageSize": 30,
"sorts": [{"order": "DESC", "type": "SORTDATE"}],
},
)
for product in playlist.get("productList", {}).get("products", []):
product_url = product.get("productUrl", []).get("url")
if not product_url:
continue
yield self.url_result(
product_url,
"Shahid",
str_or_none(product.get("id")),
product.get("title"),
)
entries = InAdvancePagedList(
page_func, math.ceil(playlist["count"] / self._PAGE_SIZE), self._PAGE_SIZE
)
return self.playlist_result(
entries, show_id, show.get("title"), show.get("description")
)
|
Gui | Hop | # -*- coding: utf-8 -*-
# ***************************************************************************
# * Copyright (c) 2014 Yorik van Havre <yorik@uncreated.net> *
# * *
# * This program is free software; you can redistribute it and/or modify *
# * it under the terms of the GNU Lesser General Public License (LGPL) *
# * as published by the Free Software Foundation; either version 2 of *
# * the License, or (at your option) any later version. *
# * for detail see the LICENCE text file. *
# * *
# * This program is distributed in the hope that it will be useful, *
# * but WITHOUT ANY WARRANTY; without even the implied warranty of *
# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
# * GNU Library General Public License for more details. *
# * *
# * You should have received a copy of the GNU Library General Public *
# * License along with this program; if not, write to the Free Software *
# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
# * USA *
# * *
# ***************************************************************************
import FreeCAD
import FreeCADGui
import Path
from PySide.QtCore import QT_TRANSLATE_NOOP
__doc__ = """Path Hop object and FreeCAD command"""
translate = FreeCAD.Qt.translate
class ObjectHop:
def __init__(self, obj):
obj.addProperty(
"App::PropertyLink",
"NextObject",
"Path",
QT_TRANSLATE_NOOP("App::Property", "The object to be reached by this hop"),
)
obj.addProperty(
"App::PropertyDistance",
"HopHeight",
"Path",
QT_TRANSLATE_NOOP("App::Property", "The Z height of the hop"),
)
obj.Proxy = self
def dumps(self):
return None
def loads(self, state):
return None
def execute(self, obj):
nextpoint = FreeCAD.Vector()
if obj.NextObject:
if obj.NextObject.isDerivedFrom("Path::Feature"):
# look for the first position of the next path
for c in obj.NextObject.Path.Commands:
if c.Name in ["G0", "G00", "G1", "G01", "G2", "G02", "G3", "G03"]:
nextpoint = c.Placement.Base
break
# absolute coords, millimeters, cancel offsets
output = "G90\nG21\nG40\n"
# go up to the given height
output += "G0 Z" + str(obj.HopHeight.Value) + "\n"
# go horizontally to the position of nextpoint
output += "G0 X" + str(nextpoint.x) + " Y" + str(nextpoint.y) + "\n"
# print output
path = Path.Path(output)
obj.Path = path
class ViewProviderPathHop:
def __init__(self, vobj):
self.Object = vobj.Object
vobj.Proxy = self
def attach(self, vobj):
self.Object = vobj.Object
def getIcon(self):
return ":/icons/Path_Hop.svg"
def dumps(self):
return None
def loads(self, state):
return None
class CommandPathHop:
def GetResources(self):
return {
"Pixmap": "Path_Hop",
"MenuText": QT_TRANSLATE_NOOP("Path_Hop", "Hop"),
"ToolTip": QT_TRANSLATE_NOOP("Path_Hop", "Creates a Path Hop object"),
}
def IsActive(self):
if FreeCAD.ActiveDocument is not None:
for o in FreeCAD.ActiveDocument.Objects:
if o.Name[:3] == "Job":
return True
return False
def Activated(self):
# check that the selection contains exactly what we want
selection = FreeCADGui.Selection.getSelection()
if len(selection) != 1:
FreeCAD.Console.PrintError(
translate("Path_Hop", "Please select one path object") + "\n"
)
return
if not selection[0].isDerivedFrom("Path::Feature"):
FreeCAD.Console.PrintError(
translate("Path_Hop", "The selected object is not a path") + "\n"
)
return
FreeCAD.ActiveDocument.openTransaction("Create Hop")
FreeCADGui.addModule("Path.Op.Gui.Hop")
FreeCADGui.addModule("PathScripts.PathUtils")
FreeCADGui.doCommand(
'obj = FreeCAD.ActiveDocument.addObject("Path::FeaturePython","Hop")'
)
FreeCADGui.doCommand("Path.Op.Gui.Hop.ObjectHop(obj)")
FreeCADGui.doCommand("Path.Op.Gui.Hop.ViewProviderPathHop(obj.ViewObject)")
FreeCADGui.doCommand(
"obj.NextObject = FreeCAD.ActiveDocument." + selection[0].Name
)
FreeCADGui.doCommand("PathScripts.PathUtils.addToJob(obj)")
FreeCAD.ActiveDocument.commitTransaction()
FreeCAD.ActiveDocument.recompute()
if FreeCAD.GuiUp:
# register the FreeCAD command
FreeCADGui.addCommand("Path_Hop", CommandPathHop())
FreeCAD.Console.PrintLog("Loading PathHop... done\n")
|
controllers | editor_text | # -*- coding: utf-8 -*-
#
# Copyright (C) 2016 by Ihor E. Novikov
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
from copy import deepcopy
from generic import AbstractController
from sk1 import _, config, events, modes
from uc2 import libgeom
class TextEditor(AbstractController):
mode = modes.TEXT_EDITOR_MODE
target = None
selected_obj = None
points = []
selected_points = []
spoint = None
trafos = {}
trafo_mode = modes.ET_MOVING_MODE
move_flag = False
initial_start = None
def __init__(self, canvas, presenter):
AbstractController.__init__(self, canvas, presenter)
def start_(self):
self.snap = self.presenter.snap
self.target = self.selection.objs[0]
self.selected_obj = None
self.update_points()
self.selection.clear()
self.trafo_mode = modes.ET_MOVING_MODE
msg = _("Text in shaping")
events.emit(events.APP_STATUS, msg)
def stop_(self):
if not self.selected_obj:
self.selection.set(
[
self.target,
]
)
else:
self.selection.set(
[
self.selected_obj,
]
)
self.target = None
self.selected_obj = None
self.points = []
def escape_pressed(self):
self.canvas.set_mode()
def update_points(self):
cv = self.canvas
self.points = []
index = 0
for item in self.target.cache_layout_data:
if index < len(self.target.cache_cpath) and self.target.cache_cpath[index]:
x = item[0]
y = item[4]
trafo = self.target.trafo
flag = False
if index in self.target.trafos.keys():
trafo = self.target.trafos[index]
flag = True
self.points.append(ControlPoint(cv, index, [x, y], trafo, flag))
index += 1
def set_mode(self, mode):
if mode in modes.ET_MODES and not mode == self.trafo_mode:
pass
# ----- REPAINT
def repaint(self):
bbox = self.target.cache_layout_bbox
self.canvas.renderer.draw_text_frame(bbox, self.target.trafo)
for item in self.points:
selected = False
if item in self.selected_points:
selected = True
item.repaint(selected)
def repaint_frame(self):
self.canvas.renderer.cdc_draw_frame(self.start, self.end, True)
def on_timer(self):
if self.draw:
self.repaint_frame()
# ----- MOUSE CONTROLLING
def mouse_down(self, event):
self.timer.stop()
self.initial_start = []
self.start = []
self.end = []
self.draw = False
self.move_flag = False
self.start = event.get_point()
self.initial_start = event.get_point()
self.spoint = self.select_point_by_click(self.start)
if not self.spoint:
self.timer.start()
def mouse_move(self, event):
if not self.start:
return
if not self.move_flag and not self.spoint:
self.end = event.get_point()
self.draw = True
elif self.move_flag:
self.end = event.get_point()
trafo = self.get_trafo(
self.start, self.end, event.is_ctrl(), event.is_shift()
)
self.apply_trafo_to_selected(trafo)
self.start = self.end
self.canvas.selection_redraw()
elif self.spoint:
if self.spoint not in self.selected_points:
self.set_selected_points(
[
self.spoint,
]
)
self.move_flag = True
self.trafos = deepcopy(self.target.trafos)
self.canvas.selection_redraw()
def mouse_up(self, event):
self.timer.stop()
self.end = event.get_point()
if self.draw:
self.draw = False
points = self.select_points_by_bbox(self.start + self.end)
self.set_selected_points(points, event.is_shift())
self.canvas.selection_redraw()
elif self.move_flag:
self.move_flag = False
trafo = self.get_trafo(
self.start, self.end, event.is_ctrl(), event.is_shift()
)
self.apply_trafo_to_selected(trafo, True)
self.canvas.selection_redraw()
elif self.spoint:
self.set_selected_points(
[
self.spoint,
],
event.is_shift(),
)
self.canvas.selection_redraw()
else:
objs = self.canvas.pick_at_point(self.end)
if objs and objs[0].is_primitive:
self.selected_obj = objs[0]
self.start = []
self.canvas.set_mode(modes.SHAPER_MODE)
return
else:
self.set_selected_points([])
self.canvas.selection_redraw()
self.start = []
def mouse_double_click(self, event):
self.canvas.set_mode()
# ----- POINT PROCESSING
def set_selected_points(self, points, add=False):
if add:
for item in points:
if item not in self.selected_points:
self.selected_points.append(item)
else:
self.selected_points.remove(item)
else:
self.selected_points = points
def select_points_by_bbox(self, bbox):
ret = []
bbox = libgeom.normalize_bbox(bbox)
for item in self.points:
if libgeom.is_point_in_bbox(item.get_screen_point(), bbox):
ret.append(item)
return ret
def select_point_by_click(self, point):
for item in self.points:
ipoint = item.get_screen_point()
bbox = libgeom.bbox_for_point(ipoint, config.point_sensitivity_size)
if libgeom.is_point_in_bbox(point, bbox):
return item
return None
def get_trafo(self, start, end, ctrl=False, shift=False):
trafo = [1.0, 0.0, 0.0, 1.0]
dchange = [0.0, 0.0]
dstart = self.canvas.win_to_doc(start)
dend = self.canvas.win_to_doc(end)
if self.trafo_mode == modes.ET_MOVING_MODE:
dchange = libgeom.sub_points(dend, dstart)
if ctrl:
change = libgeom.sub_points(end, self.initial_start)
if abs(change[0]) > abs(change[1]):
dchange = [dchange[0], 0.0]
else:
dchange = [0.0, dchange[1]]
return trafo + dchange
def apply_trafo_to_selected(self, trafo, final=False):
trafos = deepcopy(self.target.trafos)
for item in self.selected_points:
index = item.index
if index in trafos.keys():
trafos[index] = libgeom.multiply_trafo(trafos[index], trafo)
else:
trafos[index] = libgeom.multiply_trafo(self.target.trafo, trafo)
item.apply_trafo(trafo)
if not final:
self.api.set_temp_text_trafos(self.target, trafos)
else:
self.api.set_text_trafos(self.target, trafos, self.trafos)
self.trafos = {}
class ControlPoint:
canvas = None
index = 0
point = []
trafo = []
modified = False
def __init__(self, canvas, index, point, trafo, modified=False):
self.canvas = canvas
self.index = index
self.point = point
self.trafo = trafo
self.modified = modified
def apply_trafo(self, trafo):
self.trafo = libgeom.multiply_trafo(self.trafo, trafo)
def get_point(self):
return libgeom.apply_trafo_to_point(self.point, self.trafo)
def get_screen_point(self):
return self.canvas.point_doc_to_win(self.get_point())
def repaint(self, selected=False):
self.canvas.renderer.draw_text_point(self.get_screen_point(), selected)
|
modules | mod_tracker_lastfm | # MusicPlayer, https://github.com/albertz/music-player
# Copyright (c) 2012, Albert Zeyer, www.az2000.de
# All rights reserved.
# This code is under the 2-clause BSD license, see License.txt in the root directory of this project.
""" This is the Last.fm tracker module. """
import sys
import appinfo
import lastfm
from player import PlayerEventCallbacks
from Song import Song
from State import state
from utils import *
def track(event, args, kwargs):
# Note that we can get an `onSongChange` when we are not playing,
# e.g. at startup (first song) or when the user presses `nextSong`.
# So it might make sense to delay that here...
# We don't for now for simplicity reasons...
if event is PlayerEventCallbacks.onSongChange:
oldSong = kwargs["oldSong"]
newSong = kwargs["newSong"]
lastfm.onSongChange(newSong)
if event is PlayerEventCallbacks.onSongFinished:
song = kwargs["song"]
timestamp = kwargs["timestamp"]
lastfm.onSongFinished(song, timestamp=timestamp)
def event_filter(ev):
if ev is PlayerEventCallbacks.onSongChange:
return True
if ev is PlayerEventCallbacks.onSongFinished:
return True
return False
def stateUpdates_append_wrapper(self, value):
ev, args, kwargs = value
if not event_filter(ev):
return
self.__get__(None).append(value)
self.save()
def tracker_lastfmMain():
if not appinfo.config.lastFm:
return
assert "append" in OnRequestQueue.ListUsedModFunctions
assert PlayerEventCallbacks.onSongChange is not None
assert PlayerEventCallbacks.onSongFinished is not None
queueList = PersistentObject(
deque,
"lastfm-queue.dat",
namespace=globals(),
customAttribs={"append": stateUpdates_append_wrapper},
installAutosaveWrappersOn=OnRequestQueue.ListUsedModFunctions,
)
stateUpdateStream = state.updates.read(queueList=queueList)
lastfm.login()
for ev, args, kwargs in stateUpdateStream:
try:
track(ev, args, kwargs)
except Exception:
sys.excepthook(*sys.exc_info())
else:
queueList.save()
lastfm.quit()
|
models | messaging | import hashlib
from django.conf import settings
from django.db import models
from .utils import UUIDModel
def get_email_hash(email: str) -> str:
return hashlib.sha256(f"{settings.SECRET_KEY}_{email}".encode()).hexdigest()
class MessagingRecordManager(models.Manager):
def get_or_create(self, defaults=None, **kwargs):
raw_email = kwargs.pop("raw_email", None)
if raw_email:
kwargs["email_hash"] = get_email_hash(raw_email)
return super().get_or_create(defaults, **kwargs)
class MessagingRecord(UUIDModel):
objects = MessagingRecordManager()
email_hash: models.CharField = models.CharField(max_length=1024)
campaign_key: models.CharField = models.CharField(max_length=128)
sent_at: models.DateTimeField = models.DateTimeField(null=True)
created_at: models.DateTimeField = models.DateTimeField(auto_now_add=True)
class Meta:
unique_together = (
"email_hash",
"campaign_key",
) # can only send campaign once to each email
|
blocks | qa_vector_map | #!/usr/bin/env python
#
# Copyright 2012,2013 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# SPDX-License-Identifier: GPL-3.0-or-later
#
#
import math
from gnuradio import blocks, gr, gr_unittest
class test_vector_map(gr_unittest.TestCase):
def setUp(self):
self.tb = gr.top_block()
def tearDown(self):
self.tb = None
def test_reversing(self):
# Chunk data in blocks of N and reverse the block contents.
N = 5
src_data = list(range(0, 20))
expected_result = []
for i in range(N - 1, len(src_data), N):
for j in range(0, N):
expected_result.append(1.0 * (i - j))
mapping = [list(reversed([(0, i) for i in range(0, N)]))]
src = blocks.vector_source_f(src_data, False, N)
vmap = blocks.vector_map(gr.sizeof_float, (N,), mapping)
dst = blocks.vector_sink_f(N)
self.tb.connect(src, vmap, dst)
self.tb.run()
result_data = list(dst.data())
self.assertEqual(expected_result, result_data)
def test_vector_to_streams(self):
# Split an input vector into N streams.
N = 5
M = 20
src_data = list(range(0, M))
expected_results = []
for n in range(0, N):
expected_results.append(list(range(n, M, N)))
mapping = [[(0, n)] for n in range(0, N)]
src = blocks.vector_source_f(src_data, False, N)
vmap = blocks.vector_map(gr.sizeof_float, (N,), mapping)
dsts = [blocks.vector_sink_f(1) for n in range(0, N)]
self.tb.connect(src, vmap)
for n in range(0, N):
self.tb.connect((vmap, n), dsts[n])
self.tb.run()
for n in range(0, N):
result_data = list(dsts[n].data())
self.assertEqual(expected_results[n], result_data)
def test_interleaving(self):
# Takes 3 streams (a, b and c)
# Outputs 2 streams.
# First (d) is interleaving of a and b.
# Second (e) is interleaving of a and b and c. c is taken in
# chunks of 2 which are reversed.
A = [1, 2, 3, 4, 5]
B = [11, 12, 13, 14, 15]
C = [99, 98, 97, 96, 95, 94, 93, 92, 91, 90]
expected_D = [1, 11, 2, 12, 3, 13, 4, 14, 5, 15]
expected_E = [
1,
11,
98,
99,
2,
12,
96,
97,
3,
13,
94,
95,
4,
14,
92,
93,
5,
15,
90,
91,
]
mapping = [
[(0, 0), (1, 0)], # mapping to produce D
[(0, 0), (1, 0), (2, 1), (2, 0)], # mapping to produce E
]
srcA = blocks.vector_source_f(A, False, 1)
srcB = blocks.vector_source_f(B, False, 1)
srcC = blocks.vector_source_f(C, False, 2)
vmap = blocks.vector_map(gr.sizeof_int, (1, 1, 2), mapping)
dstD = blocks.vector_sink_f(2)
dstE = blocks.vector_sink_f(4)
self.tb.connect(srcA, (vmap, 0))
self.tb.connect(srcB, (vmap, 1))
self.tb.connect(srcC, (vmap, 2))
self.tb.connect((vmap, 0), dstD)
self.tb.connect((vmap, 1), dstE)
self.tb.run()
self.assertEqual(expected_D, dstD.data())
self.assertEqual(expected_E, dstE.data())
if __name__ == "__main__":
gr_unittest.run(test_vector_map)
|
downloaders | RedtubeCom | # -*- coding: utf-8 -*-
import json
import re
from ..base.downloader import BaseDownloader
class RedtubeCom(BaseDownloader):
__name__ = "RedtubeCom"
__type__ = "downloader"
__version__ = "0.28"
__status__ = "testing"
__pattern__ = r"https?://(?:www\.)?redtube\.com/\d+"
__config__ = [("enabled", "bool", "Activated", True)]
__description__ = """Redtube.com downloader plugin"""
__license__ = "GPLv3"
__authors__ = [
("jeix", "jeix@hasnomail.de"),
("GammaC0de", "nitzo2001[AT}yahoo[DOT]com"),
]
def process(self, pyfile):
html = self.load(pyfile.url)
m = re.search(r"playervars: ({.+}),", html)
if m is None:
self.error(self._("playervars pattern not found"))
playervars = json.loads(m.group(1))
media_info = [
x["videoUrl"]
for x in playervars["mediaDefinitions"]
if x.get("format") == "mp4" and x.get("remote") is True
]
if len(media_info) == 0:
self.fail(self._("no media definitions found"))
video_info = json.loads(self.load(media_info[0]))
video_info = sorted(video_info, key=lambda k: int(k["quality"]), reverse=True)
link = video_info[0]["videoUrl"]
pyfile.name = playervars["video_title"] + ".mp4"
self.download(link)
|
admin | link_domains | """ Manage link domains"""
from bookwyrm import forms, models
from bookwyrm.models.report import APPROVE_DOMAIN, BLOCK_DOMAIN
from bookwyrm.views.helpers import redirect_to_referer
from django.contrib.auth.decorators import login_required, permission_required
from django.shortcuts import get_object_or_404, redirect
from django.template.response import TemplateResponse
from django.utils.decorators import method_decorator
from django.views import View
from django.views.decorators.http import require_POST
# pylint: disable=no-self-use
@method_decorator(login_required, name="dispatch")
@method_decorator(
permission_required("bookwyrm.moderate_user", raise_exception=True),
name="dispatch",
)
class LinkDomain(View):
"""Moderate links"""
def get(self, request, status="pending"):
"""view pending domains"""
data = {
"domains": models.LinkDomain.objects.filter(status=status)
.prefetch_related("links")
.order_by("-created_date"),
"counts": {
"pending": models.LinkDomain.objects.filter(status="pending").count(),
"approved": models.LinkDomain.objects.filter(status="approved").count(),
"blocked": models.LinkDomain.objects.filter(status="blocked").count(),
},
"form": forms.EmailBlocklistForm(),
"status": status,
}
return TemplateResponse(
request, "settings/link_domains/link_domains.html", data
)
def post(self, request, status, domain_id):
"""Set display name"""
domain = get_object_or_404(models.LinkDomain, id=domain_id)
form = forms.LinkDomainForm(request.POST, instance=domain)
form.save(request)
return redirect("settings-link-domain", status=status)
@require_POST
@login_required
@permission_required("bookwyrm.moderate_user")
def update_domain_status(request, domain_id, status, report_id=None):
"""This domain seems fine"""
domain = get_object_or_404(models.LinkDomain, id=domain_id)
domain.raise_not_editable(request.user)
domain.status = status
domain.save()
if status == "approved":
models.Report.record_action(report_id, APPROVE_DOMAIN, request.user)
elif status == "blocked":
models.Report.record_action(report_id, BLOCK_DOMAIN, request.user)
return redirect_to_referer(request, "settings-link-domain", status="pending")
|
misc | throttle | # SPDX-FileCopyrightText: Jay Kamat <jaygkamat@gmail.com>
#
# SPDX-License-Identifier: GPL-3.0-or-later
"""A throttle for throttling function calls."""
import dataclasses
import time
from typing import Any, Callable, Mapping, Optional, Sequence
from qutebrowser.qt.core import QObject
from qutebrowser.utils import usertypes
@dataclasses.dataclass
class _CallArgs:
args: Sequence[Any]
kwargs: Mapping[str, Any]
class Throttle(QObject):
"""A throttle to throttle calls.
If a request comes in, it will be processed immediately. If another request
comes in too soon, it is ignored, but will be processed when a timeout
ends. If another request comes in, it will update the pending request.
"""
def __init__(
self, func: Callable[..., None], delay_ms: int, parent: QObject = None
) -> None:
"""Constructor.
Args:
delay_ms: The time to wait before allowing another call of the
function. -1 disables the wrapper.
func: The function/method to call on __call__.
parent: The parent object.
"""
super().__init__(parent)
self._delay_ms = delay_ms
self._func = func
self._pending_call: Optional[_CallArgs] = None
self._last_call_ms: Optional[int] = None
self._timer = usertypes.Timer(self, "throttle-timer")
self._timer.setSingleShot(True)
def _call_pending(self) -> None:
"""Start a pending call."""
assert self._pending_call is not None
self._func(*self._pending_call.args, **self._pending_call.kwargs)
self._pending_call = None
self._last_call_ms = int(time.monotonic() * 1000)
def __call__(self, *args: Any, **kwargs: Any) -> Any:
cur_time_ms = int(time.monotonic() * 1000)
if self._pending_call is None:
if (
self._last_call_ms is None
or cur_time_ms - self._last_call_ms > self._delay_ms
):
# Call right now
self._last_call_ms = cur_time_ms
self._func(*args, **kwargs)
return
self._timer.setInterval(self._delay_ms - (cur_time_ms - self._last_call_ms))
# Disconnect any existing calls, continue if no connections.
try:
self._timer.timeout.disconnect()
except TypeError:
pass
self._timer.timeout.connect(self._call_pending)
self._timer.start()
# Update arguments for an existing pending call
self._pending_call = _CallArgs(args=args, kwargs=kwargs)
def set_delay(self, delay_ms: int) -> None:
"""Set the delay to wait between invocation of this function."""
self._delay_ms = delay_ms
def cancel(self) -> None:
"""Cancel any pending instance of this timer."""
self._timer.stop()
|
restapi | downloads_endpoint | from asyncio import CancelledError
from asyncio import TimeoutError as AsyncTimeoutError
from asyncio import wait_for
from binascii import unhexlify
from contextlib import suppress
from pathlib import PurePosixPath
from aiohttp import web
from aiohttp_apispec import docs, json_schema
from ipv8.messaging.anonymization.tunnel import CIRCUIT_ID_PORT, PEER_FLAG_EXIT_BT
from ipv8.REST.schema import schema
from marshmallow.fields import Boolean, Float, Integer, List, String
from tribler.core.components.libtorrent.download_manager.download_config import (
DownloadConfig,
)
from tribler.core.components.libtorrent.download_manager.download_manager import (
DownloadManager,
)
from tribler.core.components.libtorrent.download_manager.stream import (
STREAM_PAUSE_TIME,
StreamChunk,
)
from tribler.core.components.libtorrent.utils.libtorrent_helper import libtorrent as lt
from tribler.core.components.restapi.rest.rest_endpoint import (
HTTP_BAD_REQUEST,
HTTP_INTERNAL_SERVER_ERROR,
HTTP_NOT_FOUND,
RESTEndpoint,
RESTResponse,
RESTStreamResponse,
)
from tribler.core.components.restapi.rest.utils import return_handled_exception
from tribler.core.utilities.path_util import Path
from tribler.core.utilities.simpledefs import DOWNLOAD, UPLOAD, DownloadStatus
from tribler.core.utilities.unicode import ensure_unicode, hexlify
from tribler.core.utilities.utilities import froze_it
TOTAL = "total"
LOADED = "loaded"
ALL_LOADED = "all_loaded"
def _safe_extended_peer_info(ext_peer_info):
"""
Given a string describing peer info, return a json.dumps() safe representation.
:param ext_peer_info: the string to convert to a dumpable format
:return: the safe string
"""
# First see if we can use this as-is
if not ext_peer_info:
return ""
try:
return ensure_unicode(ext_peer_info, "utf8")
except UnicodeDecodeError:
# We might have some special unicode characters in here
return "".join(map(chr, ext_peer_info))
def get_extended_status(tunnel_community, download) -> DownloadStatus:
"""
This function filters the original download status to possibly add tunnel-related status.
Extracted from DownloadState to remove coupling between DownloadState and Tunnels.
"""
state = download.get_state()
status = state.get_status()
# Nothing to do with tunnels. If stopped - it happened by the user or libtorrent-only reason
stopped_by_user = state.lt_status and state.lt_status.paused
if status == DownloadStatus.STOPPED and not stopped_by_user:
if download.config.get_hops() > 0:
if tunnel_community.get_candidates(PEER_FLAG_EXIT_BT):
return DownloadStatus.CIRCUITS
else:
return DownloadStatus.EXIT_NODES
return DownloadStatus.STOPPED
return status
@froze_it
class DownloadsEndpoint(RESTEndpoint):
"""
This endpoint is responsible for all requests regarding downloads. Examples include getting all downloads,
starting, pausing and stopping downloads.
"""
path = "/downloads"
def __init__(
self,
download_manager: DownloadManager,
metadata_store=None,
tunnel_community=None,
):
super().__init__()
self.download_manager = download_manager
self.mds = metadata_store
self.tunnel_community = tunnel_community
def setup_routes(self):
self.app.add_routes(
[
web.get("", self.get_downloads),
web.put("", self.add_download),
web.delete("/{infohash}", self.delete_download),
web.patch("/{infohash}", self.update_download),
web.get("/{infohash}/torrent", self.get_torrent),
web.get("/{infohash}/files", self.get_files),
web.get(
"/{infohash}/stream/{fileindex}", self.stream, allow_head=False
),
]
)
@staticmethod
def return_404(request, message="this download does not exist"):
"""
Returns a 404 response code if your channel has not been created.
"""
return RESTResponse({"error": message}, status=HTTP_NOT_FOUND)
@staticmethod
def create_dconfig_from_params(parameters):
"""
Create a download configuration based on some given parameters. Possible parameters are:
- anon_hops: the number of hops for the anonymous download. 0 hops is equivalent to a plain download
- safe_seeding: whether the seeding of the download should be anonymous or not (0 = off, 1 = on)
- destination: the destination path of the torrent (where it is saved on disk)
"""
download_config = DownloadConfig()
anon_hops = parameters.get("anon_hops", 0)
safe_seeding = bool(parameters.get("safe_seeding", 0))
if anon_hops > 0 and not safe_seeding:
return None, "Cannot set anonymous download without safe seeding enabled"
if anon_hops > 0:
download_config.set_hops(anon_hops)
if safe_seeding:
download_config.set_safe_seeding(True)
if "destination" in parameters:
download_config.set_dest_dir(parameters["destination"])
if "selected_files" in parameters:
download_config.set_selected_files(parameters["selected_files"])
return download_config, None
@staticmethod
def get_files_info_json(download):
"""
Return file information as JSON from a specified download.
"""
files_json = []
files_completion = {
name: progress
for name, progress in download.get_state().get_files_completion()
}
selected_files = download.config.get_selected_files()
file_index = 0
for fn, size in download.get_def().get_files_with_length():
files_json.append(
{
"index": file_index,
# We always return files in Posix format to make GUI independent of Core and simplify testing
"name": str(PurePosixPath(fn)),
"size": size,
"included": (file_index in selected_files or not selected_files),
"progress": files_completion.get(fn, 0.0),
}
)
file_index += 1
return files_json
@docs(
tags=["Libtorrent"],
summary="Return all downloads, both active and inactive",
parameters=[
{
"in": "query",
"name": "get_peers",
"description": "Flag indicating whether or not to include peers",
"type": "boolean",
"required": False,
},
{
"in": "query",
"name": "get_pieces",
"description": "Flag indicating whether or not to include pieces",
"type": "boolean",
"required": False,
},
{
"in": "query",
"name": "get_files",
"description": "Flag indicating whether or not to include files",
"type": "boolean",
"required": False,
},
],
responses={
200: {
"schema": schema(
DownloadsResponse={
"downloads": schema(
Download={
"name": String,
"progress": Float,
"infohash": String,
"speed_down": Float,
"speed_up": Float,
"status": String,
"status_code": Integer,
"size": Integer,
"eta": Integer,
"num_peers": Integer,
"num_seeds": Integer,
"total_up": Integer,
"total_down": Integer,
"ratio": Float,
"files": String,
"trackers": String,
"hops": Integer,
"anon_download": Boolean,
"safe_seeding": Boolean,
"max_upload_speed": Integer,
"max_download_speed": Integer,
"destination": String,
"availability": Float,
"peers": String,
"total_pieces": Integer,
"vod_mode": Boolean,
"vod_prebuffering_progress": Float,
"vod_prebuffering_progress_consec": Float,
"error": String,
"time_added": Integer,
}
),
"checkpoints": schema(
Checkpoints={
TOTAL: Integer,
LOADED: Integer,
ALL_LOADED: Boolean,
}
),
}
),
}
},
description="This endpoint returns all downloads in Tribler, both active and inactive. The progress "
"is a number ranging from 0 to 1, indicating the progress of the specific state (downloading, "
"checking etc). The download speeds have the unit bytes/sec. The size of the torrent is given "
"in bytes. The estimated time assumed is given in seconds.\n\n"
"Detailed information about peers and pieces is only requested when the get_peers and/or "
"get_pieces flag is set. Note that setting this flag has a negative impact on performance "
"and should only be used in situations where this data is required. ",
)
async def get_downloads(self, request):
params = request.query
get_peers = params.get("get_peers", "0") == "1"
get_pieces = params.get("get_pieces", "0") == "1"
get_files = params.get("get_files", "0") == "1"
checkpoints = {
TOTAL: self.download_manager.checkpoints_count,
LOADED: self.download_manager.checkpoints_loaded,
ALL_LOADED: self.download_manager.all_checkpoints_are_loaded,
}
if not self.download_manager.all_checkpoints_are_loaded:
return RESTResponse({"downloads": [], "checkpoints": checkpoints})
downloads_json = []
downloads = self.download_manager.get_downloads()
for download in downloads:
if download.hidden and not download.config.get_channel_download():
# We still want to send channel downloads since they are displayed in the GUI
continue
state = download.get_state()
tdef = download.get_def()
# Create tracker information of the download
tracker_info = []
for url, url_info in download.get_tracker_status().items():
tracker_info.append(
{"url": url, "peers": url_info[0], "status": url_info[1]}
)
num_seeds, num_peers = state.get_num_seeds_peers()
(
num_connected_seeds,
num_connected_peers,
) = download.get_num_connected_seeds_peers()
if download.config.get_channel_download():
download_name = self.mds.ChannelMetadata.get_channel_name_cached(
tdef.get_name_utf8(), tdef.get_infohash()
)
elif self.mds is None:
download_name = tdef.get_name_utf8()
else:
download_name = (
self.mds.TorrentMetadata.get_torrent_title(tdef.get_infohash())
or tdef.get_name_utf8()
)
download_status = (
get_extended_status(self.tunnel_community, download)
if self.tunnel_community
else download.get_state().get_status()
)
download_json = {
"name": download_name,
"progress": state.get_progress(),
"infohash": hexlify(tdef.get_infohash()),
"speed_down": state.get_current_payload_speed(DOWNLOAD),
"speed_up": state.get_current_payload_speed(UPLOAD),
"status": download_status.name,
"status_code": download_status.value,
"size": tdef.get_length(),
"eta": state.get_eta(),
"num_peers": num_peers,
"num_seeds": num_seeds,
"num_connected_peers": num_connected_peers,
"num_connected_seeds": num_connected_seeds,
"total_up": state.get_total_transferred(UPLOAD),
"total_down": state.get_total_transferred(DOWNLOAD),
"ratio": state.get_seeding_ratio(),
"trackers": tracker_info,
"hops": download.config.get_hops(),
"anon_download": download.get_anon_mode(),
"safe_seeding": download.config.get_safe_seeding(),
# Maximum upload/download rates are set for entire sessions
"max_upload_speed": DownloadManager.get_libtorrent_max_upload_rate(
self.download_manager.config
),
"max_download_speed": DownloadManager.get_libtorrent_max_download_rate(
self.download_manager.config
),
"destination": str(download.config.get_dest_dir()),
"availability": state.get_availability(),
"total_pieces": tdef.get_nr_pieces(),
"vod_mode": download.stream and download.stream.enabled,
"error": repr(state.get_error()) if state.get_error() else "",
"time_added": download.config.get_time_added(),
"channel_download": download.config.get_channel_download(),
}
if download.stream:
download_json.update(
{
"vod_prebuffering_progress": download.stream.prebuffprogress,
"vod_prebuffering_progress_consec": download.stream.prebuffprogress_consec,
"vod_header_progress": download.stream.headerprogress,
"vod_footer_progress": download.stream.footerprogress,
}
)
# Add peers information if requested
if get_peers:
peer_list = state.get_peerlist()
for (
peer_info
) in peer_list: # Remove have field since it is very large to transmit.
del peer_info["have"]
if "extended_version" in peer_info:
peer_info["extended_version"] = _safe_extended_peer_info(
peer_info["extended_version"]
)
# Does this peer represent a hidden services circuit?
if (
peer_info.get("port") == CIRCUIT_ID_PORT
and self.tunnel_community
):
tc = self.tunnel_community
circuit_id = tc.ip_to_circuit_id(peer_info["ip"])
circuit = tc.circuits.get(circuit_id, None)
if circuit:
peer_info["circuit"] = circuit_id
download_json["peers"] = peer_list
# Add piece information if requested
if get_pieces:
download_json["pieces"] = download.get_pieces_base64().decode("utf-8")
# Add files if requested
if get_files:
download_json["files"] = self.get_files_info_json(download)
downloads_json.append(download_json)
return RESTResponse({"downloads": downloads_json, "checkpoints": checkpoints})
@docs(
tags=["Libtorrent"],
summary="Start a download from a provided URI.",
parameters=[
{
"in": "query",
"name": "get_peers",
"description": "Flag indicating whether or not to include peers",
"type": "boolean",
"required": False,
},
{
"in": "query",
"name": "get_pieces",
"description": "Flag indicating whether or not to include pieces",
"type": "boolean",
"required": False,
},
{
"in": "query",
"name": "get_files",
"description": "Flag indicating whether or not to include files",
"type": "boolean",
"required": False,
},
],
responses={
200: {
"schema": schema(
AddDownloadResponse={"started": Boolean, "infohash": String}
),
"examples": {
"started": True,
"infohash": "4344503b7e797ebf31582327a5baae35b11bda01",
},
}
},
)
@json_schema(
schema(
AddDownloadRequest={
"anon_hops": (
Integer,
"Number of hops for the anonymous download. No hops is equivalent to a plain download",
),
"safe_seeding": (
Boolean,
"Whether the seeding of the download should be anonymous or not",
),
"destination": (String, "the download destination path of the torrent"),
"uri*": (
String,
"The URI of the torrent file that should be downloaded. This URI can either represent a file "
"location, a magnet link or a HTTP(S) url.",
),
}
)
)
async def add_download(self, request):
params = await request.json()
uri = params.get("uri")
if not uri:
return RESTResponse(
{"error": "uri parameter missing"}, status=HTTP_BAD_REQUEST
)
download_config, error = DownloadsEndpoint.create_dconfig_from_params(params)
if error:
return RESTResponse({"error": error}, status=HTTP_BAD_REQUEST)
try:
download = await self.download_manager.start_download_from_uri(
uri, config=download_config
)
except Exception as e:
return RESTResponse({"error": str(e)}, status=HTTP_INTERNAL_SERVER_ERROR)
return RESTResponse(
{"started": True, "infohash": hexlify(download.get_def().get_infohash())}
)
@docs(
tags=["Libtorrent"],
summary="Remove a specific download.",
parameters=[
{
"in": "path",
"name": "infohash",
"description": "Infohash of the download to remove",
"type": "string",
"required": True,
}
],
responses={
200: {
"schema": schema(
DeleteDownloadResponse={"removed": Boolean, "infohash": String}
),
"examples": {
"removed": True,
"infohash": "4344503b7e797ebf31582327a5baae35b11bda01",
},
}
},
)
@json_schema(
schema(
RemoveDownloadRequest={
"remove_data": (
Boolean,
"Whether or not to remove the associated data",
),
}
)
)
async def delete_download(self, request):
parameters = await request.json()
if "remove_data" not in parameters:
return RESTResponse(
{"error": "remove_data parameter missing"}, status=HTTP_BAD_REQUEST
)
infohash = unhexlify(request.match_info["infohash"])
download = self.download_manager.get_download(infohash)
if not download:
return DownloadsEndpoint.return_404(request)
try:
await self.download_manager.remove_download(
download, remove_content=parameters["remove_data"]
)
except Exception as e:
self._logger.exception(e)
return return_handled_exception(request, e)
return RESTResponse(
{"removed": True, "infohash": hexlify(download.get_def().get_infohash())}
)
async def vod_response(self, download, parameters, request, vod_mode):
modified = False
if vod_mode:
file_index = parameters.get("fileindex")
if file_index is None:
return RESTResponse(
{"error": "fileindex is necessary to enable vod_mode"},
status=HTTP_BAD_REQUEST,
)
if download.stream is None:
download.add_stream()
if not download.stream.enabled or download.stream.fileindex != file_index:
await wait_for(
download.stream.enable(file_index, request.http_range.start or 0),
10,
)
await download.stream.updateprios()
modified = True
elif not vod_mode and download.stream is not None and download.stream.enabled:
download.stream.disable()
modified = True
return RESTResponse(
{
"vod_prebuffering_progress": download.stream.prebuffprogress,
"vod_prebuffering_progress_consec": download.stream.prebuffprogress_consec,
"vod_header_progress": download.stream.headerprogress,
"vod_footer_progress": download.stream.footerprogress,
"vod_mode": download.stream.enabled,
"infohash": hexlify(download.get_def().get_infohash()),
"modified": modified,
}
)
@docs(
tags=["Libtorrent"],
summary="Update a specific download.",
parameters=[
{
"in": "path",
"name": "infohash",
"description": "Infohash of the download to update",
"type": "string",
"required": True,
}
],
responses={
200: {
"schema": schema(
UpdateDownloadResponse={"modified": Boolean, "infohash": String}
),
"examples": {
"modified": True,
"infohash": "4344503b7e797ebf31582327a5baae35b11bda01",
},
}
},
)
@json_schema(
schema(
UpdateDownloadRequest={
"state": (
String,
"State parameter to be passed to modify the state of the download (resume/stop/recheck)",
),
"selected_files": (
List(Integer),
"File indexes to be included in the download",
),
"anon_hops": (
Integer,
"The anonymity of a download can be changed at runtime by passing the anon_hops "
"parameter, however, this must be the only parameter in this request.",
),
}
)
)
async def update_download(self, request):
infohash = unhexlify(request.match_info["infohash"])
download = self.download_manager.get_download(infohash)
if not download:
return DownloadsEndpoint.return_404(request)
parameters = await request.json()
vod_mode = parameters.get("vod_mode")
if vod_mode is not None:
if not isinstance(vod_mode, bool):
return RESTResponse(
{"error": "vod_mode must be bool flag"}, status=HTTP_BAD_REQUEST
)
return await self.vod_response(download, parameters, request, vod_mode)
if len(parameters) > 1 and "anon_hops" in parameters:
return RESTResponse(
{"error": "anon_hops must be the only parameter in this request"},
status=HTTP_BAD_REQUEST,
)
elif "anon_hops" in parameters:
anon_hops = int(parameters["anon_hops"])
try:
await self.download_manager.update_hops(download, anon_hops)
except Exception as e:
self._logger.exception(e)
return return_handled_exception(request, e)
return RESTResponse(
{
"modified": True,
"infohash": hexlify(download.get_def().get_infohash()),
}
)
if "selected_files" in parameters:
selected_files_list = parameters["selected_files"]
num_files = len(download.tdef.get_files())
if not all([0 <= index < num_files for index in selected_files_list]):
return RESTResponse(
{"error": "index out of range"}, status=HTTP_BAD_REQUEST
)
download.set_selected_files(selected_files_list)
if state := parameters.get("state"):
if state == "resume":
download.resume()
elif state == "stop":
await download.stop(user_stopped=True)
elif state == "recheck":
download.force_recheck()
elif state == "move_storage":
dest_dir = Path(parameters["dest_dir"])
if not dest_dir.exists():
return RESTResponse(
{"error": f"Target directory ({dest_dir}) does not exist"}
)
download.move_storage(dest_dir)
download.checkpoint()
else:
return RESTResponse(
{"error": "unknown state parameter"}, status=HTTP_BAD_REQUEST
)
return RESTResponse(
{"modified": True, "infohash": hexlify(download.get_def().get_infohash())}
)
@docs(
tags=["Libtorrent"],
summary="Return the .torrent file associated with the specified download.",
parameters=[
{
"in": "path",
"name": "infohash",
"description": "Infohash of the download from which to get the .torrent file",
"type": "string",
"required": True,
}
],
responses={200: {"description": "The torrent"}},
)
async def get_torrent(self, request):
infohash = unhexlify(request.match_info["infohash"])
download = self.download_manager.get_download(infohash)
if not download:
return DownloadsEndpoint.return_404(request)
torrent = download.get_torrent_data()
if not torrent:
return DownloadsEndpoint.return_404(request)
return RESTResponse(
lt.bencode(torrent),
headers={
"content-type": "application/x-bittorrent",
"Content-Disposition": "attachment; filename=%s.torrent"
% hexlify(infohash).encode("utf-8"),
},
)
@docs(
tags=["Libtorrent"],
summary="Return file information of a specific download.",
parameters=[
{
"in": "path",
"name": "infohash",
"description": "Infohash of the download to from which to get file information",
"type": "string",
"required": True,
}
],
responses={
200: {
"schema": schema(
GetFilesResponse={
"files": [
schema(
File={
"index": Integer,
"name": String,
"size": Integer,
"included": Boolean,
"progress": Float,
}
)
]
}
)
}
},
)
async def get_files(self, request):
infohash = unhexlify(request.match_info["infohash"])
download = self.download_manager.get_download(infohash)
if not download:
return DownloadsEndpoint.return_404(request)
return RESTResponse({"files": self.get_files_info_json(download)})
@docs(
tags=["Libtorrent"],
summary="Stream the contents of a file that is being downloaded.",
parameters=[
{
"in": "path",
"name": "infohash",
"description": "Infohash of the download to stream",
"type": "string",
"required": True,
},
{
"in": "path",
"name": "fileindex",
"description": "The fileindex to stream",
"type": "string",
"required": True,
},
],
responses={206: {"description": "Contents of the stream"}},
)
async def stream(self, request):
infohash = unhexlify(request.match_info["infohash"])
download = self.download_manager.get_download(infohash)
if not download:
return DownloadsEndpoint.return_404(request)
file_index = int(request.match_info["fileindex"])
http_range = request.http_range
start = http_range.start or 0
if download.stream is None:
download.add_stream()
await wait_for(download.stream.enable(file_index, None if start > 0 else 0), 10)
stop = (
download.stream.filesize
if http_range.stop is None
else min(http_range.stop, download.stream.filesize)
)
if (
not start < stop
or not 0 <= start < download.stream.filesize
or not 0 < stop <= download.stream.filesize
):
return RESTResponse("Requested Range Not Satisfiable", status=416)
response = RESTStreamResponse(
status=206,
reason="OK",
headers={
"Accept-Ranges": "bytes",
"Content-Type": "application/octet-stream",
"Content-Length": f"{stop - start}",
"Content-Range": f"{start}-{stop}/{download.stream.filesize}",
},
)
response.force_close()
with suppress(CancelledError, ConnectionResetError):
async with StreamChunk(download.stream, start) as chunk:
await response.prepare(request)
bytes_todo = stop - start
bytes_done = 0
self._logger.info(
"Got range request for %s-%s (%s bytes)", start, stop, bytes_todo
)
while not request.transport.is_closing():
if chunk.seekpos >= download.stream.filesize:
break
data = await chunk.read()
try:
if len(data) == 0:
break
if bytes_done + len(data) > bytes_todo:
# if we have more data than we need
endlen = bytes_todo - bytes_done
if endlen != 0:
await wait_for(
response.write(data[:endlen]), STREAM_PAUSE_TIME
)
bytes_done += endlen
break
await wait_for(response.write(data), STREAM_PAUSE_TIME)
bytes_done += len(data)
if chunk.resume():
self._logger.debug(
"Stream %s-%s is resumed, starting sequential buffer",
start,
stop,
)
except AsyncTimeoutError:
# This means that stream writer has a full buffer, in practice means that
# the client keeps the conenction but sets the window size to 0. In this case
# there is no need to keep sequenial buffer if there are other chunks waiting for prios
if chunk.pause():
self._logger.debug(
"Stream %s-%s is paused, stopping sequential buffer",
start,
stop,
)
return response
|
mtcnn | layer_factory | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# MIT License
#
# Copyright (c) 2018 Iván de Paz Centeno
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from distutils.version import LooseVersion
import tensorflow as tf
__author__ = "Iván de Paz Centeno"
class LayerFactory(object):
"""
Allows to create stack layers for a given network.
"""
AVAILABLE_PADDINGS = ("SAME", "VALID")
def __init__(self, network):
self.__network = network
@staticmethod
def __validate_padding(padding):
if padding not in LayerFactory.AVAILABLE_PADDINGS:
raise Exception("Padding {} not valid".format(padding))
@staticmethod
def __validate_grouping(channels_input: int, channels_output: int, group: int):
if channels_input % group != 0:
raise Exception(
"The number of channels in the input does not match the group"
)
if channels_output % group != 0:
raise Exception(
"The number of channels in the output does not match the group"
)
@staticmethod
def vectorize_input(input_layer):
input_shape = input_layer.get_shape()
if input_shape.ndims == 4:
# Spatial input, must be vectorized.
dim = 1
for x in input_shape[1:].as_list():
dim *= int(x)
# dim = operator.mul(*(input_shape[1:].as_list()))
vectorized_input = tf.reshape(input_layer, [-1, dim])
else:
vectorized_input, dim = (input_layer, input_shape[-1])
return vectorized_input, dim
def __make_var(self, name: str, shape: list):
"""
Creates a tensorflow variable with the given name and shape.
:param name: name to set for the variable.
:param shape: list defining the shape of the variable.
:return: created TF variable.
"""
return tf.compat.v1.get_variable(
name, shape, trainable=self.__network.is_trainable(), use_resource=False
)
def new_feed(self, name: str, layer_shape: tuple):
"""
Creates a feed layer. This is usually the first layer in the network.
:param name: name of the layer
:return:
"""
feed_data = tf.compat.v1.placeholder(tf.float32, layer_shape, "input")
self.__network.add_layer(name, layer_output=feed_data)
def new_conv(
self,
name: str,
kernel_size: tuple,
channels_output: int,
stride_size: tuple,
padding: str = "SAME",
group: int = 1,
biased: bool = True,
relu: bool = True,
input_layer_name: str = None,
):
"""
Creates a convolution layer for the network.
:param name: name for the layer
:param kernel_size: tuple containing the size of the kernel (Width, Height)
:param channels_output: ¿? Perhaps number of channels in the output? it is used as the bias size.
:param stride_size: tuple containing the size of the stride (Width, Height)
:param padding: Type of padding. Available values are: ('SAME', 'VALID')
:param group: groups for the kernel operation. More info required.
:param biased: boolean flag to set if biased or not.
:param relu: boolean flag to set if ReLu should be applied at the end of the layer or not.
:param input_layer_name: name of the input layer for this layer. If None, it will take the last added layer of
the network.
"""
# Verify that the padding is acceptable
self.__validate_padding(padding)
input_layer = self.__network.get_layer(input_layer_name)
# Get the number of channels in the input
channels_input = int(input_layer.get_shape()[-1])
# Verify that the grouping parameter is valid
self.__validate_grouping(channels_input, channels_output, group)
# Convolution for a given input and kernel
convolve = lambda input_val, kernel: tf.nn.conv2d(
input=input_val,
filters=kernel,
strides=[1, stride_size[1], stride_size[0], 1],
padding=padding,
)
with tf.compat.v1.variable_scope(name) as scope:
kernel = self.__make_var(
"weights",
shape=[
kernel_size[1],
kernel_size[0],
channels_input // group,
channels_output,
],
)
output = convolve(input_layer, kernel)
# Add the biases, if required
if biased:
biases = self.__make_var("biases", [channels_output])
output = tf.nn.bias_add(output, biases)
# Apply ReLU non-linearity, if required
if relu:
output = tf.nn.relu(output, name=scope.name)
self.__network.add_layer(name, layer_output=output)
def new_prelu(self, name: str, input_layer_name: str = None):
"""
Creates a new prelu layer with the given name and input.
:param name: name for this layer.
:param input_layer_name: name of the layer that serves as input for this one.
"""
input_layer = self.__network.get_layer(input_layer_name)
with tf.compat.v1.variable_scope(name):
channels_input = int(input_layer.get_shape()[-1])
alpha = self.__make_var("alpha", shape=[channels_input])
output = tf.nn.relu(input_layer) + tf.multiply(
alpha, -tf.nn.relu(-input_layer)
)
self.__network.add_layer(name, layer_output=output)
def new_max_pool(
self,
name: str,
kernel_size: tuple,
stride_size: tuple,
padding="SAME",
input_layer_name: str = None,
):
"""
Creates a new max pooling layer.
:param name: name for the layer.
:param kernel_size: tuple containing the size of the kernel (Width, Height)
:param stride_size: tuple containing the size of the stride (Width, Height)
:param padding: Type of padding. Available values are: ('SAME', 'VALID')
:param input_layer_name: name of the input layer for this layer. If None, it will take the last added layer of
the network.
"""
self.__validate_padding(padding)
input_layer = self.__network.get_layer(input_layer_name)
output = tf.nn.max_pool2d(
input=input_layer,
ksize=[1, kernel_size[1], kernel_size[0], 1],
strides=[1, stride_size[1], stride_size[0], 1],
padding=padding,
name=name,
)
self.__network.add_layer(name, layer_output=output)
def new_fully_connected(
self, name: str, output_count: int, relu=True, input_layer_name: str = None
):
"""
Creates a new fully connected layer.
:param name: name for the layer.
:param output_count: number of outputs of the fully connected layer.
:param relu: boolean flag to set if ReLu should be applied at the end of this layer.
:param input_layer_name: name of the input layer for this layer. If None, it will take the last added layer of
the network.
"""
with tf.compat.v1.variable_scope(name):
input_layer = self.__network.get_layer(input_layer_name)
vectorized_input, dimension = self.vectorize_input(input_layer)
weights = self.__make_var("weights", shape=[dimension, output_count])
biases = self.__make_var("biases", shape=[output_count])
operation = (
tf.compat.v1.nn.relu_layer if relu else tf.compat.v1.nn.xw_plus_b
)
fc = operation(vectorized_input, weights, biases, name=name)
self.__network.add_layer(name, layer_output=fc)
def new_softmax(self, name, axis, input_layer_name: str = None):
"""
Creates a new softmax layer
:param name: name to set for the layer
:param axis:
:param input_layer_name: name of the input layer for this layer. If None, it will take the last added layer of
the network.
"""
input_layer = self.__network.get_layer(input_layer_name)
if LooseVersion(tf.__version__) < LooseVersion("1.5.0"):
max_axis = tf.reduce_max(input_tensor=input_layer, axis=axis, keepdims=True)
target_exp = tf.exp(input_layer - max_axis)
normalize = tf.reduce_sum(input_tensor=target_exp, axis=axis, keepdims=True)
else:
max_axis = tf.reduce_max(input_tensor=input_layer, axis=axis, keepdims=True)
target_exp = tf.exp(input_layer - max_axis)
normalize = tf.reduce_sum(input_tensor=target_exp, axis=axis, keepdims=True)
softmax = tf.math.divide(target_exp, normalize, name)
self.__network.add_layer(name, layer_output=softmax)
|
booster | remove | import eos.db
import gui.mainFrame
import wx
from gui import globalEvents as GE
from gui.fitCommands.calc.booster.remove import CalcRemoveBoosterCommand
from gui.fitCommands.helpers import InternalCommandHistory
from service.fit import Fit
from service.market import Market
class GuiRemoveBoostersCommand(wx.Command):
def __init__(self, fitID, positions):
wx.Command.__init__(self, True, "Remove Boosters")
self.internalHistory = InternalCommandHistory()
self.fitID = fitID
self.positions = positions
def Do(self):
sMkt = Market.getInstance()
results = []
for position in sorted(self.positions, reverse=True):
cmd = CalcRemoveBoosterCommand(fitID=self.fitID, position=position)
results.append(self.internalHistory.submit(cmd))
sMkt.storeRecentlyUsed(cmd.savedBoosterInfo.itemID)
success = any(results)
eos.db.flush()
sFit = Fit.getInstance()
sFit.recalc(self.fitID)
sFit.fill(self.fitID)
eos.db.commit()
wx.PostEvent(
gui.mainFrame.MainFrame.getInstance(), GE.FitChanged(fitIDs=(self.fitID,))
)
return success
def Undo(self):
success = self.internalHistory.undoAll()
eos.db.flush()
sFit = Fit.getInstance()
sFit.recalc(self.fitID)
sFit.fill(self.fitID)
eos.db.commit()
wx.PostEvent(
gui.mainFrame.MainFrame.getInstance(), GE.FitChanged(fitIDs=(self.fitID,))
)
return success
|
misc | consolewidget | # SPDX-FileCopyrightText: Florian Bruhin (The Compiler) <mail@qutebrowser.org>
#
# SPDX-License-Identifier: GPL-3.0-or-later
"""Debugging console."""
import code
import sys
from typing import MutableSequence
from qutebrowser.config import stylesheet
from qutebrowser.misc import cmdhistory, miscwidgets
from qutebrowser.qt.core import Qt, pyqtSignal, pyqtSlot
from qutebrowser.qt.gui import QTextCursor
from qutebrowser.qt.widgets import QApplication, QTextEdit, QVBoxLayout, QWidget
from qutebrowser.utils import objreg, utils
console_widget = None
class ConsoleLineEdit(miscwidgets.CommandLineEdit):
"""A QLineEdit which executes entered code and provides a history.
Attributes:
_history: The command history of executed commands.
Signals:
execute: Emitted when a commandline should be executed.
"""
execute = pyqtSignal(str)
def __init__(self, _namespace, parent):
"""Constructor.
Args:
_namespace: The local namespace of the interpreter.
"""
super().__init__(parent=parent)
self._history = cmdhistory.History(parent=self)
self.returnPressed.connect(self.on_return_pressed)
@pyqtSlot()
def on_return_pressed(self):
"""Execute the line of code which was entered."""
self._history.stop()
text = self.text()
if text:
self._history.append(text)
self.execute.emit(text)
self.setText("")
def history_prev(self):
"""Go back in the history."""
try:
if not self._history.is_browsing():
item = self._history.start(self.text().strip())
else:
item = self._history.previtem()
except (cmdhistory.HistoryEmptyError, cmdhistory.HistoryEndReachedError):
return
self.setText(item)
def history_next(self):
"""Go forward in the history."""
if not self._history.is_browsing():
return
try:
item = self._history.nextitem()
except cmdhistory.HistoryEndReachedError:
return
self.setText(item)
def keyPressEvent(self, e):
"""Override keyPressEvent to handle special keypresses."""
if e.key() == Qt.Key.Key_Up:
self.history_prev()
e.accept()
elif e.key() == Qt.Key.Key_Down:
self.history_next()
e.accept()
elif (
e.modifiers() & Qt.KeyboardModifier.ControlModifier
and e.key() == Qt.Key.Key_C
):
self.setText("")
e.accept()
else:
super().keyPressEvent(e)
class ConsoleTextEdit(QTextEdit):
"""Custom QTextEdit for console output."""
def __init__(self, parent=None):
super().__init__(parent)
self.setAcceptRichText(False)
self.setReadOnly(True)
self.setFocusPolicy(Qt.FocusPolicy.ClickFocus)
def __repr__(self):
return utils.get_repr(self)
def append_text(self, text):
"""Append new text and scroll output to bottom.
We can't use Qt's way to append stuff because that inserts weird
newlines.
"""
self.moveCursor(QTextCursor.MoveOperation.End)
self.insertPlainText(text)
scrollbar = self.verticalScrollBar()
assert scrollbar is not None
scrollbar.setValue(scrollbar.maximum())
class ConsoleWidget(QWidget):
"""A widget with an interactive Python console.
Attributes:
_lineedit: The line edit in the console.
_output: The output widget in the console.
_vbox: The layout which contains everything.
_more: A flag which is set when more input is expected.
_buffer: The buffer for multi-line commands.
_interpreter: The InteractiveInterpreter to execute code with.
"""
STYLESHEET = """
ConsoleWidget > ConsoleTextEdit, ConsoleWidget > ConsoleLineEdit {
font: {{ conf.fonts.debug_console }};
}
"""
def __init__(self, parent=None):
super().__init__(parent)
if not hasattr(sys, "ps1"):
sys.ps1 = ">>> "
if not hasattr(sys, "ps2"):
sys.ps2 = "... "
namespace = {
"__name__": "__console__",
"__doc__": None,
"q_app": QApplication.instance(),
# We use parent as self here because the user "feels" the whole
# console, not just the line edit.
"self": parent,
"objreg": objreg,
}
self._more = False
self._buffer: MutableSequence[str] = []
self._lineedit = ConsoleLineEdit(namespace, self)
self._lineedit.execute.connect(self.push)
self._output = ConsoleTextEdit()
self.write(self._curprompt())
self._vbox = QVBoxLayout()
self._vbox.setSpacing(0)
self._vbox.addWidget(self._output)
self._vbox.addWidget(self._lineedit)
stylesheet.set_register(self)
self.setLayout(self._vbox)
self._lineedit.setFocus()
self._interpreter = code.InteractiveInterpreter(namespace)
def __repr__(self):
return utils.get_repr(self, visible=self.isVisible())
def write(self, line):
"""Write a line of text (without added newline) to the output."""
self._output.append_text(line)
@pyqtSlot(str)
def push(self, line):
"""Push a line to the interpreter."""
self._buffer.append(line)
source = "\n".join(self._buffer)
self.write(line + "\n")
# We do two special things with the context managers here:
# - We replace stdout/stderr to capture output. Even if we could
# override InteractiveInterpreter's write method, most things are
# printed elsewhere (e.g. by exec). Other Python GUI shells do the
# same.
# - We disable our exception hook, so exceptions from the console get
# printed and don't open a crashdialog.
with utils.fake_io(self.write), utils.disabled_excepthook():
self._more = self._interpreter.runsource(source, "<console>")
self.write(self._curprompt())
if not self._more:
self._buffer = []
def _curprompt(self):
"""Get the prompt which is visible currently."""
return sys.ps2 if self._more else sys.ps1
def init():
"""Initialize a global console."""
global console_widget
console_widget = ConsoleWidget()
|
modes | connectionmanager | #
# Copyright (C) 2011 Nick Lanham <nick@afternight.org>
#
# This file is part of Deluge and is licensed under GNU General Public License 3.0, or later, with
# the additional special exception to link portions of this program with the OpenSSL library.
# See LICENSE for more details.
#
import logging
import deluge.component as component
from deluge.decorators import overrides
from deluge.ui.console.modes.basemode import BaseMode
from deluge.ui.console.utils.curses_util import is_printable_chr
from deluge.ui.console.widgets.popup import InputPopup, PopupsHandler, SelectablePopup
from deluge.ui.hostlist import HostList
try:
import curses
except ImportError:
pass
log = logging.getLogger(__name__)
class ConnectionManager(BaseMode, PopupsHandler):
def __init__(self, stdscr, encoding=None):
PopupsHandler.__init__(self)
self.statuses = {}
self.all_torrents = None
self.hostlist = HostList()
BaseMode.__init__(self, stdscr, encoding=encoding)
def update_select_host_popup(self):
if self.popup and not isinstance(self.popup, SelectablePopup):
# Ignore MessagePopup on popup stack upon connect fail
return
selected_index = self.popup.current_selection() if self.popup else None
popup = SelectablePopup(
self,
_("Select Host"),
self._host_selected,
border_off_west=1,
active_wrap=True,
)
popup.add_header(
"{!white,black,bold!}'Q'=%s, 'a'=%s, 'D'=%s"
% (_("Quit"), _("Add Host"), _("Delete Host")),
space_below=True,
)
for host_entry in self.hostlist.get_hosts_info():
host_id, hostname, port, user = host_entry
host_status = self.statuses.get(host_id)
state = host_status[1] if host_status else "Offline"
state_color = "green" if state in ("Online", "Connected") else "red"
host_str = f"{hostname}:{port} [{state}]"
args = {"data": host_id, "foreground": state_color}
popup.add_line(
host_id, host_str, selectable=True, use_underline=True, **args
)
if selected_index:
popup.set_selection(selected_index)
self.push_popup(popup, clear=True)
self.inlist = True
self.refresh()
def update_hosts_status(self):
def on_host_status(status_info):
self.statuses[status_info[0]] = status_info
self.update_select_host_popup()
for host_entry in self.hostlist.get_hosts_info():
self.hostlist.get_host_status(host_entry[0]).addCallback(on_host_status)
def _on_connected(self, result):
def on_console_start(result):
component.get("ConsoleUI").set_mode("TorrentList")
d = component.get("ConsoleUI").start_console()
d.addCallback(on_console_start)
def _on_connect_fail(self, result):
self.report_message("Failed to connect!", result.getErrorMessage())
self.refresh()
if hasattr(result, "getTraceback"):
log.exception(result)
def _host_selected(self, selected_host, *args, **kwargs):
if selected_host in self.statuses:
d = self.hostlist.connect_host(selected_host)
d.addCallback(self._on_connected)
d.addErrback(self._on_connect_fail)
def _do_add(self, result, **kwargs):
if not result or kwargs.get("close", False):
self.pop_popup()
else:
self.add_host(
result["hostname"]["value"],
result["port"]["value"],
result["username"]["value"],
result["password"]["value"],
)
def add_popup(self):
self.inlist = False
popup = InputPopup(
self,
_("Add Host (Up & Down arrows to navigate, Esc to cancel)"),
border_off_north=1,
border_off_east=1,
close_cb=self._do_add,
)
popup.add_text_input("hostname", _("Hostname:"))
popup.add_text_input("port", _("Port:"))
popup.add_text_input("username", _("Username:"))
popup.add_text_input("password", _("Password:"))
self.push_popup(popup, clear=True)
self.refresh()
def add_host(self, hostname, port, username, password):
log.info("Adding host: %s", hostname)
if port.isdecimal():
port = int(port)
try:
self.hostlist.add_host(hostname, port, username, password)
except ValueError as ex:
self.report_message(_("Error adding host"), f"{hostname}: {ex}")
else:
self.pop_popup()
def delete_host(self, host_id):
log.info("Deleting host: %s", host_id)
self.hostlist.remove_host(host_id)
self.update_select_host_popup()
@overrides(component.Component)
def start(self):
self.refresh()
@overrides(component.Component)
def update(self):
self.update_hosts_status()
@overrides(BaseMode)
def pause(self):
self.pop_popup()
BaseMode.pause(self)
@overrides(BaseMode)
def resume(self):
BaseMode.resume(self)
self.refresh()
@overrides(BaseMode)
def refresh(self):
if self.mode_paused():
return
self.stdscr.erase()
self.draw_statusbars()
self.stdscr.noutrefresh()
if not self.popup:
self.update_select_host_popup()
if self.popup:
self.popup.refresh()
curses.doupdate()
@overrides(BaseMode)
def on_resize(self, rows, cols):
BaseMode.on_resize(self, rows, cols)
if self.popup:
self.popup.handle_resize()
self.stdscr.erase()
self.refresh()
@overrides(BaseMode)
def read_input(self):
c = self.stdscr.getch()
if is_printable_chr(c):
if chr(c) == "Q":
component.get("ConsoleUI").quit()
elif self.inlist:
if chr(c) == "q":
return
elif chr(c) == "D":
host_index = self.popup.current_selection()
host_id = self.popup.inputs[host_index].name
self.delete_host(host_id)
return
elif chr(c) == "a":
self.add_popup()
return
if self.popup:
if self.popup.handle_read(c) and self.popup.closed():
self.pop_popup()
self.refresh()
|
extractor | mediasite | # coding: utf-8
from __future__ import unicode_literals
import json
import re
from ..compat import compat_str, compat_urlparse
from ..utils import (
ExtractorError,
float_or_none,
mimetype2ext,
str_or_none,
try_get,
unescapeHTML,
unsmuggle_url,
url_or_none,
urljoin,
)
from .common import InfoExtractor
_ID_RE = r"(?:[0-9a-f]{32,34}|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12,14})"
class MediasiteIE(InfoExtractor):
_VALID_URL = (
r"(?xi)https?://[^/]+/Mediasite/(?:Play|Showcase/(?:default|livebroadcast)/Presentation)/(?P<id>%s)(?P<query>\?[^#]+|)"
% _ID_RE
)
_TESTS = [
{
"url": "https://hitsmediaweb.h-its.org/mediasite/Play/2db6c271681e4f199af3c60d1f82869b1d",
"info_dict": {
"id": "2db6c271681e4f199af3c60d1f82869b1d",
"ext": "mp4",
"title": "Lecture: Tuesday, September 20, 2016 - Sir Andrew Wiles",
"description": "Sir Andrew Wiles: “Equations in arithmetic”\\n\\nI will describe some of the interactions between modern number theory and the problem of solving equations in rational numbers or integers\\u0027.",
"timestamp": 1474268400.0,
"upload_date": "20160919",
},
},
{
"url": "http://mediasite.uib.no/Mediasite/Play/90bb363295d945d6b548c867d01181361d?catalog=a452b7df-9ae1-46b7-a3ba-aceeb285f3eb",
"info_dict": {
"id": "90bb363295d945d6b548c867d01181361d",
"ext": "mp4",
"upload_date": "20150429",
"title": "5) IT-forum 2015-Dag 1 - Dungbeetle - How and why Rain created a tiny bug tracker for Unity",
"timestamp": 1430311380.0,
},
},
{
"url": "https://collegerama.tudelft.nl/Mediasite/Play/585a43626e544bdd97aeb71a0ec907a01d",
"md5": "481fda1c11f67588c0d9d8fbdced4e39",
"info_dict": {
"id": "585a43626e544bdd97aeb71a0ec907a01d",
"ext": "mp4",
"title": "Een nieuwe wereld: waarden, bewustzijn en techniek van de mensheid 2.0.",
"description": "",
"thumbnail": r"re:^https?://.*\.jpg(?:\?.*)?$",
"duration": 7713.088,
"timestamp": 1413309600,
"upload_date": "20141014",
},
},
{
"url": "https://collegerama.tudelft.nl/Mediasite/Play/86a9ea9f53e149079fbdb4202b521ed21d?catalog=fd32fd35-6c99-466c-89d4-cd3c431bc8a4",
"md5": "ef1fdded95bdf19b12c5999949419c92",
"info_dict": {
"id": "86a9ea9f53e149079fbdb4202b521ed21d",
"ext": "wmv",
"title": "64ste Vakantiecursus: Afvalwater",
"description": "md5:7fd774865cc69d972f542b157c328305",
"thumbnail": r"re:^https?://.*\.jpg(?:\?.*?)?$",
"duration": 10853,
"timestamp": 1326446400,
"upload_date": "20120113",
},
},
{
"url": "http://digitalops.sandia.gov/Mediasite/Play/24aace4429fc450fb5b38cdbf424a66e1d",
"md5": "9422edc9b9a60151727e4b6d8bef393d",
"info_dict": {
"id": "24aace4429fc450fb5b38cdbf424a66e1d",
"ext": "mp4",
"title": "Xyce Software Training - Section 1",
"description": r"re:(?s)SAND Number: SAND 2013-7800.{200,}",
"upload_date": "20120409",
"timestamp": 1333983600,
"duration": 7794,
},
},
{
"url": "https://collegerama.tudelft.nl/Mediasite/Showcase/livebroadcast/Presentation/ada7020854f743c49fbb45c9ec7dbb351d",
"only_matching": True,
},
{
"url": "https://mediasite.ntnu.no/Mediasite/Showcase/default/Presentation/7d8b913259334b688986e970fae6fcb31d",
"only_matching": True,
},
{
# dashed id
"url": "https://hitsmediaweb.h-its.org/mediasite/Play/2db6c271-681e-4f19-9af3-c60d1f82869b1d",
"only_matching": True,
},
]
# look in Mediasite.Core.js (Mediasite.ContentStreamType[*])
_STREAM_TYPES = {
0: "video1", # the main video
2: "slide",
3: "presentation",
4: "video2", # screencast?
5: "video3",
}
@staticmethod
def _extract_urls(webpage):
return [
unescapeHTML(mobj.group("url"))
for mobj in re.finditer(
r'(?xi)<iframe\b[^>]+\bsrc=(["\'])(?P<url>(?:(?:https?:)?//[^/]+)?/Mediasite/Play/%s(?:\?.*?)?)\1'
% _ID_RE,
webpage,
)
]
def _real_extract(self, url):
url, data = unsmuggle_url(url, {})
mobj = re.match(self._VALID_URL, url)
resource_id = mobj.group("id")
query = mobj.group("query")
webpage, urlh = self._download_webpage_handle(
url, resource_id
) # XXX: add UrlReferrer?
redirect_url = urlh.geturl()
# XXX: might have also extracted UrlReferrer and QueryString from the html
service_path = compat_urlparse.urljoin(
redirect_url,
self._html_search_regex(
r'<div[^>]+\bid=["\']ServicePath[^>]+>(.+?)</div>',
webpage,
resource_id,
default="/Mediasite/PlayerService/PlayerService.svc/json",
),
)
player_options = self._download_json(
"%s/GetPlayerOptions" % service_path,
resource_id,
headers={
"Content-type": "application/json; charset=utf-8",
"X-Requested-With": "XMLHttpRequest",
},
data=json.dumps(
{
"getPlayerOptionsRequest": {
"ResourceId": resource_id,
"QueryString": query,
"UrlReferrer": data.get("UrlReferrer", ""),
"UseScreenReader": False,
}
}
).encode("utf-8"),
)["d"]
presentation = player_options["Presentation"]
title = presentation["Title"]
if presentation is None:
raise ExtractorError(
"Mediasite says: %s"
% player_options["PlayerPresentationStatusMessage"],
expected=True,
)
thumbnails = []
formats = []
for snum, Stream in enumerate(presentation["Streams"]):
stream_type = Stream.get("StreamType")
if stream_type is None:
continue
video_urls = Stream.get("VideoUrls")
if not isinstance(video_urls, list):
video_urls = []
stream_id = self._STREAM_TYPES.get(stream_type, "type%u" % stream_type)
stream_formats = []
for unum, VideoUrl in enumerate(video_urls):
video_url = url_or_none(VideoUrl.get("Location"))
if not video_url:
continue
# XXX: if Stream.get('CanChangeScheme', False), switch scheme to HTTP/HTTPS
media_type = VideoUrl.get("MediaType")
if media_type == "SS":
stream_formats.extend(
self._extract_ism_formats(
video_url,
resource_id,
ism_id="%s-%u.%u" % (stream_id, snum, unum),
fatal=False,
)
)
elif media_type == "Dash":
stream_formats.extend(
self._extract_mpd_formats(
video_url,
resource_id,
mpd_id="%s-%u.%u" % (stream_id, snum, unum),
fatal=False,
)
)
else:
stream_formats.append(
{
"format_id": "%s-%u.%u" % (stream_id, snum, unum),
"url": video_url,
"ext": mimetype2ext(VideoUrl.get("MimeType")),
}
)
# TODO: if Stream['HasSlideContent']:
# synthesise an MJPEG video stream '%s-%u.slides' % (stream_type, snum)
# from Stream['Slides']
# this will require writing a custom downloader...
# disprefer 'secondary' streams
if stream_type != 0:
for fmt in stream_formats:
fmt["preference"] = -1
thumbnail_url = Stream.get("ThumbnailUrl")
if thumbnail_url:
thumbnails.append(
{
"id": "%s-%u" % (stream_id, snum),
"url": urljoin(redirect_url, thumbnail_url),
"preference": -1 if stream_type != 0 else 0,
}
)
formats.extend(stream_formats)
self._sort_formats(formats)
# XXX: Presentation['Presenters']
# XXX: Presentation['Transcript']
return {
"id": resource_id,
"title": title,
"description": presentation.get("Description"),
"duration": float_or_none(presentation.get("Duration"), 1000),
"timestamp": float_or_none(presentation.get("UnixTime"), 1000),
"formats": formats,
"thumbnails": thumbnails,
}
class MediasiteCatalogIE(InfoExtractor):
_VALID_URL = r"""(?xi)
(?P<url>https?://[^/]+/Mediasite)
/Catalog/Full/
(?P<catalog_id>{0})
(?:
/(?P<current_folder_id>{0})
/(?P<root_dynamic_folder_id>{0})
)?
""".format(_ID_RE)
_TESTS = [
{
"url": "http://events7.mediasite.com/Mediasite/Catalog/Full/631f9e48530d454381549f955d08c75e21",
"info_dict": {
"id": "631f9e48530d454381549f955d08c75e21",
"title": "WCET Summit: Adaptive Learning in Higher Ed: Improving Outcomes Dynamically",
},
"playlist_count": 6,
"expected_warnings": ["is not a supported codec"],
},
{
# with CurrentFolderId and RootDynamicFolderId
"url": "https://medaudio.medicine.iu.edu/Mediasite/Catalog/Full/9518c4a6c5cf4993b21cbd53e828a92521/97a9db45f7ab47428c77cd2ed74bb98f14/9518c4a6c5cf4993b21cbd53e828a92521",
"info_dict": {
"id": "9518c4a6c5cf4993b21cbd53e828a92521",
"title": "IUSM Family and Friends Sessions",
},
"playlist_count": 2,
},
{
"url": "http://uipsyc.mediasite.com/mediasite/Catalog/Full/d5d79287c75243c58c50fef50174ec1b21",
"only_matching": True,
},
{
# no AntiForgeryToken
"url": "https://live.libraries.psu.edu/Mediasite/Catalog/Full/8376d4b24dd1457ea3bfe4cf9163feda21",
"only_matching": True,
},
{
"url": "https://medaudio.medicine.iu.edu/Mediasite/Catalog/Full/9518c4a6c5cf4993b21cbd53e828a92521/97a9db45f7ab47428c77cd2ed74bb98f14/9518c4a6c5cf4993b21cbd53e828a92521",
"only_matching": True,
},
{
# dashed id
"url": "http://events7.mediasite.com/Mediasite/Catalog/Full/631f9e48-530d-4543-8154-9f955d08c75e",
"only_matching": True,
},
]
def _real_extract(self, url):
mobj = re.match(self._VALID_URL, url)
mediasite_url = mobj.group("url")
catalog_id = mobj.group("catalog_id")
current_folder_id = mobj.group("current_folder_id") or catalog_id
root_dynamic_folder_id = mobj.group("root_dynamic_folder_id")
webpage = self._download_webpage(url, catalog_id)
# AntiForgeryToken is optional (e.g. [1])
# 1. https://live.libraries.psu.edu/Mediasite/Catalog/Full/8376d4b24dd1457ea3bfe4cf9163feda21
anti_forgery_token = self._search_regex(
r'AntiForgeryToken\s*:\s*(["\'])(?P<value>(?:(?!\1).)+)\1',
webpage,
"anti forgery token",
default=None,
group="value",
)
if anti_forgery_token:
anti_forgery_header = self._search_regex(
r'AntiForgeryHeaderName\s*:\s*(["\'])(?P<value>(?:(?!\1).)+)\1',
webpage,
"anti forgery header name",
default="X-SOFO-AntiForgeryHeader",
group="value",
)
data = {
"IsViewPage": True,
"IsNewFolder": True,
"AuthTicket": None,
"CatalogId": catalog_id,
"CurrentFolderId": current_folder_id,
"RootDynamicFolderId": root_dynamic_folder_id,
"ItemsPerPage": 1000,
"PageIndex": 0,
"PermissionMask": "Execute",
"CatalogSearchType": "SearchInFolder",
"SortBy": "Date",
"SortDirection": "Descending",
"StartDate": None,
"EndDate": None,
"StatusFilterList": None,
"PreviewKey": None,
"Tags": [],
}
headers = {
"Content-Type": "application/json; charset=UTF-8",
"Referer": url,
"X-Requested-With": "XMLHttpRequest",
}
if anti_forgery_token:
headers[anti_forgery_header] = anti_forgery_token
catalog = self._download_json(
"%s/Catalog/Data/GetPresentationsForFolder" % mediasite_url,
catalog_id,
data=json.dumps(data).encode(),
headers=headers,
)
entries = []
for video in catalog["PresentationDetailsList"]:
if not isinstance(video, dict):
continue
video_id = str_or_none(video.get("Id"))
if not video_id:
continue
entries.append(
self.url_result(
"%s/Play/%s" % (mediasite_url, video_id),
ie=MediasiteIE.ie_key(),
video_id=video_id,
)
)
title = try_get(catalog, lambda x: x["CurrentFolder"]["Name"], compat_str)
return self.playlist_result(
entries,
catalog_id,
title,
)
class MediasiteNamedCatalogIE(InfoExtractor):
_VALID_URL = r"(?xi)(?P<url>https?://[^/]+/Mediasite)/Catalog/catalogs/(?P<catalog_name>[^/?#&]+)"
_TESTS = [
{
"url": "https://msite.misis.ru/Mediasite/Catalog/catalogs/2016-industrial-management-skriabin-o-o",
"only_matching": True,
}
]
def _real_extract(self, url):
mobj = re.match(self._VALID_URL, url)
mediasite_url = mobj.group("url")
catalog_name = mobj.group("catalog_name")
webpage = self._download_webpage(url, catalog_name)
catalog_id = self._search_regex(
r'CatalogId\s*:\s*["\'](%s)' % _ID_RE, webpage, "catalog id"
)
return self.url_result(
"%s/Catalog/Full/%s" % (mediasite_url, catalog_id),
ie=MediasiteCatalogIE.ie_key(),
video_id=catalog_id,
)
|
extractor | huffpost | from __future__ import unicode_literals
import re
from ..utils import determine_ext, parse_duration, unified_strdate
from .common import InfoExtractor
class HuffPostIE(InfoExtractor):
IE_DESC = "Huffington Post"
_VALID_URL = r"""(?x)
https?://(embed\.)?live\.huffingtonpost\.com/
(?:
r/segment/[^/]+/|
HPLEmbedPlayer/\?segmentId=
)
(?P<id>[0-9a-f]+)"""
_TEST = {
"url": "http://live.huffingtonpost.com/r/segment/legalese-it/52dd3e4b02a7602131000677",
"md5": "55f5e8981c1c80a64706a44b74833de8",
"info_dict": {
"id": "52dd3e4b02a7602131000677",
"ext": "mp4",
"title": "Legalese It! with @MikeSacksHP",
"description": "This week on Legalese It, Mike talks to David Bosco about his new book on the ICC, \"Rough Justice,\" he also discusses the Virginia AG's historic stance on gay marriage, the execution of Edgar Tamayo, the ICC's delay of Kenya's President and more. ",
"duration": 1549,
"upload_date": "20140124",
},
"params": {
# m3u8 download
"skip_download": True,
},
"expected_warnings": ["HTTP Error 404: Not Found"],
}
def _real_extract(self, url):
video_id = self._match_id(url)
api_url = "http://embed.live.huffingtonpost.com/api/segments/%s.json" % video_id
data = self._download_json(api_url, video_id)["data"]
video_title = data["title"]
duration = parse_duration(data.get("running_time"))
upload_date = unified_strdate(
data.get("schedule", {}).get("starts_at")
or data.get("segment_start_date_time")
)
description = data.get("description")
thumbnails = []
for url in filter(None, data["images"].values()):
m = re.match(r".*-([0-9]+x[0-9]+)\.", url)
if not m:
continue
thumbnails.append(
{
"url": url,
"resolution": m.group(1),
}
)
formats = []
sources = data.get("sources", {})
live_sources = list(sources.get("live", {}).items()) + list(
sources.get("live_again", {}).items()
)
for key, url in live_sources:
ext = determine_ext(url)
if ext == "m3u8":
formats.extend(
self._extract_m3u8_formats(
url, video_id, ext="mp4", m3u8_id="hls", fatal=False
)
)
elif ext == "f4m":
formats.extend(
self._extract_f4m_formats(
url + "?hdcore=2.9.5", video_id, f4m_id="hds", fatal=False
)
)
else:
formats.append(
{
"format": key,
"format_id": key.replace("/", "."),
"ext": "mp4",
"url": url,
"vcodec": "none" if key.startswith("audio/") else None,
}
)
if not formats and data.get("fivemin_id"):
return self.url_result("5min:%s" % data["fivemin_id"])
self._sort_formats(formats)
return {
"id": video_id,
"title": video_title,
"description": description,
"formats": formats,
"duration": duration,
"upload_date": upload_date,
"thumbnails": thumbnails,
}
|
browsers | filesystem | # Copyright 2004-2005 Joe Wreschnig, Michael Urman, Iñigo Serna
# 2012-2022 Nick Boultbee
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
# Some sort of crazy directory-based browser. QL is full of minor hacks
# to support this by automatically adding songs to the library when it
# needs them to be there.
import os
from typing import Iterable, List, TypeVar
from gi.repository import Gdk, Gtk
from quodlibet import _, config, formats, qltk
from quodlibet.browsers import Browser
from quodlibet.library import SongFileLibrary
from quodlibet.qltk import Icons
from quodlibet.qltk.filesel import MainDirectoryTree
from quodlibet.qltk.songsmenu import SongsMenu
from quodlibet.qltk.x import ScrolledWindow
from quodlibet.util import connect_obj, copool
from quodlibet.util.dprint import print_d
from quodlibet.util.library import get_scan_dirs
from quodlibet.util.path import normalize_path
from senf import bytes2fsn, fsn2bytes, fsn2uri
T = TypeVar("T")
class FileSystem(Browser, Gtk.HBox):
__library = None
name = _("File System")
accelerated_name = _("_File System")
keys = ["FileSystem"]
priority = 10
uses_main_library = False
TARGET_QL, TARGET_EXT = range(1, 3)
def pack(self, songpane):
container = qltk.ConfigRHPaned("browsers", "filesystem_pos", 0.4)
container.pack1(self, True, False)
container.pack2(songpane, True, False)
return container
def unpack(self, container, songpane):
container.remove(songpane)
container.remove(self)
@classmethod
def __added(klass, library, songs):
klass.__library.remove(songs)
@classmethod
def init(klass, library):
if klass.__library is not None:
return
klass.__glibrary = library
klass.__library = SongFileLibrary("filesystem")
library.connect("added", klass.__remove_because_added)
@classmethod
def __remove_because_added(klass, library, songs):
songs = klass._only_known(songs)
klass.__library.remove(songs)
@classmethod
def _only_known(cls, songs: Iterable[T]) -> List[T]:
return [s for s in songs if cls.__library.__contains__(s)] # type:ignore
def __init__(self, library):
super().__init__()
sw = ScrolledWindow()
sw.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
sw.set_shadow_type(Gtk.ShadowType.IN)
dt = MainDirectoryTree(folders=get_scan_dirs())
targets = [
("text/x-quodlibet-songs", Gtk.TargetFlags.SAME_APP, self.TARGET_QL),
("text/uri-list", 0, self.TARGET_EXT),
]
targets = [Gtk.TargetEntry.new(*t) for t in targets]
dt.drag_source_set(Gdk.ModifierType.BUTTON1_MASK, targets, Gdk.DragAction.COPY)
dt.connect("drag-data-get", self.__drag_data_get)
sel = dt.get_selection()
sel.unselect_all()
connect_obj(sel, "changed", copool.add, self.__songs_selected, dt)
sel.connect("changed", self._on_selection_changed)
dt.connect("row-activated", lambda *a: self.songs_activated())
sw.add(dt)
self.pack_start(sw, True, True, 0)
self.show_all()
def _on_selection_changed(self, tree_selection):
model, rows = tree_selection.get_selected_rows()
selected_paths = [model[row][0] for row in rows]
if selected_paths:
data = fsn2bytes("\n".join(selected_paths), "utf-8")
else:
data = b""
config.setbytes("browsers", "filesystem", data)
def get_child(self):
return self.get_children()[0].get_child()
def __drag_data_get(self, view, ctx, sel, tid, etime):
model, rows = view.get_selection().get_selected_rows()
dirs = [model[row][0] for row in rows]
for songs in self.__find_songs(view.get_selection()):
pass
if tid == self.TARGET_QL:
cant_add = [s for s in songs if not s.can_add]
if cant_add:
qltk.ErrorMessage(
qltk.get_top_parent(self),
_("Unable to copy songs"),
_(
"The files selected cannot be copied to other "
"song lists or the queue."
),
).run()
ctx.drag_abort(etime)
return
to_add = self._only_known(songs)
self.__add_songs(view, to_add)
qltk.selection_set_songs(sel, songs)
else:
# External target (app) is delivered a list of URIS of songs
uris = list({fsn2uri(dir) for dir in dirs})
print_d("Directories to drop: %s" % dirs)
sel.set_uris(uris)
def can_filter_tag(self, key):
return key == "~dirname"
def filter(self, key, values):
self.get_child().get_selection().unselect_all()
for v in values:
self.get_child().go_to(v)
def scroll(self, song):
self.__select_paths([song("~dirname")])
def restore(self):
data = config.getbytes("browsers", "filesystem", b"")
try:
paths = bytes2fsn(data, "utf-8")
except ValueError:
return
if not paths:
return
self.__select_paths(paths.split("\n"))
def __select_paths(self, paths):
# AudioFile uses normalized paths, DirectoryTree doesn't
paths = list(map(normalize_path, paths))
def select(model, path, iter_, paths_):
(paths, first) = paths_
value = model.get_value(iter_)
if value is None:
return not bool(paths)
value = normalize_path(value)
if value in paths:
self.get_child().get_selection().select_path(path)
paths.remove(value)
if not first:
self.get_child().set_cursor(path)
# copy treepath, gets invalid after the callback
first.append(path.copy())
else:
for fpath in paths:
if fpath.startswith(value):
self.get_child().expand_row(path, False)
return not bool(paths)
# XXX: We expect all paths we want in DirectoryTree to be
# expanded once before
first = []
self.get_child().get_model().foreach(select, (paths, first))
if first:
self.get_child().scroll_to_cell(first[0], None, True, 0.5)
def activate(self):
copool.add(self.__songs_selected, self.get_child())
def Menu(self, songs, library, items):
i = qltk.MenuItem(_("_Add to Library"), Icons.LIST_ADD)
i.set_sensitive(False)
i.connect("activate", self.__add_songs, songs)
for song in songs:
if song not in self.__glibrary:
i.set_sensitive(True)
break
items.append([i])
menu = SongsMenu(
library,
songs,
remove=self.__remove_songs,
delete=True,
queue=True,
items=items,
)
return menu
def __add_songs(self, item, songs):
songs = self._only_known(songs)
self.__library.librarian.move(songs, self.__library, self.__glibrary)
def __remove_songs(self, songs):
songs = [s for s in songs if self.__glibrary.__contains__(s)]
self.__library.librarian.move(songs, self.__glibrary, self.__library)
def __find_songs(self, selection):
model, rows = selection.get_selected_rows()
dirs = [model[row][0] for row in rows]
songs = []
to_add = []
for dir in dirs:
try:
for file in sorted(os.listdir(dir)):
if not formats.filter(file):
continue
raw_path = os.path.join(dir, file)
fn = normalize_path(raw_path, canonicalise=True)
if fn in self.__glibrary:
songs.append(self.__glibrary[fn])
elif fn not in self.__library:
song = formats.MusicFile(fn)
if song:
to_add.append(song)
songs.append(song)
yield songs
if fn in self.__library:
song = self.__library[fn]
if not song.valid():
self.__library.reload(song)
if song in self.__library:
songs.append(song)
except OSError:
pass
self.__library.add(to_add)
yield songs
def __songs_selected(self, view):
if self.get_window():
self.get_window().set_cursor(Gdk.Cursor.new(Gdk.CursorType.WATCH))
for songs in self.__find_songs(view.get_selection()):
yield True
if self.get_window():
self.get_window().set_cursor(None)
self.songs_selected(songs)
browsers = [FileSystem]
|
utils | progress | import os
from collections import deque
from math import floor
from pathlib import PurePath
from shutil import get_terminal_size
from string import Formatter as StringFormatter
from threading import Event, RLock, Thread
from time import time
from typing import Callable, Deque, Dict, Iterable, List, Optional, TextIO, Tuple, Union
from streamlink.compat import is_win32
_stringformatter = StringFormatter()
_TFormat = Iterable[Iterable[Tuple[str, Optional[str], Optional[str], Optional[str]]]]
class ProgressFormatter:
# Store formats as a tuple of lists of parsed format strings,
# so when iterating, we don't have to parse over and over again.
# Reserve at least 15 characters for the path, so it can be truncated with enough useful information.
FORMATS: _TFormat = tuple(
list(_stringformatter.parse(fmt))
for fmt in (
"[download] Written {written} to {path:15} ({elapsed} @ {speed})",
"[download] Written {written} ({elapsed} @ {speed})",
"[download] {written} ({elapsed} @ {speed})",
"[download] {written} ({elapsed})",
"[download] {written}",
)
)
FORMATS_NOSPEED: _TFormat = tuple(
list(_stringformatter.parse(fmt))
for fmt in (
"[download] Written {written} to {path:15} ({elapsed})",
"[download] Written {written} ({elapsed})",
"[download] {written} ({elapsed})",
"[download] {written}",
)
)
# Use U+2026 (HORIZONTAL ELLIPSIS) to be able to distinguish between "." and ".." when truncating relative paths
ELLIPSIS: str = "…"
# widths generated from
# https://www.unicode.org/Public/4.0-Update/EastAsianWidth-4.0.0.txt
# See https://github.com/streamlink/streamlink/pull/2032
WIDTHS: Iterable[Tuple[int, int]] = (
(13, 1),
(15, 0),
(126, 1),
(159, 0),
(687, 1),
(710, 0),
(711, 1),
(727, 0),
(733, 1),
(879, 0),
(1154, 1),
(1161, 0),
(4347, 1),
(4447, 2),
(7467, 1),
(7521, 0),
(8369, 1),
(8426, 0),
(9000, 1),
(9002, 2),
(11021, 1),
(12350, 2),
(12351, 1),
(12438, 2),
(12442, 0),
(19893, 2),
(19967, 1),
(55203, 2),
(63743, 1),
(64106, 2),
(65039, 1),
(65059, 0),
(65131, 2),
(65279, 1),
(65376, 2),
(65500, 1),
(65510, 2),
(120831, 1),
(262141, 2),
(1114109, 1),
)
# On Windows, we need one less space, or we overflow the line for some reason.
gap = 1 if is_win32 else 0
@classmethod
def term_width(cls):
return get_terminal_size().columns - cls.gap
@classmethod
def _get_width(cls, ordinal: int) -> int:
"""Return the width of a specific unicode character when it would be displayed."""
return next((width for unicode, width in cls.WIDTHS if ordinal <= unicode), 1)
@classmethod
def width(cls, value: str):
"""Return the overall width of a string when it would be displayed."""
return sum(map(cls._get_width, map(ord, value)))
@classmethod
def cut(cls, value: str, max_width: int) -> str:
"""Cut off the beginning of a string until its display width fits into the output size."""
current = value
for i in range(len(value)): # pragma: no branch
current = value[i:]
if cls.width(current) <= max_width:
break
return current
@classmethod
def format(cls, formats: _TFormat, params: Dict[str, Union[str, Callable[[int], str]]]) -> str:
term_width = cls.term_width()
static: List[str] = []
variable: List[Tuple[int, Callable[[int], str], int]] = []
for fmt in formats:
static.clear()
variable.clear()
length = 0
# Get literal texts, static segments and variable segments from the parsed format
# and calculate the overall length of the literal texts and static segments after substituting them.
for literal_text, field_name, format_spec, _conversion in fmt:
static.append(literal_text)
length += len(literal_text)
if field_name is None:
continue
if field_name not in params:
break
value_or_callable = params[field_name]
if not callable(value_or_callable):
static.append(value_or_callable)
length += len(value_or_callable)
else:
variable.append((len(static), value_or_callable, int(format_spec or 0)))
static.append("")
else:
# No variable segments? Just check if the resulting string fits into the size constraints.
if not variable:
if length > term_width:
continue
else:
break
# Get the available space for each variable segment (share space equally and round down).
max_width = int((term_width - length) / len(variable))
# If at least one variable segment doesn't fit, continue with the next format.
if max_width < 1 or any(max_width < min_width for _, __, min_width in variable):
continue
# All variable segments fit, so finally format them, but continue with the next format if there's an error.
# noinspection PyBroadException
try:
for idx, fn, _ in variable:
static[idx] = fn(max_width)
except Exception:
continue
break
return "".join(static)
@staticmethod
def _round(num: float, n: int = 2) -> float:
return floor(num * 10**n) / 10**n
@classmethod
def format_filesize(cls, size: float, suffix: str = "") -> str:
if size < 1024:
return f"{size:.0f} bytes{suffix}"
if size < 2**20:
return f"{cls._round(size / 2**10, 2):.2f} KiB{suffix}"
if size < 2**30:
return f"{cls._round(size / 2**20, 2):.2f} MiB{suffix}"
if size < 2**40:
return f"{cls._round(size / 2**30, 2):.2f} GiB{suffix}"
return f"{cls._round(size / 2**40, 2):.2f} TiB{suffix}"
@classmethod
def format_time(cls, elapsed: float) -> str:
elapsed = max(elapsed, 0)
if elapsed < 60:
return f"{int(elapsed % 60):1d}s"
if elapsed < 3600:
return f"{int(elapsed % 3600 / 60):1d}m{int(elapsed % 60):02d}s"
return f"{int(elapsed / 3600)}h{int(elapsed % 3600 / 60):02d}m{int(elapsed % 60):02d}s"
@classmethod
def format_path(cls, path: PurePath, max_width: int) -> str:
# Quick check if the path fits
string = str(path)
width = cls.width(string)
if width <= max_width:
return string
# Since the path doesn't fit, we always need to add an ellipsis.
# On Windows, we also need to add the "drive" part (which is an empty string on PurePosixPath)
max_width -= cls.width(path.drive) + cls.width(cls.ELLIPSIS)
# Ignore the path's first part, aka the "anchor" (drive + root)
parts = os.path.sep.join(path.parts[1:] if path.drive else path.parts)
truncated = cls.cut(parts, max_width)
return f"{path.drive}{cls.ELLIPSIS}{truncated}"
class Progress(Thread):
def __init__(
self,
stream: TextIO,
path: PurePath,
interval: float = 0.25,
history: int = 20,
threshold: int = 2,
):
"""
:param stream: The output stream
:param path: The path that's being written
:param interval: Time in seconds between updates
:param history: Number of seconds of how long download speed history is kept
:param threshold: Number of seconds until download speed is shown
"""
super().__init__(daemon=True)
self._wait = Event()
self._lock = RLock()
self.formatter = ProgressFormatter()
self.stream: TextIO = stream
self.path: PurePath = path
self.interval: float = interval
self.history: Deque[Tuple[float, int]] = deque(maxlen=int(history / interval))
self.threshold: int = int(threshold / interval)
self.started: float = 0.0
self.overall: int = 0
self.written: int = 0
def close(self):
self._wait.set()
def write(self, chunk: bytes):
size = len(chunk)
with self._lock:
self.overall += size
self.written += size
def run(self):
self.started = time()
try:
while not self._wait.wait(self.interval): # pragma: no cover
self.update()
finally:
self.print_end()
def update(self):
with self._lock:
now = time()
formatter = self.formatter
history = self.history
history.append((now, self.written))
self.written = 0
has_history = len(history) >= self.threshold
if not has_history:
formats = formatter.FORMATS_NOSPEED
speed = ""
else:
formats = formatter.FORMATS
speed = formatter.format_filesize(sum(size for _, size in history) / (now - history[0][0]), "/s")
params = dict(
written=formatter.format_filesize(self.overall),
elapsed=formatter.format_time(now - self.started),
speed=speed,
path=lambda max_width: formatter.format_path(self.path, max_width),
)
status = formatter.format(formats, params)
self.print_inplace(status)
def print_inplace(self, msg: str):
"""Clears the previous line and prints a new one."""
term_width = self.formatter.term_width()
spacing = term_width - self.formatter.width(msg)
self.stream.write(f"\r{msg}{' ' * max(0, spacing)}")
self.stream.flush()
def print_end(self):
self.stream.write("\n")
self.stream.flush()
|
examples | pyqt_histogram_f | #!/usr/bin/env python
#
# Copyright 2013,2015 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# SPDX-License-Identifier: GPL-3.0-or-later
#
#
import sys
from gnuradio import blocks, gr
try:
import sip
from gnuradio import qtgui
from PyQt5 import Qt, QtWidgets
except ImportError:
sys.stderr.write("Error: Program requires PyQt5 and gr-qtgui.\n")
sys.exit(1)
try:
from gnuradio import analog
except ImportError:
sys.stderr.write("Error: Program requires gr-analog.\n")
sys.exit(1)
class dialog_box(QtWidgets.QWidget):
def __init__(self, display, control):
QtWidgets.QWidget.__init__(self, None)
self.setWindowTitle("PyQt Test GUI")
self.boxlayout = QtWidgets.QBoxLayout(QtWidgets.QBoxLayout.LeftToRight, self)
self.boxlayout.addWidget(display, 1)
self.boxlayout.addWidget(control)
self.resize(800, 500)
class control_box(QtWidgets.QWidget):
def __init__(self, snk, parent=None):
QtWidgets.QWidget.__init__(self, parent)
self.setWindowTitle("Control Panel")
self.snk = snk
self.setToolTip("Control the signals")
QtWidgets.QToolTip.setFont(Qt.QFont("OldEnglish", 10))
self.layout = QtWidgets.QFormLayout(self)
# Control the first signal
self.freq1Edit = QtWidgets.QLineEdit(self)
self.freq1Edit.setMinimumWidth(100)
self.layout.addRow("Sine Frequency:", self.freq1Edit)
self.freq1Edit.editingFinished.connect(self.freq1EditText)
self.amp1Edit = QtWidgets.QLineEdit(self)
self.amp1Edit.setMinimumWidth(100)
self.layout.addRow("Sine Amplitude:", self.amp1Edit)
self.amp1Edit.editingFinished.connect(self.amp1EditText)
# Control the second signal
self.amp2Edit = QtWidgets.QLineEdit(self)
self.amp2Edit.setMinimumWidth(100)
self.layout.addRow("Noise Amplitude:", self.amp2Edit)
self.amp2Edit.editingFinished.connect(self.amp2EditText)
# Control the histogram
self.hist_npts = QtWidgets.QLineEdit(self)
self.hist_npts.setMinimumWidth(100)
self.hist_npts.setValidator(Qt.QIntValidator(0, 8191))
self.hist_npts.setText("{0}".format(self.snk.nsamps()))
self.layout.addRow("Number of Points:", self.hist_npts)
self.hist_npts.editingFinished.connect(self.set_nsamps)
self.hist_bins = QtWidgets.QLineEdit(self)
self.hist_bins.setMinimumWidth(100)
self.hist_bins.setValidator(Qt.QIntValidator(0, 1000))
self.hist_bins.setText("{0}".format(self.snk.bins()))
self.layout.addRow("Number of Bins:", self.hist_bins)
self.hist_bins.editingFinished.connect(self.set_bins)
self.hist_auto = QtWidgets.QPushButton("scale", self)
self.layout.addRow("Autoscale X:", self.hist_auto)
self.hist_auto.pressed.connect(self.autoscalex)
self.quit = QtWidgets.QPushButton("Close", self)
self.quit.setMinimumWidth(100)
self.layout.addWidget(self.quit)
self.quit.clicked.connect(QtWidgets.qApp.quit)
def attach_signal1(self, signal):
self.signal1 = signal
self.freq1Edit.setText(("{0}").format(self.signal1.frequency()))
self.amp1Edit.setText(("{0}").format(self.signal1.amplitude()))
def attach_signal2(self, signal):
self.signal2 = signal
self.amp2Edit.setText(("{0}").format(self.signal2.amplitude()))
def freq1EditText(self):
try:
newfreq = float(self.freq1Edit.text())
self.signal1.set_frequency(newfreq)
except ValueError:
print("Bad frequency value entered")
def amp1EditText(self):
try:
newamp = float(self.amp1Edit.text())
self.signal1.set_amplitude(newamp)
except ValueError:
print("Bad amplitude value entered")
def amp2EditText(self):
try:
newamp = float(self.amp2Edit.text())
self.signal2.set_amplitude(newamp)
except ValueError:
print("Bad amplitude value entered")
def set_nsamps(self):
res = self.hist_npts.text().toInt()
if res[1]:
self.snk.set_nsamps(res[0])
def set_bins(self):
res = self.hist_bins.text().toInt()
if res[1]:
self.snk.set_bins(res[0])
def autoscalex(self):
self.snk.autoscalex()
class my_top_block(gr.top_block):
def __init__(self):
gr.top_block.__init__(self)
Rs = 8000
f1 = 100
npts = 2048
self.qapp = QtWidgets.QApplication(sys.argv)
src1 = analog.sig_source_f(Rs, analog.GR_SIN_WAVE, f1, 0, 0)
src2 = analog.noise_source_f(analog.GR_GAUSSIAN, 1)
src = blocks.add_ff()
thr = blocks.throttle(gr.sizeof_float, 100 * npts)
self.snk1 = qtgui.histogram_sink_f(npts, 200, -5, 5, "Histogram", 1, None)
self.snk1.disable_legend()
self.connect(src1, (src, 0))
self.connect(src2, (src, 1))
self.connect(src, thr, self.snk1)
self.ctrl_win = control_box(self.snk1)
self.ctrl_win.attach_signal1(src1)
self.ctrl_win.attach_signal2(src2)
# Get the reference pointer to the SpectrumDisplayForm QWidget
pyQt = self.snk1.qwidget()
# Wrap the pointer as a PyQt SIP object
# This can now be manipulated as a PyQt5.QtWidgets.QWidget
pyWin = sip.wrapinstance(pyQt, QtWidgets.QWidget)
# pyWin.show()
self.main_box = dialog_box(pyWin, self.ctrl_win)
self.main_box.show()
if __name__ == "__main__":
tb = my_top_block()
tb.start()
tb.qapp.exec_()
tb.stop()
|
PyObjCTest | test_identity | # Some tests that verify that object identity is correctly retained
# accross the bridge
#
# TODO:
# - Add unittests here for every class that is treated specially by
# the bridge.
# - Add unittests that test for "real-world" scenarios (writing stuff
# to plists, ...)
# - Implement the required functionality
from __future__ import unicode_literals
import os
import sys
import objc
from PyObjCTest.identity import *
from PyObjCTools.TestSupport import *
if sys.version_info[0] == 3:
unicode = str
class TestPythonRoundTrip(TestCase):
# TODO: verify
def testBasicPython(self):
container = OC_TestIdentity.alloc().init()
for v in (self, object(), list, sum):
container.setStoredObject_(v)
self.assertTrue(v is container.storedObject(), repr(v))
def testPythonContainer(self):
container = OC_TestIdentity.alloc().init()
for v in ([1, 2, 3], (1, 2, 3), {1: 2, 3: 4}):
container.setStoredObject_(v)
self.assertTrue(v is container.storedObject(), repr(v))
def dont_testPythonStrings(self):
# XXX: this test would always fail, this is by design.
container = OC_TestIdentity.alloc().init()
for v in ("Hello world", b"Hello world"):
container.setStoredObject_(v)
self.assertTrue(v is container.storedObject(), repr(v))
def dont_testPythonNumber(self):
# XXX: this test would always fail, need to move some code to C
# to fix (but not now)
container = OC_TestIdentity.alloc().init()
for v in (99999, sys.maxsize * 3, 10.0):
container.setStoredObject_(v)
self.assertTrue(v is container.storedObject, repr(v))
class ObjCRoundTrip(TestCase):
# TODO: NSProxy
def testNSObject(self):
container = OC_TestIdentity.alloc().init()
cls = objc.lookUpClass("NSObject")
container.setStoredObjectToResultOf_on_("new", cls)
v = container.storedObject()
self.assertTrue(container.isSameObjectAsStored_(v), repr(v))
container.setStoredObjectToResultOf_on_("class", cls)
v = container.storedObject()
self.assertTrue(container.isSameObjectAsStored_(v), repr(v))
def testNSString(self):
container = OC_TestIdentity.alloc().init()
cls = objc.lookUpClass("NSObject")
container.setStoredObjectToResultOf_on_("description", cls)
v = container.storedObject()
self.assertTrue(container.isSameObjectAsStored_(v), repr(v))
self.assertTrue(isinstance(v, unicode))
cls = objc.lookUpClass("NSMutableString")
container.setStoredObjectToResultOf_on_("new", cls)
v = container.storedObject()
self.assertTrue(container.isSameObjectAsStored_(v), repr(v))
self.assertTrue(isinstance(v, unicode))
def testProtocol(self):
container = OC_TestIdentity.alloc().init()
container.setStoredObjectToAProtocol()
v = container.storedObject()
self.assertTrue(container.isSameObjectAsStored_(v), repr(v))
self.assertTrue(isinstance(v, objc.formal_protocol))
if sys.maxsize < 2**32 and os_release() < "10.7":
def testObject(self):
container = OC_TestIdentity.alloc().init()
cls = objc.lookUpClass("Object")
container.setStoredObjectAnInstanceOfClassic_(cls)
v = container.storedObject()
self.assertTrue(container.isSameObjectAsStored_(v), repr(v))
self.assertTrue(isinstance(v, cls))
def testNSNumber(self):
container = OC_TestIdentity.alloc().init()
container.setStoredObjectToInteger_(10)
v = container.storedObject()
self.assertTrue(container.isSameObjectAsStored_(v), repr(v))
container.setStoredObjectToInteger_(-40)
v = container.storedObject()
self.assertTrue(container.isSameObjectAsStored_(v), repr(v))
container.setStoredObjectToUnsignedInteger_(40)
v = container.storedObject()
self.assertTrue(container.isSameObjectAsStored_(v), repr(v))
container.setStoredObjectToUnsignedInteger_(2**32 - 4)
v = container.storedObject()
self.assertTrue(container.isSameObjectAsStored_(v), repr(v))
if sys.maxsize < 2**32:
container.setStoredObjectToLongLong_(sys.maxsize * 2)
v = container.storedObject()
self.assertTrue(container.isSameObjectAsStored_(v), repr(v))
container.setStoredObjectToLongLong_(-sys.maxsize)
v = container.storedObject()
self.assertTrue(container.isSameObjectAsStored_(v), repr(v))
container.setStoredObjectToUnsignedLongLong_(sys.maxsize * 2)
v = container.storedObject()
self.assertTrue(container.isSameObjectAsStored_(v), repr(v))
container.setStoredObjectToFloat_(10.0)
v = container.storedObject()
self.assertTrue(container.isSameObjectAsStored_(v), repr(v))
container.setStoredObjectToDouble_(9999.0)
v = container.storedObject()
self.assertTrue(container.isSameObjectAsStored_(v), repr(v))
def testNSDecimalNumber(self):
container = OC_TestIdentity.alloc().init()
cls = objc.lookUpClass("NSDecimalNumber")
container.setStoredObjectToResultOf_on_("zero", cls)
v = container.storedObject()
self.assertTrue(container.isSameObjectAsStored_(v), repr(v))
class ObjCtoPython(TestCase):
# TODO: NSProxy
def assertFetchingTwice(self, container, message=None):
v1 = container.storedObject()
v2 = container.storedObject()
self.assertTrue(v1 is v2, message)
def testNSObject(self):
container = OC_TestIdentity.alloc().init()
cls = objc.lookUpClass("NSObject")
container.setStoredObjectToResultOf_on_("new", cls)
self.assertFetchingTwice(container, repr(cls))
container.setStoredObjectToResultOf_on_("new", cls)
v1 = container.storedObject()
container.setStoredObjectToResultOf_on_("new", cls)
v2 = container.storedObject()
self.assertTrue(v1 is not v2, "different objects")
def dont_testNSString(self):
# This would always fail, NSStrings get a new proxy everytime
# they cross the bridge, otherwise it would be unnecessarily hard
# to get at the current value of NSMutableStrings.
container = OC_TestIdentity.alloc().init()
cls = objc.lookUpClass("NSObject")
container.setStoredObjectToResultOf_on_("description", cls)
self.assertFetchingTwice(container, "string")
cls = objc.lookUpClass("NSMutableString")
container.setStoredObjectToResultOf_on_("new", cls)
self.assertFetchingTwice(container, "mutable string")
def testProtocol(self):
container = OC_TestIdentity.alloc().init()
container.setStoredObjectToAProtocol()
v = container.storedObject()
self.assertFetchingTwice(container, "protocol")
if sys.maxsize < 2**32 and os_release() < "10.7":
def testObject(self):
container = OC_TestIdentity.alloc().init()
cls = objc.lookUpClass("Object")
container.setStoredObjectAnInstanceOfClassic_(cls)
self.assertFetchingTwice(container, "object")
def dont_testNSNumber(self):
# No unique proxies yet, due to the way these proxies are
# implemented. This needs to be fixed, but that does not have
# a high priority.
container = OC_TestIdentity.alloc().init()
container.setStoredObjectToInteger_(10)
self.assertFetchingTwice(container, "int 10")
container.setStoredObjectToInteger_(-40)
self.assertFetchingTwice(container, "int -40")
container.setStoredObjectToUnsignedInteger_(40)
self.assertFetchingTwice(container, "unsigned int 40")
container.setStoredObjectToUnsignedInteger_(sys.maxsize * 2)
self.assertFetchingTwice(container, "unsigned int sys.maxsize*2")
container.setStoredObjectToLongLong_(sys.maxsize * 2)
self.assertFetchingTwice(container, "long long sys.maxsize*2")
container.setStoredObjectToLongLong_(-sys.maxsize)
self.assertFetchingTwice(container, "long long -sys.maxsize")
container.setStoredObjectToUnsignedLongLong_(sys.maxsize * 2)
self.assertFetchingTwice(container, "unsigned long long sys.maxsize*2")
container.setStoredObjectToFloat_(10.0)
self.assertFetchingTwice(container, "float")
container.setStoredObjectToDouble_(9999.0)
self.assertFetchingTwice(container, "double")
def testNSDecimalNumber(self):
container = OC_TestIdentity.alloc().init()
cls = objc.lookUpClass("NSDecimalNumber")
container.setStoredObjectToResultOf_on_("zero", cls)
self.assertFetchingTwice(container, "decimal")
class PythonToObjC(TestCase):
# TODO: verify
def testPlainObjects(self):
container = OC_TestIdentity.alloc().init()
for v in (self, object(), list, sum):
container.setStoredObject_(v)
self.assertTrue(container.isSameObjectAsStored_(v), repr(v))
def testContainers(self):
container = OC_TestIdentity.alloc().init()
for v in ([1, 2, 3], (1, 2, 3), {1: 2, 3: 4}):
container.setStoredObject_(v)
self.assertTrue(container.isSameObjectAsStored_(v), repr(v))
def dont_testStrings(self):
# These get converted, not proxied
container = OC_TestIdentity.alloc().init()
for v in (b"hello world", "a unicode string"):
container.setStoredObject_(v)
self.assertTrue(container.isSameObjectAsStored_(v), repr(v))
def dont_testNumbers(self):
# These get converted, not proxied
container = OC_TestIdentity.alloc().init()
for v in (
1,
666666,
sys.maxsize * 3,
1.0,
):
container.setStoredObject_(v)
self.assertTrue(container.isSameObjectAsStored_(v), repr(v))
class TestSerializingDataStructures(TestCase):
# OC_Python{Array,Dictionary} used to contain specialized
# identity-preservation code. It is unclear why this was added, it might
# have to do with writing data to plist files.
# This TestCase tries to trigger the problem that caused the addition of
# said code, although unsuccesfully...
def tearDown(self):
if os.path.exists("/tmp/pyPyObjCTest.identity"):
os.unlink("/tmp/pyPyObjCTest.identity")
def testMakePlist(self):
container = OC_TestIdentity.alloc().init()
value = [1, 2, 3, ["hello", ["world", ("in", 9)], True, {"aap": 3}]]
value.append(value[3])
container.setStoredObject_(value)
container.writeStoredObjectToFile_("/tmp/pyPyObjCTest.identity")
value = {
"hello": [1, 2, 3],
"world": {
"nl": "wereld",
"de": "Welt",
},
}
container.setStoredObject_(value)
container.writeStoredObjectToFile_("/tmp/pyPyObjCTest.identity")
if __name__ == "__main__":
main()
|
extractor | lecturio | # coding: utf-8
from __future__ import unicode_literals
import re
from ..utils import (
ExtractorError,
clean_html,
determine_ext,
float_or_none,
int_or_none,
str_or_none,
url_or_none,
urlencode_postdata,
urljoin,
)
from .common import InfoExtractor
class LecturioBaseIE(InfoExtractor):
_API_BASE_URL = "https://app.lecturio.com/api/en/latest/html5/"
_LOGIN_URL = "https://app.lecturio.com/en/login"
_NETRC_MACHINE = "lecturio"
def _real_initialize(self):
self._login()
def _login(self):
username, password = self._get_login_info()
if username is None:
return
# Sets some cookies
_, urlh = self._download_webpage_handle(
self._LOGIN_URL, None, "Downloading login popup"
)
def is_logged(url_handle):
return self._LOGIN_URL not in url_handle.geturl()
# Already logged in
if is_logged(urlh):
return
login_form = {
"signin[email]": username,
"signin[password]": password,
"signin[remember]": "on",
}
response, urlh = self._download_webpage_handle(
self._LOGIN_URL, None, "Logging in", data=urlencode_postdata(login_form)
)
# Logged in successfully
if is_logged(urlh):
return
errors = self._html_search_regex(
r'(?s)<ul[^>]+class=["\']error_list[^>]+>(.+?)</ul>',
response,
"errors",
default=None,
)
if errors:
raise ExtractorError("Unable to login: %s" % errors, expected=True)
raise ExtractorError("Unable to log in")
class LecturioIE(LecturioBaseIE):
_VALID_URL = r"""(?x)
https://
(?:
app\.lecturio\.com/([^/]+/(?P<nt>[^/?#&]+)\.lecture|(?:\#/)?lecture/c/\d+/(?P<id>\d+))|
(?:www\.)?lecturio\.de/[^/]+/(?P<nt_de>[^/?#&]+)\.vortrag
)
"""
_TESTS = [
{
"url": "https://app.lecturio.com/medical-courses/important-concepts-and-terms-introduction-to-microbiology.lecture#tab/videos",
"md5": "9a42cf1d8282a6311bf7211bbde26fde",
"info_dict": {
"id": "39634",
"ext": "mp4",
"title": "Important Concepts and Terms — Introduction to Microbiology",
},
"skip": "Requires lecturio account credentials",
},
{
"url": "https://www.lecturio.de/jura/oeffentliches-recht-staatsexamen.vortrag",
"only_matching": True,
},
{
"url": "https://app.lecturio.com/#/lecture/c/6434/39634",
"only_matching": True,
},
]
_CC_LANGS = {
"Arabic": "ar",
"Bulgarian": "bg",
"German": "de",
"English": "en",
"Spanish": "es",
"Persian": "fa",
"French": "fr",
"Japanese": "ja",
"Polish": "pl",
"Pashto": "ps",
"Russian": "ru",
}
def _real_extract(self, url):
mobj = re.match(self._VALID_URL, url)
nt = mobj.group("nt") or mobj.group("nt_de")
lecture_id = mobj.group("id")
display_id = nt or lecture_id
api_path = "lectures/" + lecture_id if lecture_id else "lecture/" + nt + ".json"
video = self._download_json(self._API_BASE_URL + api_path, display_id)
title = video["title"].strip()
if not lecture_id:
pid = video.get("productId") or video.get("uid")
if pid:
spid = pid.split("_")
if spid and len(spid) == 2:
lecture_id = spid[1]
formats = []
for format_ in video["content"]["media"]:
if not isinstance(format_, dict):
continue
file_ = format_.get("file")
if not file_:
continue
ext = determine_ext(file_)
if ext == "smil":
# smil contains only broken RTMP formats anyway
continue
file_url = url_or_none(file_)
if not file_url:
continue
label = str_or_none(format_.get("label"))
filesize = int_or_none(format_.get("fileSize"))
f = {
"url": file_url,
"format_id": label,
"filesize": float_or_none(filesize, invscale=1000),
}
if label:
mobj = re.match(r"(\d+)p\s*\(([^)]+)\)", label)
if mobj:
f.update(
{
"format_id": mobj.group(2),
"height": int(mobj.group(1)),
}
)
formats.append(f)
self._sort_formats(formats)
subtitles = {}
automatic_captions = {}
captions = video.get("captions") or []
for cc in captions:
cc_url = cc.get("url")
if not cc_url:
continue
cc_label = cc.get("translatedCode")
lang = cc.get("languageCode") or self._search_regex(
r"/([a-z]{2})_",
cc_url,
"lang",
default=cc_label.split()[0] if cc_label else "en",
)
original_lang = self._search_regex(
r"/[a-z]{2}_([a-z]{2})_", cc_url, "original lang", default=None
)
sub_dict = (
automatic_captions
if "auto-translated" in cc_label or original_lang
else subtitles
)
sub_dict.setdefault(self._CC_LANGS.get(lang, lang), []).append(
{
"url": cc_url,
}
)
return {
"id": lecture_id or nt,
"title": title,
"formats": formats,
"subtitles": subtitles,
"automatic_captions": automatic_captions,
}
class LecturioCourseIE(LecturioBaseIE):
_VALID_URL = r"https://app\.lecturio\.com/(?:[^/]+/(?P<nt>[^/?#&]+)\.course|(?:#/)?course/c/(?P<id>\d+))"
_TESTS = [
{
"url": "https://app.lecturio.com/medical-courses/microbiology-introduction.course#/",
"info_dict": {
"id": "microbiology-introduction",
"title": "Microbiology: Introduction",
"description": "md5:13da8500c25880c6016ae1e6d78c386a",
},
"playlist_count": 45,
"skip": "Requires lecturio account credentials",
},
{
"url": "https://app.lecturio.com/#/course/c/6434",
"only_matching": True,
},
]
def _real_extract(self, url):
nt, course_id = re.match(self._VALID_URL, url).groups()
display_id = nt or course_id
api_path = (
"courses/" + course_id if course_id else "course/content/" + nt + ".json"
)
course = self._download_json(self._API_BASE_URL + api_path, display_id)
entries = []
for lecture in course.get("lectures", []):
lecture_id = str_or_none(lecture.get("id"))
lecture_url = lecture.get("url")
if lecture_url:
lecture_url = urljoin(url, lecture_url)
else:
lecture_url = "https://app.lecturio.com/#/lecture/c/%s/%s" % (
course_id,
lecture_id,
)
entries.append(
self.url_result(
lecture_url, ie=LecturioIE.ie_key(), video_id=lecture_id
)
)
return self.playlist_result(
entries,
display_id,
course.get("title"),
clean_html(course.get("description")),
)
class LecturioDeCourseIE(LecturioBaseIE):
_VALID_URL = r"https://(?:www\.)?lecturio\.de/[^/]+/(?P<id>[^/?#&]+)\.kurs"
_TEST = {
"url": "https://www.lecturio.de/jura/grundrechte.kurs",
"only_matching": True,
}
def _real_extract(self, url):
display_id = self._match_id(url)
webpage = self._download_webpage(url, display_id)
entries = []
for mobj in re.finditer(
r'(?s)<td[^>]+\bdata-lecture-id=["\'](?P<id>\d+).+?\bhref=(["\'])(?P<url>(?:(?!\2).)+\.vortrag)\b[^>]+>',
webpage,
):
lecture_url = urljoin(url, mobj.group("url"))
lecture_id = mobj.group("id")
entries.append(
self.url_result(
lecture_url, ie=LecturioIE.ie_key(), video_id=lecture_id
)
)
title = self._search_regex(r"<h1[^>]*>([^<]+)", webpage, "title", default=None)
return self.playlist_result(entries, display_id, title)
|
PyObjCTest | test_nsnumberformatter | from Foundation import *
from PyObjCTools.TestSupport import *
class TestNSNumberFormatter(TestCase):
def testConstants(self):
self.assertEqual(NSNumberFormatterNoStyle, kCFNumberFormatterNoStyle)
self.assertEqual(NSNumberFormatterDecimalStyle, kCFNumberFormatterDecimalStyle)
self.assertEqual(
NSNumberFormatterCurrencyStyle, kCFNumberFormatterCurrencyStyle
)
self.assertEqual(NSNumberFormatterPercentStyle, kCFNumberFormatterPercentStyle)
self.assertEqual(
NSNumberFormatterScientificStyle, kCFNumberFormatterScientificStyle
)
self.assertEqual(
NSNumberFormatterSpellOutStyle, kCFNumberFormatterSpellOutStyle
)
self.assertEqual(NSNumberFormatterBehaviorDefault, 0)
self.assertEqual(NSNumberFormatterBehavior10_0, 1000)
self.assertEqual(NSNumberFormatterBehavior10_4, 1040)
self.assertEqual(
NSNumberFormatterPadBeforePrefix, kCFNumberFormatterPadBeforePrefix
)
self.assertEqual(
NSNumberFormatterPadAfterPrefix, kCFNumberFormatterPadAfterPrefix
)
self.assertEqual(
NSNumberFormatterPadBeforeSuffix, kCFNumberFormatterPadBeforeSuffix
)
self.assertEqual(
NSNumberFormatterPadAfterSuffix, kCFNumberFormatterPadAfterSuffix
)
self.assertEqual(NSNumberFormatterRoundCeiling, kCFNumberFormatterRoundCeiling)
self.assertEqual(NSNumberFormatterRoundFloor, kCFNumberFormatterRoundFloor)
self.assertEqual(NSNumberFormatterRoundDown, kCFNumberFormatterRoundDown)
self.assertEqual(NSNumberFormatterRoundUp, kCFNumberFormatterRoundUp)
self.assertEqual(
NSNumberFormatterRoundHalfEven, kCFNumberFormatterRoundHalfEven
)
self.assertEqual(
NSNumberFormatterRoundHalfDown, kCFNumberFormatterRoundHalfDown
)
self.assertEqual(NSNumberFormatterRoundHalfUp, kCFNumberFormatterRoundHalfUp)
def testOutput(self):
self.assertResultIsBOOL(NSNumberFormatter.getObjectValue_forString_range_error_)
self.assertArgIsOut(NSNumberFormatter.getObjectValue_forString_range_error_, 0)
self.assertArgIsInOut(
NSNumberFormatter.getObjectValue_forString_range_error_, 2
)
self.assertArgIsOut(NSNumberFormatter.getObjectValue_forString_range_error_, 3)
self.assertResultIsBOOL(NSNumberFormatter.generatesDecimalNumbers)
self.assertArgIsBOOL(NSNumberFormatter.setGeneratesDecimalNumbers_, 0)
self.assertResultIsBOOL(NSNumberFormatter.allowsFloats)
self.assertArgIsBOOL(NSNumberFormatter.setAllowsFloats_, 0)
self.assertResultIsBOOL(NSNumberFormatter.alwaysShowsDecimalSeparator)
self.assertArgIsBOOL(NSNumberFormatter.setAlwaysShowsDecimalSeparator_, 0)
self.assertResultIsBOOL(NSNumberFormatter.usesGroupingSeparator)
self.assertArgIsBOOL(NSNumberFormatter.setUsesGroupingSeparator_, 0)
self.assertResultIsBOOL(NSNumberFormatter.isLenient)
self.assertArgIsBOOL(NSNumberFormatter.setLenient_, 0)
self.assertResultIsBOOL(NSNumberFormatter.usesSignificantDigits)
self.assertArgIsBOOL(NSNumberFormatter.setUsesSignificantDigits_, 0)
self.assertResultIsBOOL(NSNumberFormatter.isPartialStringValidationEnabled)
self.assertArgIsBOOL(NSNumberFormatter.setPartialStringValidationEnabled_, 0)
self.assertResultIsBOOL(NSNumberFormatter.hasThousandSeparators)
self.assertArgIsBOOL(NSNumberFormatter.setHasThousandSeparators_, 0)
self.assertResultIsBOOL(NSNumberFormatter.localizesFormat)
self.assertArgIsBOOL(NSNumberFormatter.setLocalizesFormat_, 0)
if __name__ == "__main__":
main()
|
internal | deprecation | import contextlib
import re
import warnings
# Messages used in deprecation warnings are collected here so we can target
# them easily when ignoring warnings.
_MESSAGES = {
# Deprecated features in core playback:
"core.playback.play:tl_track_kwargs": (
'playback.play() with "tl_track" argument is pending deprecation use '
'"tlid" instead'
),
# Deprecated features in core tracklist:
"core.tracklist.add:tracks_arg": (
'tracklist.add() "tracks" argument is deprecated'
),
"core.tracklist.eot_track": (
"tracklist.eot_track() is pending deprecation, use tracklist.get_eot_tlid()"
),
"core.tracklist.next_track": (
"tracklist.next_track() is pending deprecation, use "
"tracklist.get_next_tlid()"
),
"core.tracklist.previous_track": (
"tracklist.previous_track() is pending deprecation, use "
"tracklist.get_previous_tlid()"
),
# Deprecated argument value in core library:
"core.library.get_distinct:field_arg:track": (
'library.get_distinct() with "field" argument "track" is pending '
'deprecation, use "track_name" instead'
),
}
def warn(msg_id, pending=False):
category = PendingDeprecationWarning if pending else DeprecationWarning
warnings.warn(_MESSAGES.get(msg_id, msg_id), category, stacklevel=2)
@contextlib.contextmanager
def ignore(ids=None):
with warnings.catch_warnings():
if isinstance(ids, str):
ids = [ids]
if ids:
for msg_id in ids:
msg = re.escape(_MESSAGES.get(msg_id, msg_id))
warnings.filterwarnings("ignore", msg, DeprecationWarning)
else:
warnings.filterwarnings("ignore", category=DeprecationWarning)
yield
|
serializers | users | from apps.api.permissions import LegacyAccessControlRole
from apps.slack.models import SlackUserIdentity
from apps.user_management.models import User
from common.api_helpers.mixins import EagerLoadingMixin
from rest_framework import serializers
class SlackUserIdentitySerializer(serializers.ModelSerializer):
user_id = serializers.CharField(source="slack_id")
team_id = serializers.CharField(source="slack_team_identity.slack_id")
class Meta:
model = SlackUserIdentity
fields = (
"user_id",
"team_id",
)
class FastUserSerializer(serializers.ModelSerializer):
id = serializers.ReadOnlyField(read_only=True, source="public_primary_key")
email = serializers.EmailField(read_only=True)
role = serializers.SerializerMethodField() # LEGACY, should be removed eventually
is_phone_number_verified = serializers.SerializerMethodField()
class Meta:
model = User
fields = ["id", "email", "username", "role", "is_phone_number_verified"]
@staticmethod
def get_role(obj):
"""
LEGACY, should be removed eventually
"""
return LegacyAccessControlRole(obj.role).name.lower()
def get_is_phone_number_verified(self, obj):
return obj.verified_phone_number is not None
class UserSerializer(serializers.ModelSerializer, EagerLoadingMixin):
id = serializers.ReadOnlyField(read_only=True, source="public_primary_key")
email = serializers.EmailField(read_only=True)
slack = SlackUserIdentitySerializer(read_only=True, source="slack_user_identity")
role = serializers.SerializerMethodField() # LEGACY, should be removed eventually
is_phone_number_verified = serializers.SerializerMethodField()
SELECT_RELATED = [
"slack_user_identity",
"slack_user_identity__slack_team_identity",
]
class Meta:
model = User
fields = [
"id",
"email",
"slack",
"username",
"role",
"is_phone_number_verified",
]
@staticmethod
def get_role(obj):
"""
LEGACY, should be removed eventually
"""
return LegacyAccessControlRole(obj.role).name.lower()
def get_is_phone_number_verified(self, obj):
return obj.verified_phone_number is not None
|
interface | searchtree | # -*- coding: utf-8 -*-
#
# gPodder - A media aggregator and podcast client
# Copyright (c) 2005-2018 The gPodder Team
#
# gPodder is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# gPodder is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import gi # isort:skip
gi.require_version("Gtk", "3.0") # isort:skip
from gi.repository import Gdk, GLib # isort:skip
class SearchTree:
"""
handle showing/hiding the search box for podcast or episode treeviews,
as well as searching for text entered in the search entry.
Automatically attaches to entry signals on creation.
"""
def __init__(self, search_box, search_entry, tree, model, config):
self.search_box = search_box
self.search_entry = search_entry
self.tree = tree
self.model = model
self.config = config
self._search_timeout = None
self.search_entry.connect("icon-press", self.hide_search)
self.search_entry.connect("changed", self.on_entry_changed)
self.search_entry.connect("key-press-event", self.on_entry_key_press)
def set_search_term(self, text):
self.model.set_search_term(text)
self._search_timeout = None
return False
def on_entry_changed(self, editable):
if self.search_box.get_property("visible"):
if self._search_timeout is not None:
GLib.source_remove(self._search_timeout)
# use timeout_add, not util.idle_timeout_add, so it updates the TreeView before background tasks
self._search_timeout = GLib.timeout_add(
self.config.ui.gtk.live_search_delay,
self.set_search_term,
editable.get_chars(0, -1),
)
def on_entry_key_press(self, editable, event):
if event.keyval == Gdk.KEY_Escape:
self.hide_search()
return True
def hide_search(self, *args):
if self._search_timeout is not None:
GLib.source_remove(self._search_timeout)
self._search_timeout = None
if not self.config.ui.gtk.search_always_visible:
self.search_box.hide()
self.search_entry.set_text("")
self.model.set_search_term(None)
self.tree.grab_focus()
def show_search(self, input_char=None, grab_focus=True):
self.search_box.show()
if input_char:
self.search_entry.insert_text(input_char, -1)
if grab_focus:
self.search_entry.grab_focus()
self.search_entry.set_position(-1)
|
parts | containers | # This file is part of the Frescobaldi project, http://www.frescobaldi.org/
#
# Copyright (c) 2008 - 2014 by Wilbert Berendsen
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
# See http://www.gnu.org/licenses/ for more information.
"""
Container part types.
"""
import listmodel
import ly.dom
import symbols
from PyQt5.QtCore import QSize
from PyQt5.QtWidgets import (
QCheckBox,
QComboBox,
QGridLayout,
QGroupBox,
QHBoxLayout,
QLabel,
QLineEdit,
QRadioButton,
QVBoxLayout,
)
from scorewiz import scoreproperties
from . import _base, register
class StaffGroup(_base.Container):
@staticmethod
def title(_=_base.translate):
return _("Staff Group")
def accepts(self):
return (StaffGroup, _base.Part)
def createWidgets(self, layout):
self.systemStartLabel = QLabel()
self.systemStart = QComboBox()
self.systemStartLabel.setBuddy(self.systemStart)
self.systemStart.setModel(
listmodel.ListModel(
(
# L10N: Brace like a piano staff
(lambda: _("Brace"), "system_start_brace"),
# L10N: Bracket like a choir staff
(lambda: _("Bracket"), "system_start_bracket"),
# L10N: Square bracket like a sub-group
(lambda: _("Square"), "system_start_square"),
),
self.systemStart,
display=listmodel.translate_index(0),
icon=lambda item: symbols.icon(item[1]),
)
)
self.systemStart.setIconSize(QSize(64, 64))
self.connectBarLines = QCheckBox(checked=True)
box = QHBoxLayout()
box.addWidget(self.systemStartLabel)
box.addWidget(self.systemStart)
layout.addLayout(box)
layout.addWidget(self.connectBarLines)
def translateWidgets(self):
self.systemStartLabel.setText(_("Type:"))
self.connectBarLines.setText(_("Connect Barlines"))
self.connectBarLines.setToolTip(
_("If checked, barlines are connected between the staves.")
)
self.systemStart.model().update()
def build(self, data, builder):
s = self.systemStart.currentIndex()
b = self.connectBarLines.isChecked()
if s == 0:
node = ly.dom.GrandStaff()
if not b:
ly.dom.Line("\\remove Span_bar_engraver", node.getWith())
else:
node = ly.dom.StaffGroup() if b else ly.dom.ChoirStaff()
if s == 2:
node.getWith()["systemStartDelimiter"] = ly.dom.Scheme(
"'SystemStartSquare"
)
data.nodes.append(node)
data.music = ly.dom.Simr(node)
class Score(_base.Group, scoreproperties.ScoreProperties):
@staticmethod
def title(_=_base.translate):
return _("Score")
def createWidgets(self, layout):
self.pieceLabel = QLabel()
self.piece = QLineEdit()
self.pieceLabel.setBuddy(self.piece)
self.opusLabel = QLabel()
self.opus = QLineEdit()
self.opusLabel.setBuddy(self.opus)
self.scoreProps = QGroupBox(checkable=True, checked=False)
scoreproperties.ScoreProperties.createWidgets(self)
grid = QGridLayout()
grid.addWidget(self.pieceLabel, 0, 0)
grid.addWidget(self.piece, 0, 1)
grid.addWidget(self.opusLabel, 1, 0)
grid.addWidget(self.opus, 1, 1)
layout.addLayout(grid)
layout.addWidget(self.scoreProps)
layout = QVBoxLayout()
self.scoreProps.setLayout(layout)
scoreproperties.ScoreProperties.layoutWidgets(self, layout)
scorewiz = self.scoreProps.window()
self.setPitchLanguage(scorewiz.pitchLanguage())
scorewiz.pitchLanguageChanged.connect(self.setPitchLanguage)
def translateWidgets(self):
self.pieceLabel.setText(_("Piece:"))
self.opusLabel.setText(_("Opus:"))
self.scoreProps.setTitle(_("Properties"))
scoreproperties.ScoreProperties.translateWidgets(self)
def accepts(self):
return (StaffGroup, _base.Part)
def makeNode(self, node):
score = ly.dom.Score(node)
h = ly.dom.Header()
piece = self.piece.text().strip()
opus = self.opus.text().strip()
if piece:
h["piece"] = ly.dom.QuotedString(piece)
if opus:
h["opus"] = ly.dom.QuotedString(opus)
if len(h):
score.append(h)
return score
def globalSection(self, builder):
if self.scoreProps.isChecked():
return scoreproperties.ScoreProperties.globalSection(self, builder)
class BookPart(_base.Group):
@staticmethod
def title(_=_base.translate):
return _("Book Part")
def accepts(self):
return (Score, StaffGroup, _base.Part)
def makeNode(self, node):
bookpart = ly.dom.BookPart(node)
return bookpart
class Book(_base.Group):
@staticmethod
def title(_=_base.translate):
return _("Book")
def accepts(self):
return (BookPart, Score, StaffGroup, _base.Part)
def createWidgets(self, layout):
self.bookOutputInfo = QLabel(wordWrap=True)
self.bookOutputLabel = QLabel()
self.bookOutput = QLineEdit(clearButtonEnabled=True)
self.bookOutputFileName = QRadioButton()
self.bookOutputSuffix = QRadioButton(checked=True)
layout.addWidget(self.bookOutputInfo)
grid = QGridLayout(spacing=0)
grid.addWidget(self.bookOutputLabel, 0, 0)
grid.addWidget(self.bookOutput, 0, 1, 1, 2)
grid.addWidget(self.bookOutputFileName, 1, 1)
grid.addWidget(self.bookOutputSuffix, 1, 2)
layout.addLayout(grid)
def translateWidgets(self):
self.bookOutputInfo.setText(
_(
"<p>Here you can specify a filename or suffix (without extension) "
"to set the names of generated output files for this book.</p>\n"
'<p>If you choose "Suffix" the entered name will be appended '
'to the document\'s file name; if you choose "Filename", just '
"the entered name will be used.</p>"
)
)
self.bookOutputLabel.setText(_("Output Filename:"))
self.bookOutputFileName.setText(_("Filename"))
self.bookOutputSuffix.setText(_("Suffix"))
def makeNode(self, node):
book = ly.dom.Book(node)
name = self.bookOutput.text().strip()
if name:
cmd = (
"bookOutputName"
if self.bookOutputFileName.isChecked()
else "bookOutputSuffix"
)
ly.dom.Line(r'\{} "{}"'.format(cmd, name.replace('"', r"\"")), book)
return book
register(
lambda: _("Containers"),
[
StaffGroup,
Score,
BookPart,
Book,
],
)
|
QT | PantallaBMT | import os.path
import time
from Code import BMT, Analisis, ControlPGN, ControlPosicion, Partida, TrListas, Util
from Code.Constantes import *
from Code.QT import (
Colocacion,
Columnas,
Controles,
Delegados,
FormLayout,
Grid,
Iconos,
QTUtil,
QTUtil2,
QTVarios,
Tablero,
)
from PyQt4 import QtCore
class WHistorialBMT(QTVarios.WDialogo):
def __init__(self, owner, dbf):
# Variables
self.procesador = owner.procesador
self.configuracion = owner.configuracion
# Datos ----------------------------------------------------------------
self.dbf = dbf
self.recnoActual = self.dbf.recno
bmt_lista = Util.blob2var(dbf.leeOtroCampo(self.recnoActual, "BMT_LISTA"))
self.liHistorial = Util.blob2var(
dbf.leeOtroCampo(self.recnoActual, "HISTORIAL")
)
self.maxPuntos = dbf.MAXPUNTOS
if bmt_lista.siTerminada():
dic = {
"FFINAL": dbf.FFINAL,
"ESTADO": dbf.ESTADO,
"PUNTOS": dbf.PUNTOS,
"SEGUNDOS": dbf.SEGUNDOS,
}
self.liHistorial.append(dic)
# Dialogo ---------------------------------------------------------------
icono = Iconos.Historial()
titulo = _("Track record") + ": " + dbf.NOMBRE
extparam = "bmthistorial"
QTVarios.WDialogo.__init__(self, owner, titulo, icono, extparam)
# Toolbar
tb = QTVarios.LCTB(self)
tb.new(_("Close"), Iconos.MainMenu(), self.terminar)
# Lista
oColumnas = Columnas.ListaColumnas()
oColumnas.nueva(
"ESTADO", "", 26, edicion=Delegados.PmIconosBMT(), siCentrado=True
)
oColumnas.nueva("PUNTOS", _("Points"), 104, siCentrado=True)
oColumnas.nueva("TIEMPO", _("Time"), 80, siCentrado=True)
oColumnas.nueva("FFINAL", _("End date"), 90, siCentrado=True)
self.grid = grid = Grid.Grid(self, oColumnas, xid=False, siEditable=True)
# n = grid.anchoColumnas()
# grid.setMinimumWidth( n + 20 )
self.registrarGrid(grid)
# Colocamos ---------------------------------------------------------------
ly = Colocacion.V().control(tb).control(self.grid)
self.setLayout(ly)
self.recuperarVideo(siTam=True)
def terminar(self):
self.guardarVideo()
self.accept()
def gridNumDatos(self, grid):
return len(self.liHistorial)
def gridDato(self, grid, fila, oColumna):
dic = self.liHistorial[fila]
col = oColumna.clave
if col == "ESTADO":
return dic["ESTADO"]
elif col == "HECHOS":
return "%d" % (dic["HECHOS"])
elif col == "PUNTOS":
p = dic["PUNTOS"]
m = self.maxPuntos
porc = p * 100 / m
return "%d/%d=%d" % (p, m, porc) + "%"
elif col == "FFINAL":
f = dic["FFINAL"]
return "%s-%s-%s" % (f[6:], f[4:6], f[:4]) if f else ""
elif col == "TIEMPO":
s = dic["SEGUNDOS"]
if not s:
s = 0
m = s / 60
s %= 60
return "%d' %d\"" % (m, s) if m else '%d"' % s
class WEntrenarBMT(QTVarios.WDialogo):
def __init__(self, owner, dbf):
# Variables
self.procesador = owner.procesador
self.configuracion = owner.configuracion
self.iniTiempo = None
self.antTxtSegundos = ""
self.partida = Partida.Partida()
self.siMostrarPGN = False
self.posicion = ControlPosicion.ControlPosicion()
self.actualP = 0 # Posicion actual
self.controlPGN = ControlPGN.ControlPGN(self)
self.estado = None # compatibilidad con ControlPGN
self.siJuegaHumano = False # compatibilidad con ControlPGN
# Datos ----------------------------------------------------------------
self.dbf = dbf
self.recnoActual = self.dbf.recno
x = dbf.leeOtroCampo(self.recnoActual, "BMT_LISTA")
self.bmt_lista = Util.blob2var(dbf.leeOtroCampo(self.recnoActual, "BMT_LISTA"))
self.bmt_lista.compruebaColor()
self.historial = Util.blob2var(dbf.leeOtroCampo(self.recnoActual, "HISTORIAL"))
self.siTerminadaAntes = self.siTerminada = self.bmt_lista.siTerminada()
self.timer = None
self.datosInicio = self.bmt_lista.calculaTHPSE()
# Dialogo ---------------------------------------------------------------
icono = Iconos.BMT()
titulo = dbf.NOMBRE
extparam = "bmtentrenar"
QTVarios.WDialogo.__init__(self, owner, titulo, icono, extparam)
# Juegan ---------------------------------------------------------------
self.lbJuegan = (
Controles.LB(self, "").ponColorFondoN("white", "black").alinCentrado()
)
# Tablero ---------------------------------------------------------------
confTablero = self.configuracion.confTablero("BMT", 32)
self.tablero = Tablero.Tablero(self, confTablero)
self.tablero.crea()
self.tablero.ponMensajero(self.mueveHumano)
# Info -------------------------------------------------------------------
colorFondo = QTUtil.qtColor(confTablero.colorNegras())
self.trPuntos = "<big><b>" + _("Points") + "<br>%s</b></big>"
self.trSegundos = "<big><b>" + _("Time") + "<br>%s</b></big>"
self.lbPuntos = (
Controles.LB(self, "").ponFondo(colorFondo).alinCentrado().anchoMinimo(80)
)
self.lbSegundos = (
Controles.LB(self, "").ponFondo(colorFondo).alinCentrado().anchoMinimo(80)
)
self.lbPrimera = Controles.LB(self, _("* indicates actual move played in game"))
f = Controles.TipoLetra(puntos=8)
self.lbCondiciones = Controles.LB(self, "").ponFuente(f)
# Grid-PGN ---------------------------------------------------------------
oColumnas = Columnas.ListaColumnas()
oColumnas.nueva("NUMERO", _("N."), 35, siCentrado=True)
siFigurinesPGN = self.configuracion.figurinesPGN
oColumnas.nueva(
"BLANCAS",
_("White"),
100,
edicion=Delegados.EtiquetaPGN(True if siFigurinesPGN else None),
)
oColumnas.nueva(
"NEGRAS",
_("Black"),
100,
edicion=Delegados.EtiquetaPGN(False if siFigurinesPGN else None),
)
self.pgn = Grid.Grid(self, oColumnas, siCabeceraMovible=False)
nAnchoPgn = self.pgn.anchoColumnas() + 20
self.pgn.setMinimumWidth(nAnchoPgn)
self.pgn.setVisible(False)
# BT posiciones ---------------------------------------------------------------
self.liBT = []
nSalto = (self.tablero.ancho + 34) / 26
self.dicIconos = {
0: Iconos.PuntoBlanco(),
1: Iconos.PuntoNegro(),
2: Iconos.PuntoAmarillo(),
3: Iconos.PuntoNaranja(),
4: Iconos.PuntoVerde(),
5: Iconos.PuntoAzul(),
6: Iconos.PuntoMagenta(),
7: Iconos.PuntoRojo(),
8: Iconos.PuntoEstrella(),
}
nfila = 0
ncolumna = 0
lyBT = Colocacion.G()
numero = 0
nposic = len(self.bmt_lista)
for x in range(nposic):
bt = (
Controles.PB(self, str(x + 1), rutina=self.numero)
.anchoFijo(36)
.altoFijo(20)
)
bt.numero = numero
numero += 1
estado = self.bmt_lista.estado(x)
bt.ponIcono(self.dicIconos[estado])
self.liBT.append(bt)
lyBT.controlc(bt, nfila, ncolumna)
nfila += 1
if nfila == nSalto:
ncolumna += 1
nfila = 0
# if ncolumna == 0:
lyBT = Colocacion.V().otro(lyBT).relleno()
gbBT = Controles.GB(self, _("Positions"), lyBT)
# Lista de RM max 16 ---------------------------------------------------------------
self.liBTrm = []
nfila = 0
ncolumna = 0
lyRM = Colocacion.G()
numero = 0
for x in range(16):
btRM = (
Controles.PB(self, "", rutina=self.pulsadoRM)
.anchoFijo(180)
.altoFijo(24)
.ponPlano(True)
)
btRM.numero = numero
btRM.setEnabled(False)
numero += 1
self.liBTrm.append(btRM)
lyRM.controlc(btRM, nfila, ncolumna)
ncolumna += 1
if ncolumna == 2:
nfila += 1
ncolumna = 0
self.gbRM = Controles.GB(self, _("Moves"), lyRM)
# Tool bar ---------------------------------------------------------------
liAcciones = (
(_("Close"), Iconos.MainMenu(), "terminar"),
(_("Next"), Iconos.Siguiente(), "seguir"),
(_("Repeat"), Iconos.Pelicula_Repetir(), "repetir"),
(_("Resign"), Iconos.Abandonar(), "abandonar"),
(_("Start"), Iconos.Empezar(), "empezar"),
(_("Actual game"), Iconos.PartidaOriginal(), "original"),
)
self.tb = Controles.TB(self, liAcciones)
self.recuperarVideo(siTam=False)
# Colocamos ---------------------------------------------------------------
lyPS = (
Colocacion.H()
.relleno()
.control(self.lbPuntos)
.relleno(2)
.control(self.lbSegundos)
.relleno()
)
lyV = (
Colocacion.V()
.otro(lyPS)
.control(self.pgn)
.control(self.gbRM)
.control(self.lbPrimera)
)
lyT = (
Colocacion.V()
.control(self.lbJuegan)
.control(self.tablero)
.control(self.lbCondiciones)
.relleno()
)
lyTV = Colocacion.H().otro(lyT).otro(lyV).control(gbBT).margen(5)
ly = Colocacion.V().control(self.tb).otro(lyTV).margen(2).relleno()
self.setLayout(ly)
if self.siTerminada:
self.empezar()
else:
self.ponToolBar(["terminar", "empezar"])
self.muestraControles(False)
def muestraControles(self, si):
for control in (
self.lbJuegan,
self.tablero,
self.lbPuntos,
self.lbSegundos,
self.lbPrimera,
self.lbCondiciones,
self.pgn,
self.gbRM,
):
control.setVisible(si)
def procesarTB(self):
accion = self.sender().clave
if accion == "terminar":
self.terminar()
self.accept()
elif accion == "seguir":
self.muestraControles(True)
pos = self.actualP + 1
if pos >= len(self.liBT):
pos = 0
self.buscaPrimero(pos)
elif accion == "abandonar":
self.bmt_uno.puntos = 0
self.activaJugada(0)
self.ponPuntos(0)
self.ponToolBar()
elif accion == "repetir":
self.muestraControles(True)
self.repetir()
elif accion == "empezar":
self.muestraControles(True)
self.empezar()
elif accion == "original":
self.original()
def closeEvent(self, event):
self.terminar()
def empezar(self):
self.buscaPrimero(0)
self.ponPuntos(0)
self.ponSegundos()
self.ponReloj()
def terminar(self):
self.finalizaTiempo()
atotal, ahechos, at_puntos, at_segundos, at_estado = self.datosInicio
total, hechos, t_puntos, t_segundos, t_estado = self.bmt_lista.calculaTHPSE()
if (
(hechos != ahechos)
or (t_puntos != at_puntos)
or (t_segundos != at_segundos)
or (t_estado != at_estado)
):
reg = self.dbf.baseRegistro()
reg.BMT_LISTA = Util.var2blob(self.bmt_lista)
reg.HECHOS = hechos
reg.SEGUNDOS = t_segundos
reg.PUNTOS = t_puntos
if self.historial:
reg.HISTORIAL = Util.var2blob(self.historial)
reg.REPE = len(reg.HISTORIAL)
if self.siTerminada:
if not self.siTerminadaAntes:
reg.ESTADO = str(t_estado / total)
reg.FFINAL = Util.dtos(Util.hoy())
self.dbf.modificarReg(self.recnoActual, reg)
self.guardarVideo()
def repetir(self):
if not QTUtil2.pregunta(self, _("Do you want to repeat this training?")):
return
self.quitaReloj()
total, hechos, t_puntos, t_segundos, t_estado = self.bmt_lista.calculaTHPSE()
dic = {}
dic["FFINAL"] = (
self.dbf.FFINAL if self.siTerminadaAntes else Util.dtos(Util.hoy())
)
dic["ESTADO"] = str(t_estado / total)
dic["PUNTOS"] = t_puntos
dic["SEGUNDOS"] = t_segundos
self.historial.append(dic)
self.bmt_lista.reiniciar()
for bt in self.liBT:
bt.ponIcono(self.dicIconos[0])
self.siTerminadaAntes = self.siTerminada = False
self.tablero.ponPosicion(ControlPosicion.ControlPosicion().logo())
for bt in self.liBTrm:
bt.ponTexto("")
self.siMostrarPGN = False
self.pgn.refresh()
self.lbPuntos.ponTexto("")
self.lbSegundos.ponTexto("")
self.lbJuegan.ponTexto("")
self.lbPrimera.setVisible(False)
self.ponToolBar(["terminar", "empezar"])
def ponRevision(self, siPoner): # compatibilidad ControlPGN
return
def desactivaTodas(self): # compatibilidad ControlPGN
return
def refresh(self): # compatibilidad ControlPGN
self.tablero.escena.update()
self.update()
QTUtil.refreshGUI()
def ponPosicion(self, posicion):
self.tablero.ponPosicion(posicion)
def ponFlechaSC(
self, desde, hasta, liVar=None
): # liVar incluido por compatibilidad
self.tablero.ponFlechaSC(desde, hasta)
def gridNumDatos(self, grid):
if self.siMostrarPGN:
return self.controlPGN.numDatos()
else:
return 0
def ponteAlPrincipio(self):
self.tablero.ponPosicion(self.partida.iniPosicion)
self.pgn.goto(0, 0)
self.pgn.refresh()
def pgnMueveBase(self, fila, columna):
if columna == "NUMERO":
if fila == 0:
self.ponteAlPrincipio()
return
else:
fila -= 1
self.controlPGN.mueve(fila, columna == "BLANCAS")
def keyPressEvent(self, event):
self.teclaPulsada("V", event.key())
def tableroWheelEvent(self, nada, siAdelante):
self.teclaPulsada("T", 16777234 if siAdelante else 16777236)
def gridDato(self, grid, fila, oColumna):
return self.controlPGN.dato(fila, oColumna.clave)
def gridBotonIzquierdo(self, grid, fila, columna):
self.pgnMueveBase(fila, columna.clave)
def gridBotonDerecho(self, grid, fila, columna, modificadores):
self.pgnMueveBase(fila, columna.clave)
def gridDobleClick(self, grid, fila, columna):
if columna.clave == "NUMERO":
return
self.analizaPosicion(fila, columna.clave)
def gridTeclaControl(self, grid, k, siShift, siControl, siAlt):
self.teclaPulsada("G", k)
def gridWheelEvent(self, ogrid, siAdelante):
self.teclaPulsada("T", 16777236 if not siAdelante else 16777234)
def teclaPulsada(self, tipo, tecla):
if self.siMostrarPGN:
dic = QTUtil2.dicTeclas()
if tecla in dic:
self.mueveJugada(dic[tecla])
def mueveJugada(self, tipo):
partida = self.partida
fila, columna = self.pgn.posActual()
clave = columna.clave
if clave == "NUMERO":
siBlancas = tipo == kMoverAtras
fila -= 1
else:
siBlancas = clave != "NEGRAS"
siEmpiezaConNegras = partida.siEmpiezaConNegras
lj = partida.numJugadas()
if siEmpiezaConNegras:
lj += 1
ultFila = (lj - 1) / 2
siUltBlancas = lj % 2 == 1
if tipo == kMoverAtras:
if siBlancas:
fila -= 1
siBlancas = not siBlancas
pos = fila * 2
if not siBlancas:
pos += 1
if fila < 0 or (fila == 0 and pos == 0 and siEmpiezaConNegras):
self.ponteAlPrincipio()
return
elif tipo == kMoverAdelante:
if not siBlancas:
fila += 1
siBlancas = not siBlancas
elif tipo == kMoverInicio: # Inicio
self.ponteAlPrincipio()
return
elif tipo == kMoverFinal:
fila = ultFila
siBlancas = not partida.ultPosicion.siBlancas
if fila == ultFila:
if siUltBlancas and not siBlancas:
return
if fila < 0 or fila > ultFila:
self.refresh()
return
if fila == 0 and siBlancas and siEmpiezaConNegras:
siBlancas = False
self.pgnColocate(fila, siBlancas)
self.pgnMueveBase(fila, "BLANCAS" if siBlancas else "NEGRAS")
def pgnColocate(self, fil, siBlancas):
col = 1 if siBlancas else 2
self.pgn.goto(fil, col)
def numero(self):
bt = self.sender()
self.activaPosicion(bt.numero)
return 0
def pulsadoRM(self):
if self.siMostrarPGN:
bt = self.sender()
self.muestra(bt.numero)
def ponToolBar(self, li=None):
if not li:
li = ["terminar", "seguir"]
if not self.bmt_uno.siTerminado:
li.append("abandonar")
else:
if self.siTerminada:
li.append("repetir")
if self.bmt_uno.clpartida:
li.append("original")
self.tb.clear()
for k in li:
self.tb.dicTB[k].setVisible(True)
self.tb.dicTB[k].setEnabled(True)
self.tb.addAction(self.tb.dicTB[k])
self.tb.liAcciones = li
self.tb.update()
def ponPuntos(self, descontar):
self.bmt_uno.puntos -= descontar
if self.bmt_uno.puntos < 0:
self.bmt_uno.puntos = 0
self.bmt_uno.actualizaEstado()
eti = "%d/%d" % (self.bmt_uno.puntos, self.bmt_uno.maxPuntos)
self.lbPuntos.ponTexto(self.trPuntos % eti)
def ponSegundos(self):
segundos = self.bmt_uno.segundos
if self.iniTiempo:
segundos += int(time.time() - self.iniTiempo)
minutos = segundos / 60
segundos -= minutos * 60
if minutos:
eti = "%d'%d\"" % (minutos, segundos)
else:
eti = '%d"' % (segundos,)
eti = self.trSegundos % eti
if eti != self.antTxtSegundos:
self.antTxtSegundos = eti
self.lbSegundos.ponTexto(eti)
def buscaPrimero(self, desde):
# Buscamos el primero que no se ha terminado
n = len(self.bmt_lista)
for x in range(n):
t = desde + x
if t >= n:
t = 0
if not self.bmt_lista.siTerminado(t):
self.activaPosicion(t)
return
self.activaPosicion(desde)
def activaJugada1(self, num):
rm = self.bmt_uno.mrm.liMultiPV[num]
partida = Partida.Partida()
partida.recuperaDeTexto(rm.txtPartida)
bt = self.liBTrm[num]
txt = "%d: %s = %s" % (
rm.nivelBMT + 1,
partida.jugada(0).pgnSP(),
rm.abrTexto(),
)
if rm.siPrimero:
txt = "%s *" % txt
self.lbPrimera.setVisible(True)
bt.ponTexto(txt)
bt.setEnabled(True)
bt.ponPlano(False)
def activaJugada(self, num):
rm = self.bmt_uno.mrm.liMultiPV[num]
if rm.nivelBMT == 0:
self.finalizaTiempo()
for n in range(len(self.bmt_uno.mrm.liMultiPV)):
self.activaJugada1(n)
self.bmt_uno.siTerminado = True
self.muestra(num)
self.ponPuntos(0)
bt = self.liBT[self.actualP]
bt.ponIcono(self.dicIconos[self.bmt_uno.estado])
self.siTerminada = self.bmt_lista.siTerminada()
self.ponToolBar()
else:
self.activaJugada1(num)
def activaPosicion(self, num):
self.finalizaTiempo() # Para que guarde el tiempo, si no es el primero
self.bmt_uno = bmt_uno = self.bmt_lista.dameUno(num)
mrm = bmt_uno.mrm
tm = mrm.maxTiempo
dp = mrm.maxProfundidad
if tm > 0:
txt = " %d %s" % (tm / 1000, _("Second(s)"))
elif dp > 0:
txt = " %s %d" % (_("depth"), dp)
else:
txt = ""
self.posicion.leeFen(bmt_uno.fen)
mens = ""
if self.posicion.enroques:
color, colorR = _("White"), _("Black")
cK, cQ, cKR, cQR = "K", "Q", "k", "q"
def menr(ck, cq):
enr = ""
if ck in self.posicion.enroques:
enr += "O-O"
if cq in self.posicion.enroques:
if enr:
enr += " + "
enr += "O-O-O"
return enr
enr = menr(cK, cQ)
if enr:
mens += " %s : %s" % (color, enr)
enr = menr(cKR, cQR)
if enr:
mens += " %s : %s" % (colorR, enr)
if self.posicion.alPaso != "-":
mens += " %s : %s" % (_("En passant"), self.posicion.alPaso)
if mens:
txt += " - " + mens
self.lbCondiciones.ponTexto(mrm.nombre + txt)
self.tablero.ponPosicion(self.posicion)
self.liBT[self.actualP].ponPlano(True)
self.liBT[num].ponPlano(False)
self.actualP = num
nliRM = len(mrm.liMultiPV)
partida = Partida.Partida()
for x in range(16):
bt = self.liBTrm[x]
if x < nliRM:
rm = mrm.liMultiPV[x]
bt.setVisible(True)
bt.ponPlano(not rm.siElegida)
baseTxt = str(rm.nivelBMT + 1)
if rm.siElegida:
partida.reset(self.posicion)
partida.leerPV(rm.pv)
baseTxt += " - " + partida.jugada(0).pgnSP()
bt.ponTexto(baseTxt)
else:
bt.setVisible(False)
self.ponPuntos(0)
self.ponSegundos()
self.ponToolBar()
if bmt_uno.siTerminado:
self.activaJugada(0)
self.muestra(0)
else:
self.lbPrimera.setVisible(False)
self.iniciaTiempo()
self.sigueHumano()
def mueveHumano(self, desde, hasta, coronacion=None):
self.paraHumano()
movimiento = desde + hasta
# Peon coronando
if not coronacion and self.posicion.siPeonCoronando(desde, hasta):
coronacion = self.tablero.peonCoronando(self.posicion.siBlancas)
if coronacion is None:
self.sigueHumano()
return False
if coronacion:
movimiento += coronacion
nElegido = None
puntosDescontar = self.bmt_uno.mrm.liMultiPV[-1].nivelBMT
for n, rm in enumerate(self.bmt_uno.mrm.liMultiPV):
if rm.pv.lower().startswith(movimiento.lower()):
nElegido = n
puntosDescontar = rm.nivelBMT
break
self.ponPuntos(puntosDescontar)
if nElegido is not None:
self.activaJugada(nElegido)
if not self.bmt_uno.siTerminado:
self.sigueHumano()
return True
def paraHumano(self):
self.tablero.desactivaTodas()
def sigueHumano(self):
self.siMostrarPGN = False
self.pgn.refresh()
siW = self.posicion.siBlancas
self.tablero.ponPosicion(self.posicion)
self.tablero.ponerPiezasAbajo(siW)
self.tablero.ponIndicador(siW)
self.tablero.activaColor(siW)
self.lbJuegan.ponTexto(_("White to play") if siW else _("Black to play"))
def ponReloj(self):
self.timer = QtCore.QTimer(self)
self.connect(self.timer, QtCore.SIGNAL("timeout()"), self.enlaceReloj)
self.timer.start(500)
def quitaReloj(self):
if self.timer:
self.timer.stop()
self.timer = None
def enlaceReloj(self):
self.ponSegundos()
def original(self):
self.siMostrarPGN = True
self.lbJuegan.ponTexto(_("Actual game"))
txtPartida = self.bmt_lista.dicPartidas[self.bmt_uno.clpartida]
self.partida.recuperaDeTexto(txtPartida)
siW = self.posicion.siBlancas
fen = self.posicion.fen()
fila = 0
for jg in self.partida.liJugadas:
if jg.posicionBase.fen() == fen:
break
if not jg.posicionBase.siBlancas:
fila += 1
self.pgnMueveBase(fila, "BLANCAS" if siW else "NEGRAS")
self.pgn.goto(fila, 1 if siW else 2)
self.tablero.ponerPiezasAbajo(siW)
self.pgn.refresh()
def muestra(self, num):
for n, bt in enumerate(self.liBTrm):
f = bt.font()
siBold = f.bold()
if (num == n and not siBold) or (num != n and siBold):
f.setBold(not siBold)
bt.setFont(f)
bt.setAutoDefault(num == n)
bt.setDefault(num == n)
self.siMostrarPGN = True
self.lbJuegan.ponTexto(self.liBTrm[num].text())
self.partida.reset(self.posicion)
rm = self.bmt_uno.mrm.liMultiPV[num]
self.partida.recuperaDeTexto(rm.txtPartida)
siW = self.posicion.siBlancas
self.pgnMueveBase(0, "BLANCAS" if siW else "NEGRAS")
self.pgn.goto(0, 1 if siW else 2)
self.tablero.ponerPiezasAbajo(siW)
self.pgn.refresh()
def iniciaTiempo(self):
self.iniTiempo = time.time()
if not self.timer:
self.ponReloj()
def finalizaTiempo(self):
if self.iniTiempo:
tiempo = time.time() - self.iniTiempo
self.bmt_uno.segundos += int(tiempo)
self.iniTiempo = None
self.quitaReloj()
def dameJugadaEn(self, fila, clave):
siBlancas = clave != "NEGRAS"
pos = fila * 2
if not siBlancas:
pos += 1
if self.partida.siEmpiezaConNegras:
pos -= 1
tam_lj = self.partida.numJugadas()
if tam_lj == 0:
return
siUltimo = (pos + 1) >= tam_lj
jg = self.partida.jugada(pos)
return jg, siBlancas, siUltimo, tam_lj, pos
def analizaPosicion(self, fila, clave):
if fila < 0:
return
jg, siBlancas, siUltimo, tam_lj, pos = self.dameJugadaEn(fila, clave)
if jg.siJaqueMate:
return
maxRecursion = 9999
Analisis.muestraAnalisis(
self.procesador,
self.procesador.XTutor(),
jg,
siBlancas,
maxRecursion,
pos,
pantalla=self,
)
class WBMT(QTVarios.WDialogo):
def __init__(self, procesador):
self.procesador = procesador
self.configuracion = procesador.configuracion
self.configuracion.compruebaBMT()
self.bmt = BMT.BMT(self.configuracion.ficheroBMT)
self.leerDBF()
owner = procesador.pantalla
icono = Iconos.BMT()
titulo = self.titulo()
extparam = "bmt"
QTVarios.WDialogo.__init__(self, owner, titulo, icono, extparam)
# Toolbar
liAcciones = [
(_("Close"), Iconos.MainMenu(), self.terminar),
None,
(_("Play"), Iconos.Empezar(), self.entrenar),
None,
(_("New"), Iconos.Nuevo(), self.nuevo),
None,
(_("Modify"), Iconos.Modificar(), self.modificar),
None,
(_("Remove"), Iconos.Borrar(), self.borrar),
None,
(_("Track record"), Iconos.Historial(), self.historial),
None,
(_("Utilities"), Iconos.Utilidades(), self.utilidades),
]
tb = QTVarios.LCTB(self, liAcciones)
self.tab = tab = Controles.Tab()
# Lista
oColumnas = Columnas.ListaColumnas()
oColumnas.nueva("NOMBRE", _("Name"), 274, edicion=Delegados.LineaTextoUTF8())
oColumnas.nueva("EXTRA", _("Extra info."), 64, siCentrado=True)
oColumnas.nueva("HECHOS", _("Made"), 84, siCentrado=True)
oColumnas.nueva("PUNTOS", _("Points"), 84, siCentrado=True)
oColumnas.nueva("TIEMPO", _("Time"), 80, siCentrado=True)
oColumnas.nueva("REPETICIONES", _("Rep."), 50, siCentrado=True)
oColumnas.nueva("ORDEN", _("Order"), 70, siCentrado=True)
self.grid = grid = Grid.Grid(
self,
oColumnas,
xid="P",
siEditable=False,
siSelecFilas=True,
siSeleccionMultiple=True,
)
self.registrarGrid(grid)
tab.nuevaTab(grid, _("Pending"))
# Terminados
oColumnas = Columnas.ListaColumnas()
oColumnas.nueva(
"ESTADO", "", 26, edicion=Delegados.PmIconosBMT(), siCentrado=True
)
oColumnas.nueva("NOMBRE", _("Name"), 240)
oColumnas.nueva("EXTRA", _("Extra info."), 64, siCentrado=True)
oColumnas.nueva("HECHOS", _("Positions"), 64, siCentrado=True)
oColumnas.nueva("PUNTOS", _("Points"), 84, siCentrado=True)
oColumnas.nueva("FFINAL", _("End date"), 90, siCentrado=True)
oColumnas.nueva("TIEMPO", _("Time"), 80, siCentrado=True)
oColumnas.nueva("REPETICIONES", _("Rep."), 50, siCentrado=True)
oColumnas.nueva("ORDEN", _("Order"), 70, siCentrado=True)
self.gridT = gridT = Grid.Grid(
self,
oColumnas,
xid="T",
siEditable=True,
siSelecFilas=True,
siSeleccionMultiple=True,
)
self.registrarGrid(gridT)
tab.nuevaTab(gridT, _("Finished"))
self.dicReverse = {}
# Layout
layout = Colocacion.V().control(tb).control(tab).margen(8)
self.setLayout(layout)
self.recuperarVideo(siTam=True, anchoDefecto=760)
self.grid.gotop()
self.gridT.gotop()
self.grid.setFocus()
def titulo(self):
fdir, fnam = os.path.split(self.configuracion.ficheroBMT)
return "%s : %s (%s)" % (_("Find best move"), fnam, fdir)
def terminar(self):
self.bmt.cerrar()
self.guardarVideo()
self.reject()
return
def actual(self):
if self.tab.posActual() == 0:
grid = self.grid
dbf = self.dbf
else:
grid = self.gridT
dbf = self.dbfT
recno = grid.recno()
if recno >= 0:
dbf.goto(recno)
return grid, dbf, recno
def historial(self):
grid, dbf, recno = self.actual()
if recno >= 0:
if dbf.REPE:
w = WHistorialBMT(self, dbf)
w.exec_()
def utilidades(self):
menu = QTVarios.LCMenu(self)
menu.opcion(
"cambiar", _("Select/create another file of training"), Iconos.BMT()
)
menu.separador()
menu1 = menu.submenu(_("Import") + "/" + _("Export"), Iconos.PuntoMagenta())
menu1.opcion("exportar", _("Export the current training"), Iconos.PuntoVerde())
menu1.separador()
menu1.opcion(
"exportarLimpio",
_("Export Current training with no history"),
Iconos.PuntoAzul(),
)
menu1.separador()
menu1.opcion("importar", _("Import a training"), Iconos.PuntoNaranja())
menu.separador()
menu2 = menu.submenu(_("Generate new trainings"), Iconos.PuntoRojo())
menu2.opcion("dividir", _("Dividing the active training"), Iconos.PuntoVerde())
menu2.separador()
menu2.opcion("extraer", _("Extract a range of positions"), Iconos.PuntoAzul())
menu2.separador()
menu2.opcion("juntar", _("Joining selected training"), Iconos.PuntoNaranja())
menu2.separador()
menu2.opcion("rehacer", _("Analyze again"), Iconos.PuntoAmarillo())
resp = menu.lanza()
if resp:
if resp == "cambiar":
self.cambiar()
elif resp == "importar":
self.importar()
elif resp.startswith("exportar"):
self.exportar(resp == "exportarLimpio")
elif resp == "dividir":
self.dividir()
elif resp == "extraer":
self.extraer()
elif resp == "juntar":
self.juntar()
elif resp == "pack":
self.pack()
elif resp == "rehacer":
self.rehacer()
def pack(self):
um = QTUtil2.unMomento(self)
self.dbf.pack()
self.releer()
um.final()
def rehacer(self):
grid, dbf, recno = self.actual()
if recno < 0:
return
nombre = dbf.NOMBRE
extra = dbf.EXTRA
bmt_lista = Util.blob2var(dbf.leeOtroCampo(recno, "BMT_LISTA"))
# Motor y tiempo, cogemos los estandars de analisis
fichero = self.configuracion.ficheroAnalisis
dic = Util.recuperaVar(fichero)
if dic:
motor = dic["MOTOR"]
tiempo = dic["TIEMPO"]
else:
motor = self.configuracion.tutor.clave
tiempo = self.configuracion.tiempoTutor
# Bucle para control de errores
liGen = [(None, None)]
# # Nombre del entrenamiento
liGen.append((_("Name") + ":", nombre))
liGen.append((_("Extra info.") + ":", extra))
# # Tutor
li = self.configuracion.ayudaCambioTutor()
li[0] = motor
liGen.append((_("Engine") + ":", li))
# Decimas de segundo a pensar el tutor
liGen.append((_("Duration of engine analysis (secs)") + ":", tiempo / 1000.0))
liGen.append((None, None))
resultado = FormLayout.fedit(
liGen, title=nombre, parent=self, anchoMinimo=560, icon=Iconos.Opciones()
)
if not resultado:
return
accion, liGen = resultado
nombre = liGen[0]
extra = liGen[1]
motor = liGen[2]
tiempo = int(liGen[3] * 1000)
if not tiempo or not nombre:
return
dic = {"MOTOR": motor, "TIEMPO": tiempo}
Util.guardaVar(fichero, dic)
# Analizamos todos, creamos las partidas, y lo salvamos
confMotor = self.configuracion.buscaMotor(motor)
confMotor.multiPV = 16
xgestor = self.procesador.creaGestorMotor(confMotor, tiempo, None, True)
tamLista = len(bmt_lista.liBMT_Uno)
mensaje = _("Analyzing the move....")
tmpBP = QTUtil2.BarraProgreso(
self.procesador.pantalla, nombre, mensaje, tamLista
).mostrar()
cp = ControlPosicion.ControlPosicion()
siCancelado = False
partida = Partida.Partida()
for pos in range(tamLista):
uno = bmt_lista.dameUno(pos)
fen = uno.fen
ant_movimiento = ""
for rm in uno.mrm.liMultiPV:
if rm.siPrimero:
ant_movimiento = rm.movimiento()
break
tmpBP.mensaje(mensaje + " %d/%d" % (pos, tamLista))
tmpBP.pon(pos)
if tmpBP.siCancelado():
siCancelado = True
break
mrm = xgestor.analiza(fen)
cp.leeFen(fen)
previa = 999999999
nprevia = -1
tniv = 0
for rm in mrm.liMultiPV:
if tmpBP.siCancelado():
siCancelado = True
break
pts = rm.puntosABS()
if pts != previa:
previa = pts
nprevia += 1
tniv += nprevia
rm.nivelBMT = nprevia
rm.siElegida = False
rm.siPrimero = rm.movimiento() == ant_movimiento
partida.reset(cp)
partida.leerPV(rm.pv)
rm.txtPartida = partida.guardaEnTexto()
if siCancelado:
break
uno.mrm = mrm # lo cambiamos y ya esta
xgestor.terminar()
if not siCancelado:
# Grabamos
bmt_lista.reiniciar()
reg = self.dbf.baseRegistro()
reg.ESTADO = "0"
reg.NOMBRE = nombre
reg.EXTRA = extra
reg.TOTAL = len(bmt_lista)
reg.HECHOS = 0
reg.PUNTOS = 0
reg.MAXPUNTOS = bmt_lista.maxPuntos()
reg.FINICIAL = Util.dtos(Util.hoy())
reg.FFINAL = ""
reg.SEGUNDOS = 0
reg.BMT_LISTA = Util.var2blob(bmt_lista)
reg.HISTORIAL = Util.var2blob([])
reg.REPE = 0
reg.ORDEN = 0
self.dbf.insertarReg(reg, siReleer=True)
tmpBP.cerrar()
self.grid.refresh()
def gridDobleClickCabecera(self, grid, oColumna):
clave = oColumna.clave
if clave != "NOMBRE":
return
grid, dbf, recno = self.actual()
li = []
for x in range(dbf.reccount()):
dbf.goto(x)
li.append((dbf.NOMBRE, x))
li.sort(key=lambda x: x[0])
siReverse = self.dicReverse.get(grid.id, False)
self.dicReverse[grid.id] = not siReverse
if siReverse:
li.reverse()
order = 0
reg = dbf.baseRegistro()
for nom, recno in li:
reg.ORDEN = order
dbf.modificarReg(recno, reg)
order += 1
dbf.commit()
dbf.leer()
grid.refresh()
grid.gotop()
def dividir(self):
grid, dbf, recno = self.actual()
if recno < 0:
return
reg = (
dbf.registroActual()
) # Importante ya que dbf puede cambiarse mientras se edita
liGen = [(None, None)]
mx = dbf.TOTAL
if mx <= 1:
return
bl = mx / 2
liGen.append((FormLayout.Spinbox(_("Block Size"), 1, mx - 1, 50), bl))
resultado = FormLayout.fedit(
liGen,
title="%s %s" % (reg.NOMBRE, reg.EXTRA),
parent=self,
icon=Iconos.Opciones(),
)
if resultado:
accion, liGen = resultado
bl = liGen[0]
um = QTUtil2.unMomento(self)
bmt_lista = Util.blob2var(dbf.leeOtroCampo(recno, "BMT_LISTA"))
desde = 0
pos = 1
extra = reg.EXTRA
while desde < mx:
hasta = desde + bl
if hasta >= mx:
hasta = mx
bmt_listaNV = bmt_lista.extrae(desde, hasta)
reg.TOTAL = hasta - desde
reg.BMT_LISTA = Util.var2blob(bmt_listaNV)
reg.HISTORIAL = Util.var2blob([])
reg.REPE = 0
reg.ESTADO = "0"
reg.EXTRA = (extra + " (%d)" % pos).strip()
pos += 1
reg.HECHOS = 0
reg.PUNTOS = 0
reg.MAXPUNTOS = bmt_listaNV.maxPuntos()
reg.FFINAL = ""
reg.SEGUNDOS = 0
dbf.insertarReg(reg, siReleer=False)
desde = hasta
self.releer()
um.final()
def extraer(self):
grid, dbf, recno = self.actual()
if recno < 0:
return
reg = (
dbf.registroActual()
) # Importante ya que dbf puede cambiarse mientras se edita
liGen = [(None, None)]
config = FormLayout.Editbox(
'<div align="right">'
+ _("List of positions")
+ "<br>"
+ _("By example:")
+ " -5,7-9,14,19-",
rx="[0-9,\-,\,]*",
)
liGen.append((config, ""))
resultado = FormLayout.fedit(
liGen,
title=reg.NOMBRE,
parent=self,
anchoMinimo=200,
icon=Iconos.Opciones(),
)
if resultado:
accion, liGen = resultado
bmt_lista = Util.blob2var(dbf.leeOtroCampo(recno, "BMT_LISTA"))
clista = liGen[0]
if clista:
lni = Util.ListaNumerosImpresion(clista)
bmt_listaNV = bmt_lista.extraeLista(lni)
reg.TOTAL = len(bmt_listaNV)
reg.BMT_LISTA = Util.var2blob(bmt_listaNV)
reg.HISTORIAL = Util.var2blob([])
reg.REPE = 0
reg.ESTADO = "0"
reg.EXTRA = clista
reg.HECHOS = 0
reg.PUNTOS = 0
reg.MAXPUNTOS = bmt_listaNV.maxPuntos()
reg.FFINAL = ""
reg.SEGUNDOS = 0
um = QTUtil2.unMomento(self)
dbf.insertarReg(reg, siReleer=False)
self.releer()
um.final()
def juntar(self):
grid, dbf, recno = self.actual()
orden = dbf.ORDEN
nombre = dbf.NOMBRE
extra = dbf.EXTRA
# Lista de recnos
li = grid.recnosSeleccionados()
if len(li) <= 1:
return
# Se pide nombre y extra
liGen = [(None, None)]
# # Nombre del entrenamiento
liGen.append((_("Name") + ":", nombre))
liGen.append((_("Extra info.") + ":", extra))
liGen.append((FormLayout.Editbox(_("Order"), tipo=int, ancho=50), orden))
titulo = "%s (%d)" % (_("Joining selected training"), len(li))
resultado = FormLayout.fedit(
liGen, title=titulo, parent=self, anchoMinimo=560, icon=Iconos.Opciones()
)
if not resultado:
return
um = QTUtil2.unMomento(self)
accion, liGen = resultado
nombre = liGen[0].strip()
extra = liGen[1]
orden = liGen[2]
# Se crea una bmt_lista, suma de todas
bmt_lista = BMT.BMT_Lista()
for recno in li:
bmt_lista1 = Util.blob2var(dbf.leeOtroCampo(recno, "BMT_LISTA"))
for uno in bmt_lista1.liBMT_Uno:
bmt_lista.nuevo(uno)
if uno.clpartida:
bmt_lista.compruebaPartida(
uno.clpartida, bmt_lista1.dicPartidas[uno.clpartida]
)
bmt_lista.reiniciar()
# Se graba el registro
reg = dbf.baseRegistro()
reg.ESTADO = "0"
reg.NOMBRE = nombre
reg.EXTRA = extra
reg.TOTAL = len(bmt_lista)
reg.HECHOS = 0
reg.PUNTOS = 0
reg.MAXPUNTOS = bmt_lista.maxPuntos()
reg.FINICIAL = Util.dtos(Util.hoy())
reg.FFINAL = ""
reg.SEGUNDOS = 0
reg.BMT_LISTA = Util.var2blob(bmt_lista)
reg.HISTORIAL = Util.var2blob([])
reg.REPE = 0
reg.ORDEN = orden
dbf.insertarReg(reg, siReleer=False)
self.releer()
um.final()
def cambiar(self):
fbmt = QTUtil2.salvaFichero(
self,
_("Select/create another file of training"),
self.configuracion.ficheroBMT,
_("File") + " bmt (*.bmt)",
siConfirmarSobreescritura=False,
)
if fbmt:
fbmt = Util.dirRelativo(fbmt)
abmt = self.bmt
try:
self.bmt = BMT.BMT(fbmt)
except:
QTUtil2.mensError(self, _X(_("Unable to read file %1"), fbmt))
return
abmt.cerrar()
self.leerDBF()
self.configuracion.ficheroBMT = fbmt
self.configuracion.graba()
self.setWindowTitle(self.titulo())
self.grid.refresh()
self.gridT.refresh()
def exportar(self, siLimpiar):
grid, dbf, recno = self.actual()
if recno >= 0:
regActual = dbf.registroActual()
carpeta = os.path.dirname(self.configuracion.ficheroBMT)
filtro = _("File") + " bm1 (*.bm1)"
fbm1 = QTUtil2.salvaFichero(
self,
_("Export the current training"),
carpeta,
filtro,
siConfirmarSobreescritura=True,
)
if fbm1:
if siLimpiar:
regActual.ESTADO = "0"
regActual.HECHOS = 0
regActual.PUNTOS = 0
regActual.FFINAL = ""
regActual.SEGUNDOS = 0
bmt_lista = Util.blob2var(dbf.leeOtroCampo(recno, "BMT_LISTA"))
bmt_lista.reiniciar()
regActual.BMT_LISTA = bmt_lista
regActual.HISTORIAL = []
regActual.REPE = 0
else:
regActual.BMT_LISTA = Util.blob2var(
dbf.leeOtroCampo(recno, "BMT_LISTA")
)
regActual.HISTORIAL = Util.blob2var(
dbf.leeOtroCampo(recno, "HISTORIAL")
)
Util.guardaVar(fbm1, regActual)
def modificar(self):
grid, dbf, recno = self.actual()
if recno >= 0:
dbf.goto(recno)
nombre = dbf.NOMBRE
extra = dbf.EXTRA
orden = dbf.ORDEN
liGen = [(None, None)]
# # Nombre del entrenamiento
liGen.append((_("Name") + ":", nombre))
liGen.append((_("Extra info.") + ":", extra))
liGen.append((FormLayout.Editbox(_("Order"), tipo=int, ancho=50), orden))
resultado = FormLayout.fedit(
liGen,
title=nombre,
parent=self,
anchoMinimo=560,
icon=Iconos.Opciones(),
)
if resultado:
accion, liGen = resultado
liCamposValor = (
("NOMBRE", liGen[0].strip()),
("EXTRA", liGen[1]),
("ORDEN", liGen[2]),
)
self.grabaCampos(grid, recno, liCamposValor)
def releer(self):
self.dbf.leer()
self.dbfT.leer()
self.grid.refresh()
self.gridT.refresh()
QTUtil.refreshGUI()
def importar(self):
carpeta = os.path.dirname(self.configuracion.ficheroBMT)
filtro = _("File") + " bm1 (*.bm1)"
fbm1 = QTUtil2.leeFichero(self, carpeta, filtro, titulo=_("Import a training"))
if fbm1:
reg = Util.recuperaVar(fbm1)
if hasattr(reg, "BMT_LISTA"):
reg.BMT_LISTA = Util.var2blob(reg.BMT_LISTA)
reg.HISTORIAL = Util.var2blob(reg.HISTORIAL)
self.dbf.insertarReg(reg, siReleer=False)
self.releer()
else:
QTUtil2.mensError(self, _X(_("Unable to read file %1"), fbm1))
def entrenar(self):
grid, dbf, recno = self.actual()
if recno >= 0:
w = WEntrenarBMT(self, dbf)
w.exec_()
self.releer()
def borrar(self):
grid, dbf, recno = self.actual()
li = grid.recnosSeleccionados()
if len(li) > 0:
tit = "<br><ul>"
for x in li:
dbf.goto(x)
tit += "<li>%s %s</li>" % (dbf.NOMBRE, dbf.EXTRA)
base = _("the following training")
if QTUtil2.pregunta(self, _X(_("Delete %1?"), base) + tit):
um = QTUtil2.unMomento(self)
dbf.borrarLista(li)
dbf.pack()
self.releer()
um.final()
def grabaCampos(self, grid, fila, liCamposValor):
dbf = self.dbfT if grid.id == "T" else self.dbf
reg = dbf.baseRegistro()
for campo, valor in liCamposValor:
setattr(reg, campo, valor)
dbf.modificarReg(fila, reg)
dbf.commit()
dbf.leer()
grid.refresh()
def gridPonValor(
self, grid, fila, oColumna, valor
): # ? necesario al haber delegados
pass
def gridNumDatos(self, grid):
dbf = self.dbfT if grid.id == "T" else self.dbf
return dbf.reccount()
def gridDobleClick(self, grid, fila, columna):
self.entrenar()
def gridDato(self, grid, fila, oColumna):
dbf = self.dbfT if grid.id == "T" else self.dbf
col = oColumna.clave
dbf.goto(fila)
if col == "NOMBRE":
return dbf.NOMBRE
elif col == "ORDEN":
return dbf.ORDEN if dbf.ORDEN else 0
elif col == "ESTADO":
return dbf.ESTADO
elif col == "HECHOS":
if grid.id == "T":
return "%d" % dbf.TOTAL
else:
return "%d/%d" % (dbf.HECHOS, dbf.TOTAL)
elif col == "PUNTOS":
p = dbf.PUNTOS
m = dbf.MAXPUNTOS
if grid.id == "T":
porc = p * 100 / m
return "%d/%d=%d" % (p, m, porc) + "%"
else:
return "%d/%d" % (p, m)
elif col == "EXTRA":
return dbf.EXTRA
elif col == "FFINAL":
f = dbf.FFINAL
return "%s-%s-%s" % (f[6:], f[4:6], f[:4]) if f else ""
elif col == "TIEMPO":
s = dbf.SEGUNDOS
if not s:
s = 0
m = s / 60
s %= 60
return "%d' %d\"" % (m, s) if m else '%d"' % s
elif col == "REPETICIONES":
return str(dbf.REPE)
def leerDBF(self):
self.dbf = self.bmt.leerDBF(False)
self.dbfT = self.bmt.leerDBF(True)
def nuevo(self):
tpirat = Controles.TipoLetra(
"Chess Diagramm Pirat", self.configuracion.puntosMenu + 4
)
def xopcion(menu, clave, texto, icono, siDeshabilitado=False):
if "KP" in texto:
d = {"K": "r", "P": "w", "k": chr(126), "p": chr(134)}
k2 = texto.index("K", 2)
texto = texto[:k2] + texto[k2:].lower()
texton = ""
for c in texto:
texton += d[c]
menu.opcion(clave, texton, icono, siDeshabilitado, tipoLetra=tpirat)
else:
menu.opcion(clave, texto, icono, siDeshabilitado)
# Elegimos el entrenamiento
menu = QTVarios.LCMenu(self)
self.procesador.entrenamientos.menuFNS(
menu, _("Select the training positions you want to use as a base"), xopcion
)
resp = menu.lanza()
if resp is None:
return
fns = resp[3:]
f = open(fns, "rb")
liFEN = []
for linea in f:
linea = linea.strip()
if linea:
if "|" in linea:
linea = linea.split("|")[0]
liFEN.append(linea)
nFEN = len(liFEN)
if not nFEN:
return
nombre = os.path.basename(fns)[:-4]
nombre = TrListas.dicTraining().get(nombre, nombre)
# Motor y tiempo, cogemos los estandars de analisis
fichero = self.configuracion.ficheroAnalisis
dic = Util.recuperaVar(fichero)
if dic:
motor = dic["MOTOR"]
tiempo = dic["TIEMPO"]
else:
motor = self.configuracion.tutor.clave
tiempo = self.configuracion.tiempoTutor
if not tiempo:
tiempo = 3.0
# Bucle para control de errores
while True:
# Datos
liGen = [(None, None)]
# # Nombre del entrenamiento
liGen.append((_("Name") + ":", nombre))
# # Tutor
li = self.configuracion.ayudaCambioTutor()
li[0] = motor
liGen.append((_("Engine") + ":", li))
# Decimas de segundo a pensar el tutor
liGen.append(
(_("Duration of engine analysis (secs)") + ":", tiempo / 1000.0)
)
liGen.append((None, None))
liGen.append((FormLayout.Spinbox(_("From number"), 1, nFEN, 50), 1))
liGen.append(
(
FormLayout.Spinbox(_("To number"), 1, nFEN, 50),
nFEN if nFEN < 20 else 20,
)
)
resultado = FormLayout.fedit(
liGen,
title=nombre,
parent=self,
anchoMinimo=560,
icon=Iconos.Opciones(),
)
if resultado:
accion, liGen = resultado
nombre = liGen[0]
motor = liGen[1]
tiempo = int(liGen[2] * 1000)
if not tiempo or not nombre:
return
dic = {"MOTOR": motor, "TIEMPO": tiempo}
Util.guardaVar(fichero, dic)
desde = liGen[3]
hasta = liGen[4]
nDH = hasta - desde + 1
if nDH <= 0:
return
break
else:
return
# Analizamos todos, creamos las partidas, y lo salvamos
confMotor = self.configuracion.buscaMotor(motor)
confMotor.multiPV = 16
xgestor = self.procesador.creaGestorMotor(confMotor, tiempo, None, True)
mensaje = _("Analyzing the move....")
tmpBP = QTUtil2.BarraProgreso(
self.procesador.pantalla, nombre, mensaje, nDH
).mostrar()
cp = ControlPosicion.ControlPosicion()
siCancelado = False
bmt_lista = BMT.BMT_Lista()
partida = Partida.Partida()
for n in range(desde - 1, hasta):
fen = liFEN[n]
tmpBP.mensaje(mensaje + " %d/%d" % (n + 2 - desde, nDH))
tmpBP.pon(n + 2 - desde)
if tmpBP.siCancelado():
siCancelado = True
break
mrm = xgestor.analiza(fen)
cp.leeFen(fen)
previa = 999999999
nprevia = -1
tniv = 0
for rm in mrm.liMultiPV:
if tmpBP.siCancelado():
siCancelado = True
break
pts = rm.puntosABS()
if pts != previa:
previa = pts
nprevia += 1
tniv += nprevia
rm.nivelBMT = nprevia
rm.siElegida = False
rm.siPrimero = False
partida.reset(cp)
partida.leerPV(rm.pv)
partida.siTerminada()
rm.txtPartida = partida.guardaEnTexto()
if siCancelado:
break
bmt_uno = BMT.BMT_Uno(fen, mrm, tniv, None)
bmt_lista.nuevo(bmt_uno)
xgestor.terminar()
if not siCancelado:
# Grabamos
reg = self.dbf.baseRegistro()
reg.ESTADO = "0"
reg.NOMBRE = nombre
reg.EXTRA = "%d-%d" % (desde, hasta)
reg.TOTAL = len(bmt_lista)
reg.HECHOS = 0
reg.PUNTOS = 0
reg.MAXPUNTOS = bmt_lista.maxPuntos()
reg.FINICIAL = Util.dtos(Util.hoy())
reg.FFINAL = ""
reg.SEGUNDOS = 0
reg.BMT_LISTA = Util.var2blob(bmt_lista)
reg.HISTORIAL = Util.var2blob([])
reg.REPE = 0
reg.ORDEN = 0
self.dbf.insertarReg(reg, siReleer=True)
self.releer()
tmpBP.cerrar()
def pantallaBMT(procesador):
w = WBMT(procesador)
w.exec_()
|
core | Constants | """
Copyright 2008-2016 Free Software Foundation, Inc.
Copyright 2021 GNU Radio contributors
This file is part of GNU Radio
SPDX-License-Identifier: GPL-2.0-or-later
"""
import numbers
import os
import stat
import numpy
# Data files
DATA_DIR = os.path.dirname(__file__)
BLOCK_DTD = os.path.join(DATA_DIR, "block.dtd")
DEFAULT_FLOW_GRAPH = os.path.join(DATA_DIR, "default_flow_graph.grc")
DEFAULT_HIER_BLOCK_LIB_DIR = os.path.expanduser("~/.grc_gnuradio")
DEFAULT_FLOW_GRAPH_ID = "default"
CACHE_FILE = os.path.expanduser("~/.cache/grc_gnuradio/cache_v2.json")
BLOCK_DESCRIPTION_FILE_FORMAT_VERSION = 1
# File format versions:
# 0: undefined / legacy
# 1: non-numeric message port keys (label is used instead)
FLOW_GRAPH_FILE_FORMAT_VERSION = 1
# Param tabs
DEFAULT_PARAM_TAB = "General"
ADVANCED_PARAM_TAB = "Advanced"
DEFAULT_BLOCK_MODULE_NAME = "(no module specified)"
# Port domains
GR_STREAM_DOMAIN = "stream"
GR_MESSAGE_DOMAIN = "message"
DEFAULT_DOMAIN = GR_STREAM_DOMAIN
# File creation modes
TOP_BLOCK_FILE_MODE = (
stat.S_IRUSR
| stat.S_IWUSR
| stat.S_IXUSR
| stat.S_IRGRP
| stat.S_IWGRP
| stat.S_IXGRP
| stat.S_IROTH
)
HIER_BLOCK_FILE_MODE = (
stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IWGRP | stat.S_IROTH
)
PARAM_TYPE_NAMES = {
"raw",
"enum",
"complex",
"real",
"float",
"int",
"short",
"byte",
"complex_vector",
"real_vector",
"float_vector",
"int_vector",
"hex",
"string",
"bool",
"file_open",
"file_save",
"dir_select",
"_multiline",
"_multiline_python_external",
"id",
"stream_id",
"name",
"gui_hint",
"import",
}
PARAM_TYPE_MAP = {
"complex": numbers.Complex,
"float": numbers.Real,
"real": numbers.Real,
"int": numbers.Integral,
}
# Define types, native python + numpy
VECTOR_TYPES = (tuple, list, set, numpy.ndarray)
# Updating colors. Using the standard color palette from:
# http://www.google.com/design/spec/style/color.html#color-color-palette
# Most are based on the main, primary color standard. Some are within
# that color's spectrum when it was deemed necessary.
GRC_COLOR_BROWN = "#795548"
GRC_COLOR_BLUE = "#2196F3"
GRC_COLOR_LIGHT_GREEN = "#8BC34A"
GRC_COLOR_GREEN = "#4CAF50"
GRC_COLOR_AMBER = "#FFC107"
GRC_COLOR_PURPLE = "#9C27B0"
GRC_COLOR_CYAN = "#00BCD4"
GRC_COLOR_GR_ORANGE = "#FF6905"
GRC_COLOR_ORANGE = "#F57C00"
GRC_COLOR_LIME = "#CDDC39"
GRC_COLOR_TEAL = "#009688"
GRC_COLOR_YELLOW = "#FFEB3B"
GRC_COLOR_PINK = "#F50057"
GRC_COLOR_PURPLE_A100 = "#EA80FC"
GRC_COLOR_PURPLE_A400 = "#D500F9"
GRC_COLOR_DARK_GREY = "#72706F"
GRC_COLOR_GREY = "#BDBDBD"
GRC_COLOR_WHITE = "#FFFFFF"
CORE_TYPES = ( # name, key, sizeof, color
("Complex Float 64", "fc64", 16, GRC_COLOR_BROWN),
("Complex Float 32", "fc32", 8, GRC_COLOR_BLUE),
("Complex Integer 64", "sc64", 16, GRC_COLOR_LIGHT_GREEN),
("Complex Integer 32", "sc32", 8, GRC_COLOR_GREEN),
("Complex Integer 16", "sc16", 4, GRC_COLOR_AMBER),
("Complex Integer 8", "sc8", 2, GRC_COLOR_PURPLE),
("Float 64", "f64", 8, GRC_COLOR_CYAN),
("Float 32", "f32", 4, GRC_COLOR_ORANGE),
("Integer 64", "s64", 8, GRC_COLOR_LIME),
("Integer 32", "s32", 4, GRC_COLOR_TEAL),
("Integer 16", "s16", 2, GRC_COLOR_YELLOW),
("Integer 8", "s8", 1, GRC_COLOR_PURPLE_A400),
("Bits (unpacked byte)", "bit", 1, GRC_COLOR_PURPLE_A100),
("Async Message", "message", 0, GRC_COLOR_GREY),
("Bus Connection", "bus", 0, GRC_COLOR_WHITE),
("Wildcard", "", 0, GRC_COLOR_WHITE),
)
ALIAS_TYPES = {
"complex": (8, GRC_COLOR_BLUE),
"float": (4, GRC_COLOR_ORANGE),
"int": (4, GRC_COLOR_TEAL),
"short": (2, GRC_COLOR_YELLOW),
"byte": (1, GRC_COLOR_PURPLE_A400),
"bits": (1, GRC_COLOR_PURPLE_A100),
}
ALIASES_OF = {
"complex": {"fc32"},
"float": {"f32"},
"int": {"s32"},
"short": {"s16", "sc16"},
"byte": {"s8", "sc8"},
"bits": {"bit"},
"fc32": {"complex"},
"f32": {"float"},
"s32": {"int"},
"s16": {"short"},
"sc16": {"short"},
"s8": {"byte"},
"sc8": {"byte"},
"bit": {"bits"},
}
TYPE_TO_SIZEOF = {key: sizeof for name, key, sizeof, color in CORE_TYPES}
TYPE_TO_SIZEOF.update((key, sizeof) for key, (sizeof, _) in ALIAS_TYPES.items())
|
engines | peertube | # SPDX-License-Identifier: AGPL-3.0-or-later
"""
peertube (Videos)
"""
from datetime import datetime
from json import loads
from urllib.parse import urlencode
from searx.utils import html_to_text
# about
about = {
"website": "https://joinpeertube.org",
"wikidata_id": "Q50938515",
"official_api_documentation": "https://docs.joinpeertube.org/api-rest-reference.html",
"use_official_api": True,
"require_api_key": False,
"results": "JSON",
}
# engine dependent config
categories = ["videos"]
paging = True
base_url = "https://peer.tube"
supported_languages_url = base_url + "/api/v1/videos/languages"
# do search-request
def request(query, params):
sanitized_url = base_url.rstrip("/")
pageno = (params["pageno"] - 1) * 15
search_url = sanitized_url + "/api/v1/search/videos/?pageno={pageno}&{query}"
query_dict = {"search": query}
language = params["language"].split("-")[0]
# pylint: disable=undefined-variable
if "all" != language and language in supported_languages:
query_dict["languageOneOf"] = language
params["url"] = search_url.format(query=urlencode(query_dict), pageno=pageno)
return params
def _get_offset_from_pageno(pageno):
return (pageno - 1) * 15 + 1
# get response from search-request
def response(resp):
sanitized_url = base_url.rstrip("/")
results = []
search_res = loads(resp.text)
embedded_url = (
'<iframe width="560" height="315" sandbox="allow-same-origin allow-scripts allow-popups" '
+ 'src="'
+ sanitized_url
+ '{embed_path}" frameborder="0" allowfullscreen></iframe>'
)
# return empty array if there are no results
if "data" not in search_res:
return []
# parse results
for res in search_res["data"]:
title = res["name"]
url = sanitized_url + "/videos/watch/" + res["uuid"]
description = res["description"]
if description:
content = html_to_text(res["description"])
else:
content = ""
thumbnail = sanitized_url + res["thumbnailPath"]
publishedDate = datetime.strptime(res["publishedAt"], "%Y-%m-%dT%H:%M:%S.%fZ")
embedded = embedded_url.format(embed_path=res["embedPath"])
results.append(
{
"template": "videos.html",
"url": url,
"title": title,
"content": content,
"publishedDate": publishedDate,
"embedded": embedded,
"thumbnail": thumbnail,
}
)
# return results
return results
def _fetch_supported_languages(resp):
peertube_languages = list(loads(resp.text).keys())
return peertube_languages
|
deep-learning | segment | import itertools
import multiprocessing
import os
import pathlib
import sys
import tempfile
import traceback
import invesalius.data.slice_ as slc
import numpy as np
from invesalius import inv_paths
from invesalius.data import imagedata_utils
from invesalius.data.converters import to_vtk
from invesalius.net.utils import download_url_to_file
from invesalius.utils import new_name_by_pattern
from skimage.transform import resize
from vtkmodules.vtkIOXML import vtkXMLImageDataWriter
from . import utils
SIZE = 48
def gen_patches(image, patch_size, overlap):
overlap = int(patch_size * overlap / 100)
sz, sy, sx = image.shape
i_cuts = list(
itertools.product(
range(0, sz, patch_size - overlap),
range(0, sy, patch_size - overlap),
range(0, sx, patch_size - overlap),
)
)
sub_image = np.empty(shape=(patch_size, patch_size, patch_size), dtype="float32")
for idx, (iz, iy, ix) in enumerate(i_cuts):
sub_image[:] = 0
_sub_image = image[
iz : iz + patch_size, iy : iy + patch_size, ix : ix + patch_size
]
sz, sy, sx = _sub_image.shape
sub_image[0:sz, 0:sy, 0:sx] = _sub_image
ez = iz + sz
ey = iy + sy
ex = ix + sx
yield (idx + 1.0) / len(i_cuts), sub_image, ((iz, ez), (iy, ey), (ix, ex))
def predict_patch(sub_image, patch, nn_model, patch_size):
(iz, ez), (iy, ey), (ix, ex) = patch
sub_mask = nn_model.predict(
sub_image.reshape(1, patch_size, patch_size, patch_size, 1)
)
return sub_mask.reshape(patch_size, patch_size, patch_size)[
0 : ez - iz, 0 : ey - iy, 0 : ex - ix
]
def predict_patch_torch(sub_image, patch, nn_model, device, patch_size):
import torch
with torch.no_grad():
(iz, ez), (iy, ey), (ix, ex) = patch
sub_mask = (
nn_model(
torch.from_numpy(
sub_image.reshape(1, 1, patch_size, patch_size, patch_size)
).to(device)
)
.cpu()
.numpy()
)
return sub_mask.reshape(patch_size, patch_size, patch_size)[
0 : ez - iz, 0 : ey - iy, 0 : ex - ix
]
def segment_keras(
image, weights_file, overlap, probability_array, comm_array, patch_size
):
import keras
# Loading model
with open(weights_file, "r") as json_file:
model = keras.models.model_from_json(json_file.read())
model.load_weights(str(weights_file.parent.joinpath("model.h5")))
model.compile("Adam", "binary_crossentropy")
image = imagedata_utils.image_normalize(image, 0.0, 1.0, output_dtype=np.float32)
sums = np.zeros_like(image)
# segmenting by patches
for completion, sub_image, patch in gen_patches(image, patch_size, overlap):
comm_array[0] = completion
(iz, ez), (iy, ey), (ix, ex) = patch
sub_mask = predict_patch(sub_image, patch, model, patch_size)
probability_array[iz:ez, iy:ey, ix:ex] += sub_mask
sums[iz:ez, iy:ey, ix:ex] += 1
probability_array /= sums
comm_array[0] = np.Inf
def download_callback(comm_array):
def _download_callback(value):
comm_array[0] = value
return _download_callback
def segment_torch(
image, weights_file, overlap, device_id, probability_array, comm_array, patch_size
):
import torch
from .model import Unet3D
device = torch.device(device_id)
if weights_file.exists():
state_dict = torch.load(str(weights_file), map_location=torch.device("cpu"))
else:
raise FileNotFoundError("Weights file not found")
model = Unet3D()
model.load_state_dict(state_dict["model_state_dict"])
model.to(device)
model.eval()
image = imagedata_utils.image_normalize(image, 0.0, 1.0, output_dtype=np.float32)
sums = np.zeros_like(image)
# segmenting by patches
with torch.no_grad():
for completion, sub_image, patch in gen_patches(image, patch_size, overlap):
comm_array[0] = completion
(iz, ez), (iy, ey), (ix, ex) = patch
sub_mask = predict_patch_torch(sub_image, patch, model, device, patch_size)
probability_array[iz:ez, iy:ey, ix:ex] += sub_mask
sums[iz:ez, iy:ey, ix:ex] += 1
probability_array /= sums
comm_array[0] = np.Inf
def segment_torch_jit(
image,
weights_file,
overlap,
device_id,
probability_array,
comm_array,
patch_size,
resize_by_spacing=True,
image_spacing=(1.0, 1.0, 1.0),
needed_spacing=(0.5, 0.5, 0.5),
flipped=False,
):
import torch
from .model import WrapModel
print(f"\n\n\n{image_spacing}\n\n\n")
print("Patch size:", patch_size)
if resize_by_spacing:
old_shape = image.shape
new_shape = [
round(i * j / k)
for (i, j, k) in zip(old_shape, image_spacing[::-1], needed_spacing[::-1])
]
image = resize(image, output_shape=new_shape, order=0, preserve_range=True)
original_probability_array = probability_array
probability_array = np.zeros_like(image)
device = torch.device(device_id)
if weights_file.exists():
jit_model = torch.jit.load(weights_file, map_location=torch.device("cpu"))
else:
raise FileNotFoundError("Weights file not found")
model = WrapModel(jit_model)
model.to(device)
model.eval()
sums = np.zeros_like(image)
# segmenting by patches
for completion, sub_image, patch in gen_patches(image, patch_size, overlap):
comm_array[0] = completion
(iz, ez), (iy, ey), (ix, ex) = patch
sub_mask = predict_patch_torch(sub_image, patch, model, device, patch_size)
probability_array[iz:ez, iy:ey, ix:ex] += sub_mask.squeeze()
sums[iz:ez, iy:ey, ix:ex] += 1
probability_array /= sums
# FIX: to remove
if flipped:
probability_array = np.flip(probability_array, 2)
if resize_by_spacing:
original_probability_array[:] = resize(
probability_array, output_shape=old_shape, preserve_range=True
)
comm_array[0] = np.Inf
ctx = multiprocessing.get_context("spawn")
class SegmentProcess(ctx.Process):
def __init__(
self,
image,
create_new_mask,
backend,
device_id,
use_gpu,
overlap=50,
apply_wwwl=False,
window_width=255,
window_level=127,
patch_size=SIZE,
):
multiprocessing.Process.__init__(self)
self._image_filename = image.filename
self._image_dtype = image.dtype
self._image_shape = image.shape
self._probability_array = np.memmap(
tempfile.mktemp(), shape=image.shape, dtype=np.float32, mode="w+"
)
self._prob_array_filename = self._probability_array.filename
self._comm_array = np.memmap(
tempfile.mktemp(), shape=(1,), dtype=np.float32, mode="w+"
)
self._comm_array_filename = self._comm_array.filename
self.create_new_mask = create_new_mask
self.backend = backend
self.device_id = device_id
self.use_gpu = use_gpu
self.overlap = overlap
self.patch_size = patch_size
self.apply_wwwl = apply_wwwl
self.window_width = window_width
self.window_level = window_level
self._pconn, self._cconn = multiprocessing.Pipe()
self._exception = None
self.torch_weights_file_name = ""
self.torch_weights_url = ""
self.torch_weights_hash = ""
self.keras_weight_file = ""
self.mask = None
def run(self):
try:
self._run_segmentation()
self._cconn.send(None)
except Exception as e:
tb = traceback.format_exc()
self._cconn.send((e, tb))
def _run_segmentation(self):
image = np.memmap(
self._image_filename,
dtype=self._image_dtype,
shape=self._image_shape,
mode="r",
)
if self.apply_wwwl:
image = imagedata_utils.get_LUT_value(
image, self.window_width, self.window_level
)
probability_array = np.memmap(
self._prob_array_filename,
dtype=np.float32,
shape=self._image_shape,
mode="r+",
)
comm_array = np.memmap(
self._comm_array_filename, dtype=np.float32, shape=(1,), mode="r+"
)
if self.backend.lower() == "pytorch":
if not self.torch_weights_file_name:
raise FileNotFoundError("Weights file not specified.")
folder = inv_paths.MODELS_DIR.joinpath(
self.torch_weights_file_name.split(".")[0]
)
system_state_dict_file = folder.joinpath(self.torch_weights_file_name)
user_state_dict_file = inv_paths.USER_DL_WEIGHTS.joinpath(
self.torch_weights_file_name
)
if system_state_dict_file.exists():
weights_file = system_state_dict_file
elif user_state_dict_file.exists():
weights_file = user_state_dict_file
else:
download_url_to_file(
self.torch_weights_url,
user_state_dict_file,
self.torch_weights_hash,
download_callback(comm_array),
)
weights_file = user_state_dict_file
segment_torch(
image,
weights_file,
self.overlap,
self.device_id,
probability_array,
comm_array,
self.patch_size,
)
else:
utils.prepare_ambient(self.backend, self.device_id, self.use_gpu)
segment_keras(
image,
self.keras_weight_file,
self.overlap,
probability_array,
comm_array,
self.patch_size,
)
@property
def exception(self):
# Based on https://stackoverflow.com/a/33599967
if self._pconn.poll():
self._exception = self._pconn.recv()
return self._exception
def apply_segment_threshold(self, threshold):
if self.create_new_mask:
if self.mask is None:
name = new_name_by_pattern("brainseg_mri_t1")
self.mask = slc.Slice().create_new_mask(name=name)
else:
self.mask = slc.Slice().current_mask
if self.mask is None:
name = new_name_by_pattern("brainseg_mri_t1")
self.mask = slc.Slice().create_new_mask(name=name)
self.mask.was_edited = True
self.mask.matrix[1:, 1:, 1:] = (self._probability_array >= threshold) * 255
self.mask.modified(True)
def get_completion(self):
return self._comm_array[0]
def __del__(self):
del self._comm_array
os.remove(self._comm_array_filename)
del self._probability_array
os.remove(self._prob_array_filename)
class BrainSegmentProcess(SegmentProcess):
def __init__(
self,
image,
create_new_mask,
backend,
device_id,
use_gpu,
overlap=50,
apply_wwwl=False,
window_width=255,
window_level=127,
patch_size=SIZE,
):
super().__init__(
image,
create_new_mask,
backend,
device_id,
use_gpu,
overlap=overlap,
apply_wwwl=apply_wwwl,
window_width=window_width,
window_level=window_level,
patch_size=patch_size,
)
self.torch_weights_file_name = "brain_mri_t1.pt"
self.torch_weights_url = "https://github.com/tfmoraes/deepbrain_torch/releases/download/v1.1.0/weights.pt"
self.torch_weights_hash = (
"194b0305947c9326eeee9da34ada728435a13c7b24015cbd95971097fc178f22"
)
self.keras_weight_file = inv_paths.MODELS_DIR.joinpath(
"brain_mri_t1/model.json"
)
class TracheaSegmentProcess(SegmentProcess):
def __init__(
self,
image,
create_new_mask,
backend,
device_id,
use_gpu,
overlap=50,
apply_wwwl=False,
window_width=255,
window_level=127,
patch_size=48,
):
super().__init__(
image,
create_new_mask,
backend,
device_id,
use_gpu,
overlap=overlap,
apply_wwwl=apply_wwwl,
window_width=window_width,
window_level=window_level,
patch_size=patch_size,
)
self.torch_weights_file_name = "trachea_ct.pt"
self.torch_weights_url = "https://github.com/tfmoraes/deep_trachea_torch/releases/download/v1.0/weights.pt"
self.torch_weights_hash = (
"6102d16e3c8c07a1c7b0632bc76db4d869c7467724ff7906f87d04f6dc72022e"
)
class MandibleCTSegmentProcess(SegmentProcess):
def __init__(
self,
image,
create_new_mask,
backend,
device_id,
use_gpu,
overlap=50,
apply_wwwl=False,
window_width=255,
window_level=127,
patch_size=96,
threshold=150,
resize_by_spacing=True,
image_spacing=(1.0, 1.0, 1.0),
):
super().__init__(
image,
create_new_mask,
backend,
device_id,
use_gpu,
overlap=overlap,
apply_wwwl=apply_wwwl,
window_width=window_width,
window_level=window_level,
patch_size=patch_size,
)
self.threshold = threshold
self.resize_by_spacing = resize_by_spacing
self.image_spacing = image_spacing
self.needed_spacing = (0.5, 0.5, 0.5)
self.torch_weights_file_name = "mandible_jit_ct.pt"
self.torch_weights_url = "https://raw.githubusercontent.com/invesalius/weights/main/mandible_ct/mandible_jit_ct.pt"
self.torch_weights_hash = (
"a9988c64b5f04dfbb6d058b95b737ed801f1a89d1cc828cd3e5d76d81979a724"
)
def _run_segmentation(self):
image = np.memmap(
self._image_filename,
dtype=self._image_dtype,
shape=self._image_shape,
mode="r",
)
if self.apply_wwwl:
image = imagedata_utils.get_LUT_value(
image, self.window_width, self.window_level
)
image = (image >= self.threshold).astype(np.float32)
probability_array = np.memmap(
self._prob_array_filename,
dtype=np.float32,
shape=self._image_shape,
mode="r+",
)
comm_array = np.memmap(
self._comm_array_filename, dtype=np.float32, shape=(1,), mode="r+"
)
if self.backend.lower() == "pytorch":
if not self.torch_weights_file_name:
raise FileNotFoundError("Weights file not specified.")
folder = inv_paths.MODELS_DIR.joinpath(
self.torch_weights_file_name.split(".")[0]
)
system_state_dict_file = folder.joinpath(self.torch_weights_file_name)
user_state_dict_file = inv_paths.USER_DL_WEIGHTS.joinpath(
self.torch_weights_file_name
)
if system_state_dict_file.exists():
weights_file = system_state_dict_file
elif user_state_dict_file.exists():
weights_file = user_state_dict_file
else:
download_url_to_file(
self.torch_weights_url,
user_state_dict_file,
self.torch_weights_hash,
download_callback(comm_array),
)
weights_file = user_state_dict_file
segment_torch_jit(
image,
weights_file,
self.overlap,
self.device_id,
probability_array,
comm_array,
self.patch_size,
resize_by_spacing=self.resize_by_spacing,
image_spacing=self.image_spacing,
needed_spacing=self.needed_spacing,
)
else:
utils.prepare_ambient(self.backend, self.device_id, self.use_gpu)
segment_keras(
image,
self.keras_weight_file,
self.overlap,
probability_array,
comm_array,
self.patch_size,
)
|
plugins | toolkit_sphinx_extension | # encoding: utf-8
"""A Sphinx extension to automatically document CKAN's crazy plugins toolkit,
autodoc-style.
Sphinx's autodoc extension can document modules or classes, but although it
masquerades as a module CKAN's plugins toolkit is actually neither a module nor
a class, it's an object-instance of a class, and it's an object with weird
__getattr__ behavior too. Autodoc can't handle it, so we have this custom
Sphinx extension to automate documenting it instead.
This extension plugs into the reading phase of the Sphinx build. It intercepts
the 'toolkit' document (extensions/plugins-toolkit.rst) after Sphinx has read
the reStructuredText source from file. It modifies the source, adding in Sphinx
directives for everything in the plugins toolkit, and then the Sphinx build
continues as normal (just as if the generated reStructuredText had been entered
into plugins-toolkit.rst manually before running Sphinx).
"""
import inspect
from typing import Any, Callable, Optional
import ckan.plugins.toolkit as toolkit
def setup(app: Any):
"""Setup this Sphinx extension. Called once when initializing Sphinx."""
# Connect to Sphinx's source-read event, the callback function will be
# called after each source file is read.
app.connect("source-read", source_read)
def format_function(
name: str, function: Callable[..., Any], docstring: Optional[str] = None
) -> str:
"""Return a Sphinx .. function:: directive for the given function.
The directive includes the function's docstring if it has one.
:param name: the name to give to the function in the directive,
eg. 'get_converter'
:type name: string
:param function: the function itself
:type function: function
:param docstring: if given, use this instead of introspecting the function
to find its actual docstring
:type docstring: string
:returns: a Sphinx .. function:: directive for the function
:rtype: string
"""
# The template we'll use to render the Sphinx function directive.
template = (
".. py:function:: ckan.plugins.toolkit.{function}{args}\n"
"\n"
"{docstring}\n"
"\n"
)
# Get the arguments of the function, as a string like:
# "(foo, bar=None, ...)"
argstring = str(inspect.signature(function))
docstring = docstring or inspect.getdoc(function)
if docstring is None:
docstring = ""
else:
# Indent the docstring by 3 spaces, as needed for the Sphinx directive.
docstring = "\n".join([" " + line for line in docstring.split("\n")])
return template.format(function=name, args=argstring, docstring=docstring)
def format_class(name: str, class_: Any, docstring: Optional[str] = None) -> str:
"""Return a Sphinx .. class:: directive for the given class.
The directive includes the class's docstring if it has one.
:param name: the name to give to the class in the directive,
eg. 'DefaultDatasetForm'
:type name: string
:param class_: the class itself
:type class_: class
:param docstring: if given, use this instead of introspecting the class
to find its actual docstring
:type docstring: string
:returns: a Sphinx .. class:: directive for the class
:rtype: string
"""
# The template we'll use to render the Sphinx class directive.
template = ".. py:class:: ckan.plugins.toolkit.{cls}\n" "\n" "{docstring}\n" "\n"
docstring = docstring or inspect.getdoc(class_)
if docstring is None:
docstring = ""
else:
# Indent the docstring by 3 spaces, as needed for the Sphinx directive.
docstring = "\n".join([" " + line for line in docstring.split("\n")])
return template.format(cls=name, docstring=docstring)
def format_object(name: str, object_: Any, docstring: Optional[str] = None) -> str:
"""Return a Sphinx .. attribute:: directive for the given object.
The directive includes the object's class's docstring if it has one.
:param name: the name to give to the object in the directive,
eg. 'request'
:type name: string
:param object_: the object itself
:type object_: object
:param docstring: if given, use this instead of introspecting the object
to find its actual docstring
:type docstring: string
:returns: a Sphinx .. attribute:: directive for the object
:rtype: string
"""
# The template we'll use to render the Sphinx attribute directive.
template = (
".. py:attribute:: ckan.plugins.toolkit.{obj}\n" "\n" "{docstring}\n" "\n"
)
docstring = docstring or inspect.getdoc(object_)
if docstring is None:
docstring = ""
else:
# Indent the docstring by 3 spaces, as needed for the Sphinx directive.
docstring = "\n".join([" " + line for line in docstring.split("\n")])
return template.format(obj=name, docstring=docstring)
def source_read(app: Any, docname: str, source: Any) -> None:
"""Transform the contents of plugins-toolkit.rst to contain reference docs."""
# We're only interested in the 'plugins-toolkit' doc (plugins-toolkit.rst).
if docname != "extensions/plugins-toolkit":
return
source_ = "\n"
for name, thing in inspect.getmembers(toolkit):
if name not in toolkit.__all__:
continue
# The plugins toolkit can override the docstrings of some of its
# members (e.g. things that are imported from third-party libraries)
# by putting custom docstrings in this docstring_overrides dict.
custom_docstring = toolkit.docstring_overrides.get(name)
if inspect.isfunction(thing):
source_ += format_function(name, thing, docstring=custom_docstring)
elif inspect.ismethod(thing):
# We document plugins toolkit methods as if they're functions. This
# is correct because the class ckan.plugins.toolkit._Toolkit
# actually masquerades as a module ckan.plugins.toolkit, and you
# call its methods as if they were functions.
source_ += format_function(name, thing, docstring=custom_docstring)
elif inspect.isclass(thing):
source_ += format_class(name, thing, docstring=custom_docstring)
elif isinstance(thing, object):
source_ += format_object(name, thing, docstring=custom_docstring)
else:
assert False, (
"Someone added {name}:{thing} to the plugins "
"toolkit and this Sphinx extension doesn't know "
"how to document that yet. If you're that someone, "
"you need to add a new format_*() function for it "
"here or the docs won't build.".format(name=name, thing=thing)
)
source[0] += source_
# This is useful for debugging the generated RST.
# open('/tmp/source', 'w').write(source[0])
|
analog | qa_phase_modulator | #!/usr/bin/env python
#
# Copyright 2012,2013 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# SPDX-License-Identifier: GPL-3.0-or-later
#
#
import math
from gnuradio import analog, blocks, gr, gr_unittest
def sincos(x):
return math.cos(x) + math.sin(x) * 1j
class test_phase_modulator(gr_unittest.TestCase):
def setUp(self):
self.tb = gr.top_block()
def tearDown(self):
self.tb = None
def test_fm_001(self):
pi = math.pi
sensitivity = pi / 4
src_data = (1.0 / 4, 1.0 / 2, 1.0 / 4, -1.0 / 4, -1.0 / 2, -1 / 4.0)
expected_result = tuple([sincos(sensitivity * x) for x in src_data])
src = blocks.vector_source_f(src_data)
op = analog.phase_modulator_fc(sensitivity)
dst = blocks.vector_sink_c()
self.tb.connect(src, op)
self.tb.connect(op, dst)
self.tb.run()
result_data = dst.data()
self.assertComplexTuplesAlmostEqual(expected_result, result_data, 5)
if __name__ == "__main__":
gr_unittest.run(test_phase_modulator)
|
bleachbit | setup | #!/usr/bin/env python
# vim: ts=4:sw=4:expandtab
# BleachBit
# Copyright (C) 2008-2023 Andrew Ziem
# https://www.bleachbit.org
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
Build BleachBit tarballs and exe
"""
import glob
import os
import sys
import tempfile
from setuptools import setup
if sys.platform == "win32":
# workaround for
# Error: Namespace packages not yet supported: Skipping package 'pywintypes'
import importlib
for m in ("pywintypes", "pythoncom"):
l = importlib.find_loader(m, None)
__import__(m)
sys.modules[m].__loader__ = l
try:
import py2exe
except ImportError:
print("warning: py2exe not available")
import bleachbit
import bleachbit.FileUtilities
import bleachbit.General
APP_NAME = "BleachBit - Free space and maintain privacy"
APP_DESCRIPTION = "BleachBit frees space and maintains privacy by quickly wiping files you don't need and didn't know you had. Supported applications include Edge, Firefox, Google Chrome, VLC, and many others."
#
# begin win32com.shell workaround for py2exe
# copied from http://spambayes.svn.sourceforge.net/viewvc/spambayes/trunk/spambayes/windows/py2exe/setup_all.py?revision=3245&content-type=text%2Fplain
# under Python license compatible with GPL
#
# ModuleFinder can't handle runtime changes to __path__, but win32com uses them,
# particularly for people who build from sources. Hook this in.
try:
# py2exe 0.6.4 introduced a replacement modulefinder.
# This means we have to add package paths there, not to the built-in
# one. If this new modulefinder gets integrated into Python, then
# we might be able to revert this some day.
try:
import py2exe.mf as modulefinder
except ImportError:
import modulefinder
import win32com
for p in win32com.__path__[1:]:
modulefinder.AddPackagePath("win32com", p)
for extra in ["win32com.shell", "win32com.mapi"]:
__import__(extra)
m = sys.modules[extra]
for p in m.__path__[1:]:
modulefinder.AddPackagePath(extra, p)
except ImportError:
# no build path setup, no worries.
pass
#
# end win32com.shell workaround for py2exe
#
data_files = []
if sys.platform.startswith("linux"):
data_files.append(
("/usr/share/applications", ["./org.bleachbit.BleachBit.desktop"])
)
data_files.append(("/usr/share/pixmaps/", ["./bleachbit.png"]))
elif sys.platform[:6] == "netbsd":
data_files.append(
("/usr/pkg/share/applications", ["./org.bleachbit.BleachBit.desktop"])
)
data_files.append(("/usr/pkg/share/pixmaps/", ["./bleachbit.png"]))
elif sys.platform.startswith("openbsd") or sys.platform.startswith("freebsd"):
data_files.append(
("/usr/local/share/applications", ["./org.bleachbit.BleachBit.desktop"])
)
data_files.append(("/usr/local/share/pixmaps/", ["./bleachbit.png"]))
args = {}
if "py2exe" in sys.argv:
args["windows"] = [
{
"script": "bleachbit.py",
"product_name": APP_NAME,
"description": APP_DESCRIPTION,
"version": bleachbit.APP_VERSION,
"icon_resources": [(1, "windows/bleachbit.ico")],
}
]
args["console"] = [
{
"script": "bleachbit_console.py",
"product_name": APP_NAME,
"description": APP_DESCRIPTION,
"version": bleachbit.APP_VERSION,
"icon_resources": [(1, "windows/bleachbit.ico")],
}
]
args["options"] = {
"py2exe": {
"packages": ["encodings", "gi", "gi.overrides", "plyer"],
"optimize": 2, # extra optimization (like python -OO)
"includes": ["gi"],
"excludes": [
"pyreadline",
"difflib",
"doctest",
"pickle",
"ftplib",
"bleachbit.Unix",
],
"dll_excludes": [
"libgstreamer-1.0-0.dll",
"CRYPT32.DLL", # required by ssl
"DNSAPI.DLL",
"IPHLPAPI.DLL", # psutil
"MPR.dll",
"MSIMG32.DLL",
"MSWSOCK.dll",
"NSI.dll", # psutil
"PDH.DLL", # psutil
"PSAPI.DLL",
"POWRPROF.dll",
"USP10.DLL",
"WINNSI.DLL", # psutil
"WTSAPI32.DLL", # psutil
"api-ms-win-core-apiquery-l1-1-0.dll",
"api-ms-win-core-crt-l1-1-0.dll",
"api-ms-win-core-crt-l2-1-0.dll",
"api-ms-win-core-debug-l1-1-1.dll",
"api-ms-win-core-delayload-l1-1-1.dll",
"api-ms-win-core-errorhandling-l1-1-0.dll",
"api-ms-win-core-errorhandling-l1-1-1.dll",
"api-ms-win-core-file-l1-1-0.dll",
"api-ms-win-core-file-l1-2-1.dll",
"api-ms-win-core-handle-l1-1-0.dll",
"api-ms-win-core-heap-l1-1-0.dll",
"api-ms-win-core-heap-l1-2-0.dll",
"api-ms-win-core-heap-obsolete-l1-1-0.dll",
"api-ms-win-core-io-l1-1-1.dll",
"api-ms-win-core-kernel32-legacy-l1-1-0.dll",
"api-ms-win-core-kernel32-legacy-l1-1-1.dll",
"api-ms-win-core-libraryloader-l1-2-0.dll",
"api-ms-win-core-libraryloader-l1-2-1.dll",
"api-ms-win-core-localization-l1-2-1.dll",
"api-ms-win-core-localization-obsolete-l1-2-0.dll",
"api-ms-win-core-memory-l1-1-0.dll",
"api-ms-win-core-memory-l1-1-2.dll",
"api-ms-win-core-perfstm-l1-1-0.dll",
"api-ms-win-core-processenvironment-l1-2-0.dll",
"api-ms-win-core-processthreads-l1-1-0.dll",
"api-ms-win-core-processthreads-l1-1-2.dll",
"api-ms-win-core-profile-l1-1-0.dll",
"api-ms-win-core-registry-l1-1-0.dll",
"api-ms-win-core-registry-l2-1-0.dll",
"api-ms-win-core-string-l1-1-0.dll",
"api-ms-win-core-string-obsolete-l1-1-0.dll",
"api-ms-win-core-synch-l1-1-0.dll",
"api-ms-win-core-synch-l1-2-0.dll",
"api-ms-win-core-sysinfo-l1-1-0.dll",
"api-ms-win-core-sysinfo-l1-2-1.dll",
"api-ms-win-core-threadpool-l1-2-0.dll",
"api-ms-win-core-timezone-l1-1-0.dll",
"api-ms-win-core-util-l1-1-0.dll",
"api-ms-win-eventing-classicprovider-l1-1-0.dll",
"api-ms-win-eventing-consumer-l1-1-0.dll",
"api-ms-win-eventing-controller-l1-1-0.dll",
"api-ms-win-eventlog-legacy-l1-1-0.dll",
"api-ms-win-perf-legacy-l1-1-0.dll",
"api-ms-win-security-base-l1-2-0.dll",
"w9xpopen.exe", # not needed after Windows 9x
],
"compressed": True, # create a compressed zipfile
}
}
# check for 32-bit
import struct
bits = 8 * struct.calcsize("P")
assert 32 == bits
def recompile_mo(langdir, app, langid, dst):
"""Recompile gettext .mo file"""
if not bleachbit.FileUtilities.exe_exists(
"msgunfmt"
) and not bleachbit.FileUtilities.exe_exists("msgunfmt.exe"):
print("warning: msgunfmt missing: skipping recompile")
return
mo_pathname = os.path.normpath("%s/LC_MESSAGES/%s.mo" % (langdir, app))
if not os.path.exists(mo_pathname):
print("info: does not exist: %s", mo_pathname)
return
# decompile .mo to .po
po = os.path.join(dst, langid + ".po")
__args = ["msgunfmt", "-o", po, mo_pathname]
ret = bleachbit.General.run_external(__args)
if ret[0] != 0:
raise RuntimeError(ret[2])
# shrink .po
po2 = os.path.join(dst, langid + ".po2")
__args = [
"msgmerge",
"--no-fuzzy-matching",
po,
os.path.normpath("windows/%s.pot" % app),
"-o",
po2,
]
ret = bleachbit.General.run_external(__args)
if ret[0] != 0:
raise RuntimeError(ret[2])
# compile smaller .po to smaller .mo
__args = ["msgfmt", po2, "-o", mo_pathname]
ret = bleachbit.General.run_external(__args)
if ret[0] != 0:
raise RuntimeError(ret[2])
# clean up
os.remove(po)
os.remove(po2)
def supported_languages():
"""Return list of supported languages by scanning ./po/"""
langs = []
for pathname in glob.glob("po/*.po"):
basename = os.path.basename(pathname)
langs.append(os.path.splitext(basename)[0])
return sorted(langs)
def clean_dist_locale():
"""Clean dist/share/locale"""
tmpd = tempfile.mkdtemp("gtk_locale")
langs = supported_languages()
basedir = os.path.normpath("dist/share/locale")
for langid in sorted(os.listdir(basedir)):
langdir = os.path.join(basedir, langid)
if langid in langs:
print("recompiling supported GTK language = %s" % langid)
# reduce the size of the .mo file
recompile_mo(langdir, "gtk30", langid, tmpd)
else:
print("removing unsupported GTK language = %s" % langid)
# remove language supported by GTK+ but not by BleachBit
cmd = "rd /s /q " + langdir
print(cmd)
os.system(cmd)
os.rmdir(tmpd)
def run_setup():
setup(
name="bleachbit",
version=bleachbit.APP_VERSION,
description=APP_NAME,
long_description=APP_DESCRIPTION,
author="Andrew Ziem",
author_email="andrew@bleachbit.org",
download_url="https://www.bleachbit.org/download",
license="GPLv3",
url=bleachbit.APP_URL,
platforms="Linux and Windows; Python v2.6 and 2.7; GTK v3.12+",
packages=["bleachbit", "bleachbit.markovify"],
**args,
)
if __name__ == "__main__":
if 2 == len(sys.argv) and sys.argv[1] == "clean-dist":
clean_dist_locale()
else:
run_setup()
|
puddlestuff | actiondlg | # -*- coding: utf-8 -*-
import os
import sys
from copy import copy, deepcopy
from functools import partial
from pyparsing import Combine, QuotedString, Word, alphanums, delimitedList
from PyQt5.QtCore import Qt, pyqtSignal
from PyQt5.QtWidgets import (
QAbstractItemView,
QAction,
QApplication,
QCheckBox,
QComboBox,
QCompleter,
QDialog,
QFrame,
QGridLayout,
QInputDialog,
QLabel,
QLineEdit,
QListWidgetItem,
QMenu,
QMessageBox,
QScrollArea,
QSizePolicy,
QSpinBox,
QStackedWidget,
QToolButton,
QVBoxLayout,
QWidget,
)
from . import findfunc, functions, functions_dialogs
from .audioinfo import INFOTAGS, READONLY
from .constants import ACTIONDIR, CHECKBOX, COMBO, CONFIGDIR, SAVEDIR, TEXT
from .findfunc import Function, Macro, apply_actions, apply_macros
from .puddleobjects import (
ListBox,
ListButtons,
OKCancel,
PuddleCombo,
PuddleConfig,
ShortcutEditor,
gettaglist,
open_resourcefile,
safe_name,
settaglist,
winsettings,
)
from .util import PluginFunction, pprint_tag, translate
READONLY = list(READONLY)
FUNC_SETTINGS = os.path.join(CONFIGDIR, "function_settings")
FIELDS_TOOLTIP = translate(
"Functions Dialog",
"""<p>Fields that will
get written to.</p>
<ul>
<li>Enter a list of comma-separated fields
eg. <b>artist, title, album</b></li>
<li>Use <b>__selected</b> to write only to the selected cells.
It is not allowed when creating an action.</li>
<li>Combinations like <b>__selected, artist, title</b> are
allowed.</li>
<li>But using <b>__selected</b> in Actions is <b>not</b>.</li>
<li>'~' will write to all the the fields, except what follows it
. Eg <b>~artist, title</b> will write to all but the artist and
title fields found in the selected files.<li>
</ul>""",
)
def displaytags(tags):
text = pprint_tag(tags)
if not text:
return translate("Functions Dialog", "<b>No change.</b>")
if text.endswith("<br />"):
text = text[: -len("<br />")]
return text
class ShortcutDialog(QDialog):
shortcutChanged = pyqtSignal(str, name="shortcutChanged")
def __init__(self, shortcuts=None, parent=None):
super(ShortcutDialog, self).__init__(parent)
self.setWindowTitle("puddletag")
self.ok = False
label = QLabel(
translate("Shortcut Editor", "Enter a key sequence for the shortcut.")
)
self._text = ShortcutEditor(shortcuts)
okcancel = OKCancel()
okcancel.cancelButton.setText(
translate("Shortcut Editor", "&Don't assign keyboard shortcut.")
)
okcancel.okButton.setEnabled(False)
okcancel.ok.connect(self.okClicked)
okcancel.cancel.connect(self.close)
self._text.validityChanged.connect(okcancel.okButton.setEnabled)
vbox = QVBoxLayout()
vbox.addWidget(label)
vbox.addWidget(self._text)
vbox.addLayout(okcancel)
vbox.addStretch()
self.setLayout(vbox)
self._shortcuts = shortcuts
def okClicked(self):
self.shortcutChanged.emit(str(self._text.text()))
self.ok = True
self.close()
def getShortcut(self):
self.exec_()
if self._text.valid:
return str(self._text.text()), self.ok
else:
return "", self.ok
class ShortcutName(QDialog):
def __init__(self, texts, default="", parent=None):
super(ShortcutName, self).__init__(parent)
self.setWindowTitle("puddletag")
self.ok = False
self._texts = texts
label = QLabel(translate("Actions", "Enter a name for the shortcut."))
self._text = QLineEdit(default)
okcancel = OKCancel()
self._ok = okcancel.okButton
self.enableOK(self._text.text())
okcancel.ok.connect(self.okClicked)
okcancel.cancel.connect(self.close)
self._text.textChanged.connect(self.enableOK)
vbox = QVBoxLayout()
vbox.addWidget(label)
vbox.addWidget(self._text)
vbox.addLayout(okcancel)
vbox.addStretch()
self.setLayout(vbox)
def okClicked(self):
self.ok = True
self.close()
def enableOK(self, text):
if text and str(text) not in self._texts:
self._ok.setEnabled(True)
else:
self._ok.setEnabled(False)
def getText(self):
self.exec_()
return str(self._text.text()), self.ok
class ScrollLabel(QScrollArea):
def __init__(self, text="", parent=None):
QScrollArea.__init__(self, parent)
label = QLabel()
label.setMargin(3)
self.setWidget(label)
self.setText(text)
self.text = label.text
label.setSizePolicy(QSizePolicy.Policy.Minimum, QSizePolicy.Policy.Preferred)
self.setFrameStyle(QFrame.Shape.NoFrame)
self.setWidgetResizable(True)
self.setAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignTop)
self.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
def wheelEvent(self, e):
h = self.horizontalScrollBar()
if h.isVisible():
numsteps = e.angleDelta().y() // 5
h.setValue(h.value() - numsteps)
e.accept()
else:
QScrollArea.wheelEvent(self, e)
def setText(self, text):
label = self.widget()
label.setText(text)
hbar = self.horizontalScrollBar()
height = label.sizeHint().height() + hbar.height()
self.setMaximumHeight(height)
self.setMinimumHeight(height)
class FunctionDialog(QWidget):
"A dialog that allows you to edit or create a Function class."
_controls = {"text": PuddleCombo, "combo": QComboBox, "check": QCheckBox}
signals = {
TEXT: "editTextChanged",
COMBO: "currentIndexChanged",
CHECKBOX: "stateChanged",
}
updateExample = pyqtSignal(object, name="updateExample")
def __init__(
self,
funcname,
selected_fields=False,
userargs=None,
default_fields=None,
parent=None,
example=None,
text=None,
):
"""funcname is name the function you want to use(can be either string, or functions.py function).
if combotags is true then a combobox with tags that the user can choose from are shown.
userargs is the default values you want to fill the controls in the dialog with
[make sure they don't exceed the number of arguments of funcname]."""
QWidget.__init__(self, parent)
identifier = QuotedString('"') | Combine(
Word(alphanums + " !\"#$%&'()*+-./:;<=>?@[\\]^_`{|}~")
)
tags = delimitedList(identifier)
self.func = Function(funcname)
docstr = self.func.doc[1:]
self.vbox = QVBoxLayout()
self.retval = []
self._selectedFields = selected_fields
if selected_fields:
fields = ["__all"] + sorted(INFOTAGS) + selected_fields + gettaglist()
else:
fields = ["__selected", "__all"] + sorted(INFOTAGS) + gettaglist()
self.tagcombo = QComboBox(self)
self.tagcombo.setToolTip(FIELDS_TOOLTIP)
self.tagcombo.setEditable(True)
self.tagcombo.setCompleter(QCompleter(self.tagcombo))
self.tagcombo.addItems(fields)
self.tagcombo.editTextChanged.connect(self.showexample)
if self.func.function not in functions.no_fields:
label = QLabel(translate("Defaults", "&Fields"))
self.vbox.addWidget(label)
self.vbox.addWidget(self.tagcombo)
label.setBuddy(self.tagcombo)
else:
self.tagcombo.setVisible(False)
self.example = example
self._text = text
if self.func.function in functions_dialogs.dialogs:
vbox = QVBoxLayout()
vbox.addWidget(self.tagcombo)
self.widget = functions_dialogs.dialogs[self.func.function](self)
vbox.addWidget(self.widget)
vbox.addStretch()
self.setLayout(vbox)
self.setMinimumSize(self.sizeHint())
self.setArguments(default_fields, userargs)
return
else:
self.widget = None
self.textcombos = []
# Loop that creates all the controls
self.controls = []
for argno, line in enumerate(docstr):
args = tags.parseString(line)
label = args[0]
ctype = args[1]
default = args[2:]
control, func, label = self._createControl(label, ctype, default)
self.retval.append(func)
self.controls.append(control)
getattr(control, self.signals[ctype]).connect(self.showexample)
if label:
self.vbox.addWidget(label)
self.vbox.addWidget(control)
self.setArguments(default_fields, userargs)
self.vbox.addStretch()
self.setLayout(self.vbox)
self.setMinimumSize(self.sizeHint())
def argValues(self):
"""Returns the values in the windows controls.
The last argument is the tags value.
Also sets self.func's arg and tag values."""
if self.widget:
newargs = self.widget.arguments()
else:
newargs = []
for method in self.retval:
if method.__name__ == "checkState":
if method() == Qt.CheckState.Checked:
newargs.append(True)
elif (method() == Qt.CheckState.PartiallyChecked) or (
method() == Qt.CheckState.Unchecked
):
newargs.append(False)
else:
if isinstance(method(), int):
newargs.append(method())
else:
newargs.append(str(method()))
[z.save() for z in self.textcombos]
self.func.setArgs(newargs)
fields = [z.strip() for z in str(self.tagcombo.currentText()).split(",") if z]
if self.func.function in functions.no_fields:
self.func.setTag(["just nothing to do with this"])
else:
self.func.setTag(fields)
return newargs + fields
def _createControl(self, label, ctype, default=None):
if ctype == "text":
control = self._controls["text"](label, parent=self)
else:
control = self._controls[ctype](self)
if ctype == "combo":
func = control.currentText
if default:
control.addItems([translate("Functions", d) for d in default])
elif ctype == "text":
self.textcombos.append(control)
func = control.currentText
if default:
control.setEditText(default[0])
elif ctype == "check":
func = control.checkState
if default:
if default[0] == "True" or default[0] is True:
control.setChecked(True)
else:
control.setChecked(False)
control.setText(translate("Functions", label))
if ctype != "check":
label = QLabel(translate("Functions", label))
label.setBuddy(control)
else:
label = None
return control, func, label
def loadSettings(self, filename=None):
if filename is None:
filename = FUNC_SETTINGS
cparser = PuddleConfig(filename)
function = self.func.function
section = "%s_%s" % (function.__module__, function.__name__)
arguments = cparser.get(section, "arguments", [])
fields = cparser.get(section, "fields", [])
if not fields:
fields = None
self.setArguments(fields, arguments)
def saveSettings(self, filename=None):
if not filename:
filename = FUNC_SETTINGS
function = self.func.function
section = "%s_%s" % (function.__module__, function.__name__)
cparser = PuddleConfig(filename)
args = self.argValues()
cparser.set(section, "arguments", self.func.args)
cparser.set(section, "fields", self.func.tag)
def showexample(self, *args, **kwargs):
self.argValues()
if self.example is not None:
audio = self.example
try:
if self.func.function in functions.no_preview:
self.updateExample.emit(
translate(
"Functions Dialog",
"No preview for is shown for this function.",
)
)
return
fields = findfunc.parse_field_list(
self.func.tag, audio, self._selectedFields
)
from .puddletag import status
files = status["selectedfiles"]
files = str(len(files)) if files else "1"
state = {"__counter": "0", "__total_files": files}
val = apply_actions([self.func], audio, state, fields)
except findfunc.ParseError as e:
val = "<b>%s</b>" % (e.message)
if val is not None:
self.updateExample.emit(val)
else:
self.updateExample.emit(
translate("Functions Dialog", "<b>No change</b>")
)
def _sanitize(self, ctype, value):
if ctype in ["combo", "text"]:
return value
elif ctype == "check":
if value is True or value == "True":
return True
else:
return False
elif ctype == "spinbox":
try:
return int(value)
except (TypeError, ValueError):
return 0
def setArguments(self, fields=None, args=None):
if fields is not None:
text = ", ".join(fields)
index = self.tagcombo.findText(text)
if index != -1:
self.tagcombo.setCurrentIndex(index)
else:
self.tagcombo.insertItem(0, text)
self.tagcombo.setCurrentIndex(0)
self.tagcombo.setEditText(text)
if not args:
return
if self.widget:
self.widget.setArguments(*args)
return
for argument, control in zip(args, self.controls):
if isinstance(control, QComboBox):
index = control.findText(argument)
if index != -1:
control.setCurrentIndex(index)
elif isinstance(control, PuddleCombo):
control.setEditText(argument)
elif isinstance(control, QCheckBox):
control.setChecked(self._sanitize("check", argument))
elif isinstance(control, QSpinBox):
control.setValue(self._sanitize("spinbox", argument))
class CreateFunction(QDialog):
"""A dialog to allow the creation of functions using only one window and a QStackedWidget.
For each function in functions, a dialog is created and displayed in the stacked widget."""
valschanged = pyqtSignal(object, name="valschanged")
def __init__(
self, prevfunc=None, selected_fields=None, parent=None, example=None, text=None
):
"""tags is a list of the tags you want to show in the FunctionDialog.
Each item should be in the form (DisplayName, tagname) as used in audioinfo.
prevfunc is a Function object that is to be edited."""
QDialog.__init__(self, parent)
self.setWindowTitle(translate("Functions Dialog", "Functions"))
winsettings("createfunction", self)
# Allow __selected field to be used.
self.allowSelected = True
self.realfuncs = []
# Get all the function from the functions module.
for z, funcname in functions.functions.items():
if isinstance(funcname, PluginFunction):
self.realfuncs.append(funcname)
elif callable(funcname) and (
not (funcname.__name__.startswith("__") or (funcname.__doc__ is None))
):
self.realfuncs.append(z)
funcnames = [(Function(z).funcname, z) for z in self.realfuncs]
funcnames.sort(key=lambda x: translate("Functions", x[0]))
self.realfuncs = [z[1] for z in funcnames]
self.vbox = QVBoxLayout()
self.functions = QComboBox()
self.functions.addItems(
sorted([translate("Functions", x[0]) for x in funcnames])
)
self.vbox.addWidget(self.functions)
self.stack = QStackedWidget()
self.vbox.addWidget(self.stack)
self.okcancel = OKCancel()
self.stackWidgets = {} # Holds the created windows in the form self.functions.index: window
self.setLayout(self.vbox)
self.setMinimumHeight(self.sizeHint().height())
self.okcancel.ok.connect(self.okClicked)
self.okcancel.cancel.connect(self.close)
self.example = example
self._text = text
if not selected_fields:
self.selectedFields = []
else:
self.selectedFields = selected_fields
self.exlabel = ScrollLabel("")
if prevfunc is not None:
index = self.functions.findText(translate("Functions", prevfunc.funcname))
if index >= 0:
self.functions.setCurrentIndex(index)
self.createWindow(index, prevfunc.tag, prevfunc.args)
else:
self.createWindow(0)
self.functions.activated.connect(self.createWindow)
self.vbox.addWidget(self.exlabel)
self.vbox.addLayout(self.okcancel)
self.setLayout(self.vbox)
def createWindow(self, index, fields=None, args=None):
"""Creates a Function dialog in the stack window
if it doesn't exist already."""
self.stack.setFrameStyle(QFrame.Shape.Box)
if index not in self.stackWidgets:
widget = FunctionDialog(
self.realfuncs[index],
self.selectedFields,
args,
fields,
example=self.example,
text=self._text,
)
if args is None:
widget.loadSettings()
self.stackWidgets.update({index: widget})
self.stack.addWidget(widget)
widget.updateExample.connect(self.updateExample)
self.stack.setCurrentWidget(self.stackWidgets[index])
self.stackWidgets[index].showexample()
self.controls = getattr(self.stackWidgets[index], "controls", [])
self.setMinimumHeight(self.sizeHint().height())
if self.sizeHint().width() > self.width():
self.setMinimumWidth(self.sizeHint().width())
def okClicked(self, close=True):
w = self.stack.currentWidget()
w.argValues()
if not self.checkFields(w.func.tag):
return
if close:
self.close()
if w.func.tag:
fields = gettaglist()
new_fields = [z for z in w.func.tag if z not in fields]
if new_fields:
settaglist(sorted(new_fields + fields))
for widget in self.stackWidgets.values():
widget.saveSettings()
self.saveSettings()
self.valschanged.emit(w.func)
def checkFields(self, fields):
func = self.stack.currentWidget().func
msg = translate(
"Actions", "Error: Using <b>__selected</b> in Actions is not allowed."
)
if not self.allowSelected and "__selected" in fields:
QMessageBox.warning(self, "puddletag", msg)
return False
elif func is not None and func not in functions.no_fields:
msg = translate("Actions", "Please enter some fields to write to.")
if not [_f for _f in fields if _f]:
QMessageBox.information(self, "puddletag", msg)
return False
return True
def loadSettings(self):
cparser = PuddleConfig()
func_name = cparser.get("functions", "last_used", "")
if not func_name:
return
try:
index = self.realfuncs.index(func_name)
self.createWindow(index)
self.functions.setCurrentIndex(index)
except ValueError:
return
def saveSettings(self):
cparser = PuddleConfig()
funcname = self.realfuncs[self.functions.currentIndex()]
cparser.set("functions", "last_used", funcname)
def updateExample(self, text):
if not text:
self.exlabel.setText("")
else:
self.exlabel.setText(displaytags(text))
class CreateAction(QDialog):
"An action is defined as a collection of functions. This dialog serves the purpose of creating an action"
donewithmyshit = pyqtSignal(list, name="donewithmyshit")
def __init__(self, parent=None, prevfunctions=None, example=None):
"""tags is a list of the tags you want to show in the FunctionDialog.
Each item should be in the form (DisplayName, tagname as used in audioinfo).
prevfunction is the previous function that is to be edited."""
QDialog.__init__(self, parent)
self.setWindowTitle(translate("Actions", "Modify Action"))
winsettings("editaction", self)
self.grid = QGridLayout()
self.listbox = ListBox()
self.functions = []
self.buttonlist = ListButtons()
self.grid.addWidget(self.listbox, 0, 0)
self.grid.addLayout(self.buttonlist, 0, 1)
self.okcancel = OKCancel()
self.setLayout(self.grid)
self.example = example
self.okcancel.cancel.connect(self.cancelClicked)
self.okcancel.ok.connect(self.okClicked)
self.buttonlist.add.connect(self.add)
self.buttonlist.edit.connect(self.edit)
self.buttonlist.moveup.connect(self.moveUp)
self.buttonlist.movedown.connect(self.moveDown)
self.buttonlist.remove.connect(self.remove)
self.buttonlist.duplicate.connect(self.duplicate)
self.listbox.currentRowChanged.connect(self.enableEditButtons)
self.listbox.itemDoubleClicked.connect(self.edit)
if len(self.functions) == 0:
self.buttonlist.duplicateButton.setEnabled(False)
self.buttonlist.editButton.setEnabled(False)
if prevfunctions is not None:
self.functions = copy(prevfunctions)
self.listbox.addItems(
[function.description() for function in self.functions]
)
if example:
self._examplelabel = ScrollLabel("")
self.grid.addWidget(self._examplelabel, 1, 0)
self.grid.setRowStretch(0, 1)
self.grid.setRowStretch(1, 0)
self.example = example
self.updateExample()
self.grid.addLayout(self.okcancel, 2, 0, 1, 2)
else:
self.grid.addLayout(self.okcancel, 1, 0, 1, 2)
self.enableOK()
def updateExample(self):
try:
from .puddletag import status
files = status["selectedfiles"]
files = str(len(files)) if files else "1"
state = {"__counter": "0", "__total_files": files}
tags = apply_actions(self.functions, self.example, state)
self._examplelabel.setText(displaytags(tags))
except findfunc.ParseError as e:
self._examplelabel.setText(e.message)
def enableEditButtons(self, val):
if val == -1:
[button.setEnabled(False) for button in self.buttonlist.widgets[1:]]
else:
[button.setEnabled(True) for button in self.buttonlist.widgets[1:]]
def enableOK(self):
if self.listbox.count() > 0:
self.okcancel.okButton.setEnabled(True)
else:
self.okcancel.okButton.setEnabled(False)
def moveDown(self):
self.listbox.moveDown(self.functions)
def moveUp(self):
self.listbox.moveUp(self.functions)
def remove(self):
self.listbox.removeSelected(self.functions)
self.updateExample()
self.enableOK()
def add(self):
self.win = CreateFunction(None, parent=self, example=self.example)
self.win.allowSelected = False
self.win.setModal(True)
self.win.show()
self.win.valschanged.connect(self.addBuddy)
def edit(self):
self.win = CreateFunction(
self.functions[self.listbox.currentRow()], parent=self, example=self.example
)
self.win.allowSelected = False
self.win.setModal(True)
self.win.show()
self.win.valschanged.connect(self.editBuddy)
def editBuddy(self, func):
self.listbox.currentItem().setText(func.description())
self.functions[self.listbox.currentRow()] = func
self.updateExample()
def addBuddy(self, func):
self.listbox.addItem(func.description())
self.functions.append(func)
self.updateExample()
self.enableOK()
def okClicked(self):
self.accept()
self.close()
self.donewithmyshit.emit(self.functions)
def duplicate(self):
self.win = CreateFunction(
self.functions[self.listbox.currentRow()], parent=self, example=self.example
)
self.win.allowSelected = False
self.win.setModal(True)
self.win.show()
self.win.valschanged.connect(self.addBuddy)
def cancelClicked(self):
self.reject()
self.close()
class ActionWindow(QDialog):
"""Just a dialog that allows you to add, remove and edit actions
On clicking OK, a signal "donewithmyshit" is emitted.
It returns a list of lists.
Each element of a list contains one complete action. While
the elements of that action are just normal Function objects."""
donewithmyshit = pyqtSignal(list, name="donewithmyshit")
actionOrderChanged = pyqtSignal(name="actionOrderChanged")
checkedChanged = pyqtSignal(list, name="checkedChanged")
def __init__(self, parent=None, example=None, quickaction=None):
"""tags are the tags to be shown in the FunctionDialog"""
QDialog.__init__(self, parent)
self.setWindowTitle(translate("Actions", "Actions"))
winsettings("actions", self)
self._shortcuts = []
self._quickaction = quickaction
self.listbox = ListBox()
self.listbox.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection)
self.listbox.setEditTriggers(QAbstractItemView.EditTrigger.EditKeyPressed)
self.example = example
self.macros = self.loadMacros()
cparser = PuddleConfig()
self.__configKey = "quick_actions" if quickaction else "actions"
to_check = cparser.get(self.__configKey, "checked", [])
for i, m in sorted(self.macros.items()):
item = QListWidgetItem(m.name)
item.setFlags(item.flags() | Qt.ItemFlag.ItemIsEditable)
if m.name in to_check:
item.setCheckState(Qt.CheckState.Checked)
else:
item.setCheckState(Qt.CheckState.Unchecked)
self.listbox.addItem(item)
self.okcancel = OKCancel()
self.okcancel.okButton.setDefault(True)
x = QAction(translate("Actions", "Assign &Shortcut"), self)
self.shortcutButton = QToolButton()
self.shortcutButton.setDefaultAction(x)
x.setToolTip(
translate(
"Actions",
"""<p>Creates a
shortcut for the checked actions on the Actions menu.
Use Edit Shortcuts (found by pressing down on this button)
to edit shortcuts after the fact.</p>""",
)
)
menu = QMenu(self)
edit_shortcuts = QAction(translate("Actions", "Edit Shortcuts"), menu)
edit_shortcuts.triggered.connect(self.editShortcuts)
menu.addAction(edit_shortcuts)
self.shortcutButton.setMenu(menu)
self.okcancel.insertWidget(0, self.shortcutButton)
self.grid = QGridLayout()
self.buttonlist = ListButtons()
self.grid.addWidget(self.listbox, 0, 0)
self.grid.setRowStretch(0, 1)
self.grid.addLayout(self.buttonlist, 0, 1)
self.setLayout(self.grid)
self.okcancel.ok.connect(self.okClicked)
self.okcancel.cancel.connect(self.close)
self.buttonlist.add.connect(self.add)
self.buttonlist.edit.connect(self.edit)
self.buttonlist.moveup.connect(self.moveUp)
self.buttonlist.movedown.connect(self.moveDown)
self.buttonlist.remove.connect(self.remove)
self.buttonlist.duplicate.connect(self.duplicate)
self.listbox.itemDoubleClicked.connect(self.edit)
self.listbox.currentRowChanged.connect(self.enableListButtons)
self.listbox.itemChanged.connect(self.renameAction)
self.listbox.itemChanged.connect(self.enableOK)
self.shortcutButton.clicked.connect(self.createShortcut)
self._examplelabel = ScrollLabel("")
self.grid.addWidget(self._examplelabel, 1, 0, 1, -1)
self.grid.setRowStretch(1, 0)
if example is None:
self._examplelabel.hide()
self.listbox.itemChanged.connect(self.updateExample)
self.grid.addLayout(self.okcancel, 2, 0, 1, 2)
self.updateExample()
self.enableOK(None)
def createShortcut(self):
macros = self.checked()
names = [m.name for m in macros]
(name, ok) = ShortcutName(self.shortcutNames(), names[0]).getText()
if name and ok:
from . import puddletag
shortcuts = [
str(z.shortcut().toString()) for z in puddletag.status["actions"]
]
(shortcut, ok) = ShortcutDialog(shortcuts).getShortcut()
name = str(name)
from .action_shortcuts import create_action_shortcut, save_shortcut
filenames = [m.filename for m in macros]
if shortcut and ok:
create_action_shortcut(name, filenames, shortcut, add=True)
else:
create_action_shortcut(name, filenames, add=True)
save_shortcut(name, filenames)
def editShortcuts(self):
from . import action_shortcuts
win = action_shortcuts.ShortcutEditor(True, self, True)
win.setModal(True)
win.show()
def moveUp(self):
self.listbox.moveUp(self.macros)
def moveDown(self):
self.listbox.moveDown(self.macros)
def remove(self):
cparser = PuddleConfig()
listbox = self.listbox
rows = sorted([listbox.row(item) for item in listbox.selectedItems()])
for row in rows:
filename = self.macros[row].filename
os.rename(filename, filename + ".deleted")
self.listbox.removeSelected(self.macros)
macros = {}
for i, key in enumerate(self.macros):
macros[i] = self.macros[key]
macros = self.macros
self.macros = dict((i, macros[k]) for i, k in enumerate(sorted(macros)))
def enableListButtons(self, val):
if val == -1:
[button.setEnabled(False) for button in self.buttonlist.widgets[1:]]
else:
[button.setEnabled(True) for button in self.buttonlist.widgets[1:]]
def enableOK(self, val):
item = self.listbox.item
enable = [
row
for row in range(self.listbox.count())
if item(row).checkState() == Qt.CheckState.Checked
]
if enable:
self.okcancel.okButton.setEnabled(True)
self.shortcutButton.setEnabled(True)
else:
self.okcancel.okButton.setEnabled(False)
self.shortcutButton.setEnabled(False)
def renameAction(self, item):
name = str(item.text())
names = [m.name for m in self.macros.values()]
row = self.listbox.row(item)
if name not in names:
macro = self.macros[row]
macro.name = name
self.saveMacro(macro)
else:
self.listbox.blockSignals(True)
item.setText(self.macros[row].name)
self.listbox.blockSignals(False)
def loadMacros(self):
from glob import glob
basename = os.path.basename
funcs = {}
cparser = PuddleConfig()
set_value = partial(cparser.set, "puddleactions")
get_value = partial(cparser.get, "puddleactions")
firstrun = get_value("firstrun", True)
set_value("firstrun", False)
convert = get_value("convert", True)
order = get_value("order", [])
if convert:
set_value("convert", False)
findfunc.convert_actions(SAVEDIR, ACTIONDIR)
if order:
old_order = dict([(basename(z), i) for i, z in enumerate(order)])
files = glob(os.path.join(ACTIONDIR, "*.action"))
order = {}
for i, action_fn in enumerate(files):
try:
order[old_order[basename(action_fn)]] = action_fn
except KeyError:
if not old_order:
order[i] = action_fn
order = [z[1] for z in sorted(order.items())]
set_value("order", order)
files = glob(os.path.join(ACTIONDIR, "*.action"))
if firstrun and not files:
filenames = [":/caseconversion.action", ":/standard.action"]
files = list(map(open_resourcefile, filenames))
set_value("firstrun", False)
for fileobj, filename in zip(files, filenames):
filename = os.path.join(ACTIONDIR, filename[2:])
f = open(filename, "w")
f.write(fileobj.read())
f.close()
files = glob(os.path.join(ACTIONDIR, "*.action"))
files = [z for z in order if z in files] + [z for z in files if z not in order]
return dict((i, Macro(f)) for i, f in enumerate(files))
def updateExample(self, *args):
if self.example is None:
self._examplelabel.hide()
return
l = self.listbox
items = [l.item(z) for z in range(l.count())]
selectedrows = [
i for i, z in enumerate(items) if z.checkState() == Qt.CheckState.Checked
]
if selectedrows:
from .puddletag import status
files = status["selectedfiles"]
total = str(len(files)) if files else "1"
state = {"__counter": "0", "__total_files": total}
macros = [self.macros[i] for i in selectedrows]
try:
tags = apply_macros(macros, self.example, state, self._quickaction)
self._examplelabel.setText(displaytags(tags))
except findfunc.ParseError as e:
self._examplelabel.setText(e.message)
self._examplelabel.show()
else:
self._examplelabel.hide()
def saveMacro(self, macro, filename=None):
cparser = PuddleConfig()
if filename is None and macro.filename:
macro.save()
elif filename:
macro.filename = filename
macro.save()
else:
name = macro.name
filename = os.path.join(ACTIONDIR, safe_name(name) + ".action")
base = os.path.splitext(filename)[0]
i = 0
while os.path.exists(filename):
filename = "%s_%d" % (base, i) + ".action"
i += 1
macro.save(filename)
macro.filename = filename
return filename
def add(self):
(text, ok) = QInputDialog.getText(
self,
translate("Actions", "New Action"),
translate("Actions", "Enter a name for the new action."),
QLineEdit.EchoMode.Normal,
)
if (ok is True) and text:
item = QListWidgetItem(text)
item.setCheckState(Qt.CheckState.Unchecked)
item.setFlags(item.flags() | Qt.ItemFlag.ItemIsEditable)
self.listbox.addItem(item)
else:
return
win = CreateAction(self, example=self.example)
win.setWindowTitle(
translate("Actions", "Add Action: ")
+ self.listbox.item(self.listbox.count() - 1).text()
)
win.setModal(True)
win.donewithmyshit.connect(self.addBuddy)
win.rejected.connect(lambda: self.listbox.takeItem(self.listbox.count() - 1))
win.show()
def addBuddy(self, actions):
m = Macro()
m.name = str(self.listbox.item(self.listbox.count() - 1).text())
m.actions = actions
self.saveMacro(m)
self.macros[self.listbox.count() - 1] = m
def edit(self):
m = self.macros[self.listbox.currentRow()]
win = CreateAction(self, m.actions, example=self.example)
win.setWindowTitle(translate("Actions", "Edit Action: ") + m.name)
win.show()
win.donewithmyshit.connect(self.editBuddy)
def editBuddy(self, actions):
m = self.macros[self.listbox.currentRow()]
m.actions = actions
self.saveMacro(m)
self.updateExample()
def checked(self):
return [self.macros[row] for row in self.checkedRows()]
def checkedRows(self):
l = self.listbox
items = [l.item(z) for z in range(l.count())]
checked = [
i for i, z in enumerate(items) if z.checkState() == Qt.CheckState.Checked
]
return checked
def saveChecked(self):
cparser = PuddleConfig()
m_names = [m.name for m in self.checked()]
cparser.set(self.__configKey, "checked", m_names)
def saveOrder(self):
macros = self.macros
cparser = PuddleConfig()
order = [macros[i].filename for i in sorted(macros)]
lastorder = cparser.get("puddleactions", "order", [])
if lastorder == order:
return
cparser.set("puddleactions", "order", order)
self.actionOrderChanged.emit()
def close(self):
self.saveOrder()
QDialog.close(self)
def okClicked(self, close=True):
"""When clicked, save the current contents of the listbox and the associated functions"""
macros = self.checked()
names = [m.name for m in macros]
cparser = PuddleConfig()
cparser.set(self.__configKey, "checked", names)
if close:
self.close()
self.checkedChanged.emit(self.checkedRows())
self.donewithmyshit.emit(macros)
def duplicate(self):
l = self.listbox
if len(l.selectedItems()) > 1:
return
row = l.currentRow()
oldname = self.macros[row].name
(text, ok) = QInputDialog.getText(
self,
translate("Actions", "Copy %s action" % oldname),
translate("Actions", "Enter a name for the new action."),
QLineEdit.EchoMode.Normal,
)
if not (ok and text):
return
name = str(text)
actions = deepcopy(self.macros[row].actions)
win = CreateAction(self, actions, example=self.example)
win.setWindowTitle(translate("Actions", "Edit Action: %s") % name)
win.show()
dupebuddy = partial(self.duplicateBuddy, name)
win.donewithmyshit.connect(dupebuddy)
def duplicateBuddy(self, name, actions):
item = QListWidgetItem(name)
item.setCheckState(Qt.CheckState.Unchecked)
item.setFlags(item.flags() | Qt.ItemFlag.ItemIsEditable)
self.listbox.addItem(item)
m = Macro()
m.name = name
m.actions = actions
self.saveMacro(m)
self.macros[self.listbox.count() - 1] = m
def shortcutNames(self):
from .action_shortcuts import load_settings
return [name for name, filename in load_settings()[1]]
if __name__ == "__main__":
app = QApplication(sys.argv)
app.setOrganizationName("Puddle Inc.")
app.setApplicationName("puddletag")
qb = ActionWindow(
[
("Path", "__path"),
("Artist", "artist"),
("Title", "title"),
("Album", "album"),
("Track", "track"),
("Length", "__length"),
("Year", "date"),
]
)
qb.show()
app.exec_()
|
femexamples | material_multiple_bendingbeam_fiveboxes | # ***************************************************************************
# * Copyright (c) 2020 Sudhanshu Dubey <sudhanshu.thethunder@gmail.com> *
# * Copyright (c) 2021 Bernd Hahnebach <bernd@bimstatik.org> *
# * *
# * This file is part of the FreeCAD CAx development system. *
# * *
# * This program is free software; you can redistribute it and/or modify *
# * it under the terms of the GNU Lesser General Public License (LGPL) *
# * as published by the Free Software Foundation; either version 2 of *
# * the License, or (at your option) any later version. *
# * for detail see the LICENCE text file. *
# * *
# * This program is distributed in the hope that it will be useful, *
# * but WITHOUT ANY WARRANTY; without even the implied warranty of *
# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
# * GNU Library General Public License for more details. *
# * *
# * You should have received a copy of the GNU Library General Public *
# * License along with this program; if not, write to the Free Software *
# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
# * USA *
# * *
# ***************************************************************************
import BOPTools.SplitFeatures
import Fem
import FreeCAD
import ObjectsFem
from . import manager
from .manager import get_meshname, init_doc
def get_information():
return {
"name": "Multimaterial bending beam 5 boxes",
"meshtype": "solid",
"meshelement": "Tet10",
"constraints": ["fixed", "force"],
"solvers": ["calculix", "ccxtools"],
"material": "multimaterial",
"equations": ["mechanical"],
}
def get_explanation(header=""):
return (
header
+ """
To run the example from Python console use:
from femexamples.material_multiple_bendingbeam_fiveboxes import setup
setup()
See forum topic post:
...
"""
)
def setup(doc=None, solvertype="ccxtools"):
# init FreeCAD document
if doc is None:
doc = init_doc()
# explanation object
# just keep the following line and change text string in get_explanation method
manager.add_explanation_obj(
doc, get_explanation(manager.get_header(get_information()))
)
# geometric objects
# name is important because the other method in this module use obj name
box_obj1 = doc.addObject("Part::Box", "Box1")
box_obj1.Height = 10
box_obj1.Width = 10
box_obj1.Length = 20
box_obj2 = doc.addObject("Part::Box", "Box2")
box_obj2.Height = 10
box_obj2.Width = 10
box_obj2.Length = 20
box_obj2.Placement.Base = (20, 0, 0)
box_obj3 = doc.addObject("Part::Box", "Box3")
box_obj3.Height = 10
box_obj3.Width = 10
box_obj3.Length = 20
box_obj3.Placement.Base = (40, 0, 0)
box_obj4 = doc.addObject("Part::Box", "Box4")
box_obj4.Height = 10
box_obj4.Width = 10
box_obj4.Length = 20
box_obj4.Placement.Base = (60, 0, 0)
box_obj5 = doc.addObject("Part::Box", "Box5")
box_obj5.Height = 10
box_obj5.Width = 10
box_obj5.Length = 20
box_obj5.Placement.Base = (80, 0, 0)
# make a CompSolid out of the boxes, to be able to remesh with GUI
j = BOPTools.SplitFeatures.makeBooleanFragments(name="BooleanFragments")
j.Objects = [box_obj1, box_obj2, box_obj3, box_obj4, box_obj5]
j.Mode = "CompSolid"
j.Proxy.execute(j)
j.purgeTouched()
doc.recompute()
if FreeCAD.GuiUp:
for obj in j.ViewObject.Proxy.claimChildren():
obj.ViewObject.hide()
geom_obj = doc.addObject("Part::Feature", "CompSolid")
geom_obj.Shape = j.Shape.CompSolids[0]
if FreeCAD.GuiUp:
j.ViewObject.hide()
doc.recompute()
if FreeCAD.GuiUp:
geom_obj.ViewObject.Document.activeView().viewAxonometric()
geom_obj.ViewObject.Document.activeView().fitAll()
# analysis
analysis = ObjectsFem.makeAnalysis(doc, "Analysis")
# solver
if solvertype == "calculix":
solver_obj = ObjectsFem.makeSolverCalculix(doc, "SolverCalculiX")
elif solvertype == "ccxtools":
solver_obj = ObjectsFem.makeSolverCalculixCcxTools(doc, "CalculiXccxTools")
solver_obj.WorkingDir = ""
else:
FreeCAD.Console.PrintWarning(
"Unknown or unsupported solver type: {}. "
"No solver object was created.\n".format(solvertype)
)
if solvertype == "calculix" or solvertype == "ccxtools":
solver_obj.SplitInputWriter = False
solver_obj.AnalysisType = "static"
solver_obj.GeometricalNonlinearity = "linear"
solver_obj.ThermoMechSteadyState = False
solver_obj.MatrixSolverType = "default"
solver_obj.IterationsControlParameterTimeUse = False
analysis.addObject(solver_obj)
# material
material_obj1 = ObjectsFem.makeMaterialSolid(doc, "FemMaterial1")
material_obj1.References = [(doc.Box3, "Solid1")]
mat = material_obj1.Material
mat["Name"] = "Concrete-Generic"
mat["YoungsModulus"] = "32000 MPa"
mat["PoissonRatio"] = "0.17"
material_obj1.Material = mat
analysis.addObject(material_obj1)
material_obj2 = ObjectsFem.makeMaterialSolid(doc, "FemMaterial2")
material_obj2.References = [(doc.Box2, "Solid1"), (doc.Box4, "Solid1")]
mat = material_obj2.Material
mat["Name"] = "PLA"
mat["YoungsModulus"] = "3640 MPa"
mat["PoissonRatio"] = "0.36"
material_obj2.Material = mat
analysis.addObject(material_obj2)
material_obj3 = ObjectsFem.makeMaterialSolid(doc, "FemMaterial3")
material_obj3.References = []
mat = material_obj3.Material
mat["Name"] = "Steel-Generic"
mat["YoungsModulus"] = "200000 MPa"
mat["PoissonRatio"] = "0.30"
material_obj3.Material = mat
analysis.addObject(material_obj3)
# constraint fixed
con_fixed = ObjectsFem.makeConstraintFixed(doc, "ConstraintFixed")
con_fixed.References = [(doc.Box1, "Face1"), (doc.Box5, "Face2")]
analysis.addObject(con_fixed)
# constraint force
con_force = ObjectsFem.makeConstraintForce(doc, "ConstraintForce")
con_force.References = [
(doc.Box1, "Face6"),
(doc.Box2, "Face6"),
(doc.Box3, "Face6"),
(doc.Box4, "Face6"),
(doc.Box5, "Face6"),
]
con_force.Force = 10000.00
con_force.Direction = (doc.Box1, ["Edge1"])
con_force.Reversed = True
analysis.addObject(con_force)
# mesh
from .meshes.mesh_multibodybeam_tetra10 import create_elements, create_nodes
fem_mesh = Fem.FemMesh()
control = create_nodes(fem_mesh)
if not control:
FreeCAD.Console.PrintError("Error on creating nodes.\n")
control = create_elements(fem_mesh)
if not control:
FreeCAD.Console.PrintError("Error on creating elements.\n")
femmesh_obj = analysis.addObject(ObjectsFem.makeMeshGmsh(doc, get_meshname()))[0]
femmesh_obj.FemMesh = fem_mesh
femmesh_obj.Part = geom_obj
femmesh_obj.SecondOrderLinear = False
doc.recompute()
return doc
|
formspree | routes | import formspree.forms.api as fa
import formspree.forms.endpoint as fe
import formspree.forms.views as fv
import formspree.static_pages.views as sv
import formspree.users.views as uv
def configure_routes(app):
app.add_url_rule("/", "index", view_func=sv.default, methods=["GET"])
app.add_url_rule("/favicon.ico", view_func=sv.favicon)
app.add_url_rule("/formspree-verify.txt", view_func=sv.formspree_verify)
# Public forms
app.add_url_rule(
"/<email_or_string>", "send", view_func=fe.send, methods=["GET", "POST"]
)
app.add_url_rule(
"/unblock/<email>",
"unblock_email",
view_func=fv.unblock_email,
methods=["GET", "POST"],
)
app.add_url_rule(
"/resend/<email>",
"resend_confirmation",
view_func=fv.resend_confirmation,
methods=["POST"],
)
app.add_url_rule(
"/confirm/<nonce>", "confirm_email", view_func=fv.confirm_email, methods=["GET"]
)
app.add_url_rule(
"/unconfirm/<form_id>",
"request_unconfirm_form",
view_func=fv.request_unconfirm_form,
methods=["GET"],
)
app.add_url_rule(
"/unconfirm/multiple",
"unconfirm_multiple",
view_func=fv.unconfirm_multiple,
methods=["POST"],
)
app.add_url_rule(
"/unconfirm/<digest>/<form_id>",
"unconfirm_form",
view_func=fv.unconfirm_form,
methods=["GET", "POST"],
)
app.add_url_rule("/thanks", "thanks", view_func=fv.thanks, methods=["GET"])
# Users
app.add_url_rule("/account", "account", view_func=uv.account, methods=["GET"])
app.add_url_rule(
"/account/upgrade", "account-upgrade", view_func=uv.upgrade, methods=["POST"]
)
app.add_url_rule("/account/downgrade", view_func=uv.downgrade, methods=["POST"])
app.add_url_rule("/account/resubscribe", view_func=uv.resubscribe, methods=["POST"])
app.add_url_rule("/card/add", "add-card", view_func=uv.add_card, methods=["POST"])
app.add_url_rule(
"/card/<cardid>/default",
"change-default-card",
view_func=uv.change_default_card,
methods=["POST"],
)
app.add_url_rule(
"/card/<cardid>/delete",
"delete-card",
view_func=uv.delete_card,
methods=["POST"],
)
app.add_url_rule(
"/account/billing", "billing-dashboard", view_func=uv.billing, methods=["GET"]
)
app.add_url_rule(
"/account/billing/invoice/update-invoice-address",
"update-invoice-address",
view_func=uv.update_invoice_address,
methods=["POST"],
)
app.add_url_rule(
"/account/billing/invoice/<invoice_id>", view_func=uv.invoice, methods=["GET"]
)
app.add_url_rule(
"/account/add-email",
"add-account-email",
view_func=uv.add_email,
methods=["POST"],
)
app.add_url_rule(
"/account/confirm/<digest>",
"confirm-account-email",
view_func=uv.confirm_email,
methods=["GET"],
)
app.add_url_rule(
"/register", "register", view_func=uv.register, methods=["GET", "POST"]
)
app.add_url_rule("/login", "login", view_func=uv.login, methods=["GET", "POST"])
app.add_url_rule(
"/login/reset",
"forgot-password",
view_func=uv.forgot_password,
methods=["GET", "POST"],
)
app.add_url_rule(
"/login/reset/<digest>",
"reset-password",
view_func=uv.reset_password,
methods=["GET", "POST"],
)
app.add_url_rule("/logout", "logout", view_func=uv.logout, methods=["GET"])
# Users' forms
app.add_url_rule(
"/dashboard", "dashboard", view_func=fv.serve_dashboard, methods=["GET"]
)
app.add_url_rule(
"/forms", "dashboard", view_func=fv.serve_dashboard, methods=["GET"]
)
app.add_url_rule("/forms/<hashid>", view_func=fv.serve_dashboard, methods=["GET"])
app.add_url_rule(
"/forms/<hashid>/<path:s>", view_func=fv.serve_dashboard, methods=["GET"]
)
app.add_url_rule(
"/forms/<hashid>.<format>", view_func=fv.export_submissions, methods=["GET"]
)
app.add_url_rule(
"/forms/whitelabel/preview",
view_func=fv.custom_template_preview_render,
methods=["GET"],
)
app.add_url_rule("/api-int/forms", view_func=fa.list, methods=["GET"])
app.add_url_rule("/api-int/forms", view_func=fa.create, methods=["POST"])
app.add_url_rule("/api-int/forms/<hashid>", view_func=fa.get, methods=["GET"])
app.add_url_rule("/api-int/forms/<hashid>", view_func=fa.update, methods=["PATCH"])
app.add_url_rule("/api-int/forms/<hashid>", view_func=fa.delete, methods=["DELETE"])
app.add_url_rule(
"/api-int/forms/sitewide-check", view_func=fa.sitewide_check, methods=["POST"]
)
app.add_url_rule(
"/api-int/forms/<hashid>/submissions/<submissionid>",
view_func=fa.submission_delete,
methods=["DELETE"],
)
app.add_url_rule(
"/api-int/forms/<hashid>/whitelabel",
view_func=fa.custom_template_set,
methods=["PUT"],
)
# Webhooks
app.add_url_rule("/webhooks/stripe", view_func=uv.stripe_webhook, methods=["POST"])
# Any other static pages and 404
app.add_url_rule(
"/<path:template>", "default", view_func=sv.default, methods=["GET"]
)
|
core | Config | #####################################################################
# -*- coding: utf-8 -*- #
# #
# Frets on Fire #
# Copyright (C) 2006 Sami Kyöstilä #
# 2008 myfingershurt #
# 2008 Capo #
# 2008 Glorandwarf #
# #
# This program is free software; you can redistribute it and/or #
# modify it under the terms of the GNU General Public License #
# as published by the Free Software Foundation; either version 2 #
# of the License, or (at your option) any later version. #
# #
# This program is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU General Public License for more details. #
# #
# You should have received a copy of the GNU General Public License #
# along with this program; if not, write to the Free Software #
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, #
# MA 02110-1301, USA. #
#####################################################################
from __future__ import absolute_import, division, print_function
import logging
import os
import sys
from collections import MutableMapping, namedtuple
import six
from fofix.core import VFS
from fofix.core.utils import unicodify
from six import StringIO
# from fretwork.unicode import unicodify
from six.moves.configparser import RawConfigParser
log = logging.getLogger(__name__)
def decode_string(data):
"""Decode a string from utf-8 or latin-1"""
try:
return data.decode("utf-8")
except UnicodeDecodeError:
return data.decode("latin-1")
except AttributeError:
return data
class MyConfigParser(RawConfigParser):
def _write_section(self, fp, section_name, section_items):
fp.write("[%s]\n" % section_name)
for key, value in sorted(section_items):
if key != "__name__":
fp.write("{} = {}\n".format(key, value))
fp.write("\n")
def write(self, fp, type=0):
if type == 1:
return self.write_controller(fp)
elif type == 2:
return self.write_player(fp)
for section in sorted(self.sections()):
if section not in ("theme", "controller", "player"):
self._write_section(fp, section, self.items(section))
def read(self, filenames):
if isinstance(filenames, six.string_types):
filenames = [filenames]
read_ok = []
for filename in filenames:
config_data = None
try:
with open(filename, "rb") as fp:
config_data = fp.read()
config_data = decode_string(config_data)
config_lines = config_data.split("\n")
config_lines = [
line for line in config_lines if line.strip()[0:2] != "//"
]
config_data = "\n".join(config_lines)
str_fp = StringIO(config_data)
self.readfp(str_fp, filename)
except IOError:
continue
read_ok.append(filename)
return read_ok
def write_controller(self, fp):
"""Write the controller section"""
if self.has_section("controller"):
self._write_section(fp, "controller", self.items("controller"))
def write_player(self, fp):
"""Write the player section"""
if self.has_section("player"):
self._write_section(fp, "player", self.items("player"))
def get(self, section, option):
return unicodify(RawConfigParser.get(self, section, option))
def set(self, section, option, value=None):
RawConfigParser.set(self, section, option, value)
Option = namedtuple("Option", ["type", "default", "text", "options", "tipText"])
class Prototype(MutableMapping):
def __init__(self, *args, **kwargs):
self._data = dict()
self.update(dict(*args, **kwargs))
def __getitem__(self, key):
return self._data[key]
def __setitem__(self, key, value):
self._data[key] = value
def __delitem__(self, key):
del self._data[key]
def __iter__(self):
return iter(self._data)
def __len__(self):
return len(self._data)
def define(
self, section, option, type, default=None, text=None, options=None, tipText=None
):
"""
Define a configuration key.
:param section: Section name
:param option: Option name
:param type: Key type (e.g. str, int, ...)
:param default: Default value for the key
:param text: Text description for the key
:param options: Either a mapping of values to text descriptions
(e.g. {True: 'Yes', False: 'No'}) or a list of possible values
:param tipText: Helpful tip text to display in option menus.
"""
if section not in self._data:
self._data[section] = dict()
if type is bool and options is None:
options = [True, False]
self._data[section][option] = Option(
type=type, default=default, text=text, options=options, tipText=tipText
)
class Config(object):
"""A configuration registry."""
def __init__(self, prototype=None, filename=None, type=0):
"""
:param prototype: The configuration prototype mapping
:param filename: The file that holds this configuration registry
"""
self.prototype = prototype if prototype is not None else Prototype()
self.config = MyConfigParser()
self.type = type
self.read(filename)
def read(self, filename):
"""Read a config file
:param filename: the config filename
"""
if filename:
if not os.path.isfile(filename):
path = VFS.getWritableResourcePath()
filename = os.path.join(path, filename)
self.config.read(filename)
self.filename = filename
def _convertValue(self, value, type, default=False):
"""
Convert a raw config string to the proper data type.
:param value: the raw value
:param type: the desired type
:return: the converted value
"""
if type is bool:
value = str(value).lower()
if value in ("1", "true", "yes", "on"):
return True
elif value in ("none", ""):
return default # allows None-default bools to return None
else:
return False
elif issubclass(type, six.string_types):
return unicodify(value)
else:
try:
return type(value)
except Exception:
return None
def get(self, section, option):
"""
Read a configuration key.
:param section: Section name
:param option: Option name
:return: Key value
"""
try:
type = self.prototype[section][option].type
default = self.prototype[section][option].default
except KeyError:
log.error(
"Config key %s.%s not defined while reading %s.",
section,
option,
self.filename,
)
raise
value = self._convertValue(
self.config.get(section, option)
if self.config.has_option(section, option)
else default,
type,
default,
)
return value
def getOptions(self, section, option):
"""
Read the preset options of a configuration key.
:param section: Section name
:param option: Option name
:return: Tuple of Key list and Values list
"""
try:
options = self.prototype[section][option].options.values()
keys = self.prototype[section][option].options.keys()
type = self.prototype[section][option].type
except KeyError:
log.error(
"Config key %s.%s not defined while reading %s.",
section,
option,
self.filename,
)
raise
optionList = []
if type is not None:
for i in range(len(options)):
value = self._convertValue(keys[i], type)
optionList.append(value)
return optionList, options
def getTipText(self, section, option):
"""
Return the tip text for a configuration key.
:param section: Section name
:param option: Option name
:return: Tip Text String
"""
try:
text = self.prototype[section][option].tipText
except KeyError:
log.error(
"Config key %s.%s not defined while reading %s.",
section,
option,
self.filename,
)
raise
return text
def getDefault(self, section, option):
"""
Read the default value of a configuration key.
:param section: Section name
:param option: Option name
:return: Key value
"""
try:
type = self.prototype[section][option].type
default = self.prototype[section][option].default
except KeyError:
log.error(
"Config key %s.%s not defined while reading %s.",
section,
option,
self.filename,
)
raise
value = self._convertValue(default, type)
return value
def set(self, section, option, value):
"""
Set the value of a configuration key.
:param section: Section name
:param option: Option name
:param value: Value name
"""
try:
self.prototype[section][option]
except KeyError:
log.error(
"Config key %s.%s not defined while writing %s.",
section,
option,
self.filename,
)
raise
if not self.config.has_section(section):
self.config.add_section(section)
self.config.set(section, option, value)
with open(self.filename, "w") as config_file:
self.config.write(config_file, self.type)
def define(self, *args, **kwargs):
self.prototype.define(*args, **kwargs)
class _ModuleWrapper(object):
def __init__(self, module, default):
self.module = module
self.default = default
def __getattr__(self, name):
try:
return getattr(self.default, name)
except AttributeError:
return getattr(self.module, name)
def load(filename=None, setAsDefault=False, type=0):
"""Load a configuration with the default prototype"""
if setAsDefault:
default_config.read(filename)
return default_config
else:
return Config(default_config.prototype, filename, type)
default_config = Config()
# access default config by default, fallback on module
# ideally default config should be explicitly passed around
sys.modules[__name__] = _ModuleWrapper(sys.modules[__name__], default_config)
|
restapi | remote_query_endpoint | import time
from binascii import unhexlify
from aiohttp import web
from aiohttp_apispec import docs, querystring_schema
from ipv8.REST.schema import schema
from marshmallow.fields import List, String
from pony.orm import db_session
from tribler.core.components.gigachannel.community.gigachannel_community import (
GigaChannelCommunity,
)
from tribler.core.components.metadata_store.restapi.metadata_endpoint import (
MetadataEndpointBase,
)
from tribler.core.components.metadata_store.restapi.metadata_schema import (
RemoteQueryParameters,
)
from tribler.core.components.restapi.rest.rest_endpoint import (
HTTP_BAD_REQUEST,
RESTResponse,
)
from tribler.core.utilities.unicode import hexlify
from tribler.core.utilities.utilities import froze_it
@froze_it
class RemoteQueryEndpoint(MetadataEndpointBase):
"""
This endpoint fires a remote search in the IPv8 GigaChannel Community.
"""
path = "/remote_query"
def __init__(self, gigachannel_community: GigaChannelCommunity, *args, **kwargs):
MetadataEndpointBase.__init__(self, *args, **kwargs)
self.gigachannel_community = gigachannel_community
def setup_routes(self):
self.app.add_routes([web.put("", self.create_remote_search_request)])
self.app.add_routes([web.get("/channels_peers", self.get_channels_peers)])
def sanitize_parameters(self, parameters):
sanitized = super().sanitize_parameters(parameters)
if "channel_pk" in parameters:
sanitized["channel_pk"] = unhexlify(parameters["channel_pk"])
if "origin_id" in parameters:
sanitized["origin_id"] = int(parameters["origin_id"])
return sanitized
@docs(
tags=["Metadata"],
summary="Perform a search for a given query.",
responses={
200: {
"schema": schema(
RemoteSearchResponse={
"request_uuid": String(),
"peers": List(String()),
}
)
},
"examples": {
"Success": {
"request_uuid": "268560c0-3f28-4e6e-9d85-d5ccb0269693",
"peers": [
"50e9a2ce646c373985a8e827e328830e053025c6",
"107c84e5d9636c17b46c88c3ddb54842d80081b0",
],
}
},
},
)
@querystring_schema(RemoteQueryParameters)
async def create_remote_search_request(self, request):
self._logger.info("Create remote search request")
# Query remote results from the GigaChannel Community.
# Results are returned over the Events endpoint.
try:
sanitized = self.sanitize_parameters(request.query)
except (ValueError, KeyError) as e:
return RESTResponse(
{"error": f"Error processing request parameters: {e}"},
status=HTTP_BAD_REQUEST,
)
self._logger.info(f"Parameters: {sanitized}")
request_uuid, peers_list = self.gigachannel_community.send_search_request(
**sanitized
)
peers_mid_list = [hexlify(p.mid) for p in peers_list]
return RESTResponse(
{"request_uuid": str(request_uuid), "peers": peers_mid_list}
)
async def get_channels_peers(self, _):
# Get debug stats for peers serving channels
current_time = time.time()
result = []
mapping = self.gigachannel_community.channels_peers
with db_session:
for id_tuple, peers in mapping._channels_dict.items(): # pylint:disable=W0212
channel_pk, channel_id = id_tuple
chan = self.mds.ChannelMetadata.get(
public_key=channel_pk, id_=channel_id
)
peers_list = []
for p in peers:
peers_list.append(
(hexlify(p.mid), int(current_time - p.last_response))
)
chan_dict = {
"channel_name": chan.title if chan else None,
"channel_pk": hexlify(channel_pk),
"channel_id": channel_id,
"peers": peers_list,
}
result.append(chan_dict)
return RESTResponse({"channels_list": result})
|
action | create | # encoding: utf-8
"""API functions for adding data to CKAN."""
from __future__ import annotations
import datetime
import logging
import random
import re
from socket import error as socket_error
from typing import Any, Union, cast
import ckan.authz as authz
import ckan.common
import ckan.lib.api_token as api_token
import ckan.lib.datapreview
import ckan.lib.dictization
import ckan.lib.dictization.model_dictize as model_dictize
import ckan.lib.dictization.model_save as model_save
import ckan.lib.mailer as mailer
import ckan.lib.navl.dictization_functions
import ckan.lib.plugins as lib_plugins
import ckan.lib.signals as signals
import ckan.lib.uploader as uploader
import ckan.logic as logic
import ckan.logic.action
import ckan.logic.schema
import ckan.logic.validators
import ckan.model
import ckan.plugins as plugins
import six
from ckan.common import _
# FIXME this looks nasty and should be shared better
from ckan.logic.action.update import _update_package_relationship
from ckan.types import Context, DataDict, ErrorDict, Schema
from ckan.types.logic import ActionResult
log = logging.getLogger(__name__)
# Define some shortcuts
# Ensure they are module-private so that they don't get loaded as available
# actions in the action API.
_validate = ckan.lib.navl.dictization_functions.validate
_check_access = logic.check_access
_get_action = logic.get_action
ValidationError = logic.ValidationError
NotFound = logic.NotFound
NotAuthorized = logic.NotAuthorized
_get_or_bust = logic.get_or_bust
fresh_context = logic.fresh_context
def package_create(context: Context, data_dict: DataDict) -> ActionResult.PackageCreate:
"""Create a new dataset (package).
You must be authorized to create new datasets. If you specify any groups
for the new dataset, you must also be authorized to edit these groups.
Plugins may change the parameters of this function depending on the value
of the ``type`` parameter, see the
:py:class:`~ckan.plugins.interfaces.IDatasetForm` plugin interface.
:param name: the name of the new dataset, must be between 2 and 100
characters long and contain only lowercase alphanumeric characters,
``-`` and ``_``, e.g. ``'warandpeace'``
:type name: string
:param title: the title of the dataset (optional, default: same as
``name``)
:type title: string
:param private: If ``True`` creates a private dataset
:type private: bool
:param author: the name of the dataset's author (optional)
:type author: string
:param author_email: the email address of the dataset's author (optional)
:type author_email: string
:param maintainer: the name of the dataset's maintainer (optional)
:type maintainer: string
:param maintainer_email: the email address of the dataset's maintainer
(optional)
:type maintainer_email: string
:param license_id: the id of the dataset's license, see
:py:func:`~ckan.logic.action.get.license_list` for available values
(optional)
:type license_id: license id string
:param notes: a description of the dataset (optional)
:type notes: string
:param url: a URL for the dataset's source (optional)
:type url: string
:param version: (optional)
:type version: string, no longer than 100 characters
:param state: the current state of the dataset, e.g. ``'active'`` or
``'deleted'``, only active datasets show up in search results and
other lists of datasets, this parameter will be ignored if you are not
authorized to change the state of the dataset (optional, default:
``'active'``)
:type state: string
:param type: the type of the dataset (optional),
:py:class:`~ckan.plugins.interfaces.IDatasetForm` plugins
associate themselves with different dataset types and provide custom
dataset handling behaviour for these types
:type type: string
:param resources: the dataset's resources, see
:py:func:`resource_create` for the format of resource dictionaries
(optional)
:type resources: list of resource dictionaries
:param tags: the dataset's tags, see :py:func:`tag_create` for the format
of tag dictionaries (optional)
:type tags: list of tag dictionaries
:param extras: the dataset's extras (optional), extras are arbitrary
(key: value) metadata items that can be added to datasets, each extra
dictionary should have keys ``'key'`` (a string), ``'value'`` (a
string)
:type extras: list of dataset extra dictionaries
:param plugin_data: private package data belonging to plugins.
Only sysadmin users may set this value. It should be a dict that can
be dumped into JSON, and plugins should namespace their data with the
plugin name to avoid collisions with other plugins, eg::
{
"name": "test-dataset",
"plugin_data": {
"plugin1": {"key1": "value1"},
"plugin2": {"key2": "value2"}
}
}
:type plugin_data: dict
:param relationships_as_object: see :py:func:`package_relationship_create`
for the format of relationship dictionaries (optional)
:type relationships_as_object: list of relationship dictionaries
:param relationships_as_subject: see :py:func:`package_relationship_create`
for the format of relationship dictionaries (optional)
:type relationships_as_subject: list of relationship dictionaries
:param groups: the groups to which the dataset belongs (optional), each
group dictionary should have one or more of the following keys which
identify an existing group:
``'id'`` (the id of the group, string), or ``'name'`` (the name of the
group, string), to see which groups exist
call :py:func:`~ckan.logic.action.get.group_list`
:type groups: list of dictionaries
:param owner_org: the id of the dataset's owning organization, see
:py:func:`~ckan.logic.action.get.organization_list` or
:py:func:`~ckan.logic.action.get.organization_list_for_user` for
available values. This parameter can be made optional if the config
option :ref:`ckan.auth.create_unowned_dataset` is set to ``True``.
:type owner_org: string
:returns: the newly created dataset (unless 'return_id_only' is set to True
in the context, in which case just the dataset id will
be returned)
:rtype: dictionary
"""
model = context["model"]
user = context["user"]
if "type" not in data_dict:
package_plugin = lib_plugins.lookup_package_plugin()
try:
# use first type as default if user didn't provide type
package_type = package_plugin.package_types()[0]
except (AttributeError, IndexError):
package_type = "dataset"
# in case a 'dataset' plugin was registered w/o fallback
package_plugin = lib_plugins.lookup_package_plugin(package_type)
data_dict["type"] = package_type
else:
package_plugin = lib_plugins.lookup_package_plugin(data_dict["type"])
schema: Schema = context.get("schema") or package_plugin.create_package_schema()
_check_access("package_create", context, data_dict)
data, errors = lib_plugins.plugin_validate(
package_plugin, context, data_dict, schema, "package_create"
)
log.debug(
"package_create validate_errs=%r user=%s package=%s data=%r",
errors,
context.get("user"),
data.get("name"),
data_dict,
)
if errors:
model.Session.rollback()
raise ValidationError(errors)
plugin_data = data.get("plugin_data", False)
include_plugin_data = False
if user:
user_obj = model.User.by_name(six.ensure_text(user))
if user_obj:
data["creator_user_id"] = user_obj.id
include_plugin_data = user_obj.sysadmin and plugin_data
pkg = model_save.package_dict_save(data, context, include_plugin_data)
# Needed to let extensions know the package and resources ids
model.Session.flush()
data["id"] = pkg.id
if data.get("resources"):
for index, resource in enumerate(data["resources"]):
resource["id"] = pkg.resources[index].id
context_org_update = context.copy()
context_org_update["ignore_auth"] = True
context_org_update["defer_commit"] = True
_get_action("package_owner_org_update")(
context_org_update, {"id": pkg.id, "organization_id": pkg.owner_org}
)
for item in plugins.PluginImplementations(plugins.IPackageController):
item.create(pkg)
item.after_dataset_create(context, data)
# Make sure that a user provided schema is not used in create_views
# and on package_show
context.pop("schema", None)
# Create default views for resources if necessary
if data.get("resources"):
logic.get_action("package_create_default_resource_views")(
{"model": context["model"], "user": context["user"], "ignore_auth": True},
{"package": data},
)
if not context.get("defer_commit"):
model.repo.commit()
return_id_only = context.get("return_id_only", False)
if return_id_only:
return pkg.id
return _get_action("package_show")(
context.copy(), {"id": pkg.id, "include_plugin_data": include_plugin_data}
)
def resource_create(
context: Context, data_dict: DataDict
) -> ActionResult.ResourceCreate:
"""Appends a new resource to a datasets list of resources.
:param package_id: id of package that the resource should be added to.
:type package_id: string
:param url: url of resource
:type url: string
:param description: (optional)
:type description: string
:param format: (optional)
:type format: string
:param hash: (optional)
:type hash: string
:param name: (optional)
:type name: string
:param resource_type: (optional)
:type resource_type: string
:param mimetype: (optional)
:type mimetype: string
:param mimetype_inner: (optional)
:type mimetype_inner: string
:param cache_url: (optional)
:type cache_url: string
:param size: (optional)
:type size: int
:param created: (optional)
:type created: iso date string
:param last_modified: (optional)
:type last_modified: iso date string
:param cache_last_updated: (optional)
:type cache_last_updated: iso date string
:param upload: (optional)
:type upload: FieldStorage (optional) needs multipart/form-data
:returns: the newly created resource
:rtype: dictionary
"""
model = context["model"]
package_id = _get_or_bust(data_dict, "package_id")
if not data_dict.get("url"):
data_dict["url"] = ""
package_show_context: Union[Context, Any] = dict(context, for_update=True)
pkg_dict = _get_action("package_show")(package_show_context, {"id": package_id})
_check_access("resource_create", context, data_dict)
for plugin in plugins.PluginImplementations(plugins.IResourceController):
plugin.before_resource_create(context, data_dict)
if "resources" not in pkg_dict:
pkg_dict["resources"] = []
upload = uploader.get_resource_uploader(data_dict)
if "mimetype" not in data_dict:
if hasattr(upload, "mimetype"):
data_dict["mimetype"] = upload.mimetype
if "size" not in data_dict:
if hasattr(upload, "filesize"):
data_dict["size"] = upload.filesize
pkg_dict["resources"].append(data_dict)
try:
context["defer_commit"] = True
context["use_cache"] = False
_get_action("package_update")(context, pkg_dict)
context.pop("defer_commit")
except ValidationError as e:
try:
error_dict = cast("list[ErrorDict]", e.error_dict["resources"])[-1]
except (KeyError, IndexError):
error_dict = e.error_dict
raise ValidationError(error_dict)
# Get out resource_id resource from model as it will not appear in
# package_show until after commit
package = context["package"]
assert package
upload.upload(package.resources[-1].id, uploader.get_max_resource_size())
model.repo.commit()
# Run package show again to get out actual last_resource
updated_pkg_dict = _get_action("package_show")(context, {"id": package_id})
resource = updated_pkg_dict["resources"][-1]
# Add the default views to the new resource
logic.get_action("resource_create_default_resource_views")(
{"model": context["model"], "user": context["user"], "ignore_auth": True},
{"resource": resource, "package": updated_pkg_dict},
)
for plugin in plugins.PluginImplementations(plugins.IResourceController):
plugin.after_resource_create(context, resource)
return resource
def resource_view_create(
context: Context, data_dict: DataDict
) -> ActionResult.ResourceViewCreate:
"""Creates a new resource view.
:param resource_id: id of the resource
:type resource_id: string
:param title: the title of the view
:type title: string
:param description: a description of the view (optional)
:type description: string
:param view_type: type of view
:type view_type: string
:param config: options necessary to recreate a view state (optional)
:type config: JSON string
:returns: the newly created resource view
:rtype: dictionary
"""
model = context["model"]
resource_id = _get_or_bust(data_dict, "resource_id")
view_type = _get_or_bust(data_dict, "view_type")
view_plugin = ckan.lib.datapreview.get_view_plugin(view_type)
if not view_plugin:
raise ValidationError(
{
"view_type": "No plugin found for view_type {view_type}".format(
view_type=view_type
)
}
)
default: Schema = ckan.logic.schema.default_create_resource_view_schema(view_plugin)
schema: Schema = context.get("schema", default)
plugin_schema: Schema = view_plugin.info().get("schema", {})
schema.update(plugin_schema)
data, errors = _validate(data_dict, schema, context)
if errors:
model.Session.rollback()
raise ValidationError(errors)
_check_access("resource_view_create", context, data_dict)
if context.get("preview"):
return data
last_view = (
model.Session.query(model.ResourceView)
.filter_by(resource_id=resource_id)
.order_by(
# type_ignore_reason: incomplete SQLAlchemy types
model.ResourceView.order.desc() # type: ignore
)
.first()
)
if not last_view:
order = 0
else:
order = last_view.order + 1
data["order"] = order
resource_view = model_save.resource_view_dict_save(data, context)
if not context.get("defer_commit"):
model.repo.commit()
return model_dictize.resource_view_dictize(resource_view, context)
def resource_create_default_resource_views(
context: Context, data_dict: DataDict
) -> ActionResult.ResourceCreateDefaultResourceViews:
"""
Creates the default views (if necessary) on the provided resource
The function will get the plugins for the default views defined in
the configuration, and if some were found the `can_view` method of
each one of them will be called to determine if a resource view should
be created. Resource views extensions get the resource dict and the
parent dataset dict.
If the latter is not provided, `package_show` is called to get it.
By default only view plugins that don't require the resource data to be in
the DataStore are called. See
:py:func:`ckan.logic.action.create.package_create_default_resource_views.``
for details on the ``create_datastore_views`` parameter.
:param resource: full resource dict
:type resource: dict
:param package: full dataset dict (optional, if not provided
:py:func:`~ckan.logic.action.get.package_show` will be called).
:type package: dict
:param create_datastore_views: whether to create views that rely on data
being on the DataStore (optional, defaults to False)
:type create_datastore_views: bool
:returns: a list of resource views created (empty if none were created)
:rtype: list of dictionaries
"""
resource_dict = _get_or_bust(data_dict, "resource")
_check_access("resource_create_default_resource_views", context, data_dict)
dataset_dict = data_dict.get("package")
create_datastore_views = ckan.common.asbool(
data_dict.get("create_datastore_views", False)
)
return ckan.lib.datapreview.add_views_to_resource(
context,
resource_dict,
dataset_dict,
view_types=[],
create_datastore_views=create_datastore_views,
)
def package_create_default_resource_views(
context: Context, data_dict: DataDict
) -> ActionResult.PackageCreateDefaultResourceViews:
"""
Creates the default views on all resources of the provided dataset
By default only view plugins that don't require the resource data to be in
the DataStore are called. Passing `create_datastore_views` as True will
only create views that require data to be in the DataStore. The first case
happens when the function is called from `package_create` or
`package_update`, the second when it's called from the DataPusher when
data was uploaded to the DataStore.
:param package: full dataset dict (ie the one obtained
calling :py:func:`~ckan.logic.action.get.package_show`).
:type package: dict
:param create_datastore_views: whether to create views that rely on data
being on the DataStore (optional, defaults to False)
:type create_datastore_views: bool
:returns: a list of resource views created (empty if none were created)
:rtype: list of dictionaries
"""
dataset_dict = _get_or_bust(data_dict, "package")
_check_access("package_create_default_resource_views", context, data_dict)
create_datastore_views = ckan.common.asbool(
data_dict.get("create_datastore_views", False)
)
return ckan.lib.datapreview.add_views_to_dataset_resources(
context,
dataset_dict,
view_types=[],
create_datastore_views=create_datastore_views,
)
def package_relationship_create(
context: Context, data_dict: DataDict
) -> ActionResult.PackageRelationshipCreate:
"""Create a relationship between two datasets (packages).
You must be authorized to edit both the subject and the object datasets.
:param subject: the id or name of the dataset that is the subject of the
relationship
:type subject: string
:param object: the id or name of the dataset that is the object of the
relationship
:param type: the type of the relationship, one of ``'depends_on'``,
``'dependency_of'``, ``'derives_from'``, ``'has_derivation'``,
``'links_to'``, ``'linked_from'``, ``'child_of'`` or ``'parent_of'``
:type type: string
:param comment: a comment about the relationship (optional)
:type comment: string
:returns: the newly created package relationship
:rtype: dictionary
"""
model = context["model"]
schema = (
context.get("schema") or ckan.logic.schema.default_create_relationship_schema()
)
api = context.get("api_version")
ref_package_by = "id" if api == 2 else "name"
id, id2, rel_type = _get_or_bust(data_dict, ["subject", "object", "type"])
comment = data_dict.get("comment", "")
pkg1 = model.Package.get(id)
pkg2 = model.Package.get(id2)
if not pkg1:
raise NotFound("Subject package %r was not found." % id)
if not pkg2:
raise NotFound("Object package %r was not found." % id2)
_data, errors = _validate(data_dict, schema, context)
if errors:
model.Session.rollback()
raise ValidationError(errors)
_check_access("package_relationship_create", context, data_dict)
# Create a Package Relationship.
existing_rels = pkg1.get_relationships_with(pkg2, rel_type)
if existing_rels:
return _update_package_relationship(existing_rels[0], comment, context)
rel = pkg1.add_relationship(rel_type, pkg2, comment=comment)
if not context.get("defer_commit"):
model.repo.commit_and_remove()
context["relationship"] = rel
relationship_dicts = rel.as_dict(ref_package_by=ref_package_by)
return relationship_dicts
def member_create(context: Context, data_dict: DataDict) -> ActionResult.MemberCreate:
"""Make an object (e.g. a user, dataset or group) a member of a group.
If the object is already a member of the group then the capacity of the
membership will be updated.
You must be authorized to edit the group.
:param id: the id or name of the group to add the object to
:type id: string
:param object: the id or name of the object to add
:type object: string
:param object_type: the type of the object being added, e.g. ``'package'``
or ``'user'``
:type object_type: string
:param capacity: the capacity of the membership
:type capacity: string
:returns: the newly created (or updated) membership
:rtype: dictionary
"""
model = context["model"]
user = context["user"]
group_id, obj_id, obj_type, capacity = _get_or_bust(
data_dict, ["id", "object", "object_type", "capacity"]
)
group = model.Group.get(group_id)
if not group:
raise NotFound("Group was not found.")
obj_class = logic.model_name_to_class(model, obj_type)
obj = obj_class.get(obj_id)
if not obj:
raise NotFound("%s was not found." % obj_type.title())
_check_access("member_create", context, data_dict)
# Look up existing, in case it exists
member = (
model.Session.query(model.Member)
.filter(model.Member.table_name == obj_type)
.filter(model.Member.table_id == obj.id)
.filter(model.Member.group_id == group.id)
.filter(model.Member.state == "active")
.first()
)
if member:
user_obj = model.User.get(user)
if (
user_obj
and member.table_name == "user"
and member.table_id == user_obj.id
and member.capacity == "admin"
and capacity != "admin"
):
raise NotAuthorized(
"Administrators cannot revoke their " "own admin status"
)
else:
member = model.Member(
table_name=obj_type, table_id=obj.id, group_id=group.id, state="active"
)
member.group = group
member.capacity = capacity
model.Session.add(member)
if not context.get("defer_commit"):
model.repo.commit()
return model_dictize.member_dictize(member, context)
def package_collaborator_create(
context: Context, data_dict: DataDict
) -> ActionResult.PackageCollaboratorCreate:
"""Make a user a collaborator in a dataset.
If the user is already a collaborator in the dataset then their
capacity will be updated.
Currently you must be an Admin on the dataset owner organization to
manage collaborators.
Note: This action requires the collaborators feature to be enabled with
the :ref:`ckan.auth.allow_dataset_collaborators` configuration option.
:param id: the id or name of the dataset
:type id: string
:param user_id: the id or name of the user to add or edit
:type user_id: string
:param capacity: the capacity or role of the membership. Must be one of
"editor" or "member". Additionally
if :ref:`ckan.auth.allow_admin_collaborators` is set to True, "admin"
is also allowed.
:type capacity: string
:returns: the newly created (or updated) collaborator
:rtype: dictionary
"""
model = context["model"]
package_id, user_id, capacity = _get_or_bust(
data_dict, ["id", "user_id", "capacity"]
)
allowed_capacities = authz.get_collaborator_capacities()
if capacity not in allowed_capacities:
raise ValidationError(
{
"message": _('Role must be one of "{}"').format(
", ".join(allowed_capacities)
)
}
)
_check_access("package_collaborator_create", context, data_dict)
package = model.Package.get(package_id)
if not package:
raise NotFound(_("Dataset not found"))
user = model.User.get(user_id)
if not user:
raise NotFound(_("User not found"))
if not authz.check_config_permission("allow_dataset_collaborators"):
raise ValidationError({"message": _("Dataset collaborators not enabled")})
# Check if collaborator already exists
collaborator = (
model.Session.query(model.PackageMember)
.filter(model.PackageMember.package_id == package.id)
.filter(model.PackageMember.user_id == user.id)
.one_or_none()
)
if not collaborator:
collaborator = model.PackageMember(package_id=package.id, user_id=user.id)
collaborator.capacity = capacity
collaborator.modified = datetime.datetime.utcnow()
model.Session.add(collaborator)
model.repo.commit()
log.info(
"User {} added as collaborator in package {} ({})".format(
user.name, package.id, capacity
)
)
return model_dictize.member_dictize(collaborator, context)
def _group_or_org_create(
context: Context, data_dict: DataDict, is_org: bool = False
) -> Union[str, dict[str, Any]]:
model = context["model"]
user = context["user"]
session = context["session"]
data_dict["is_organization"] = is_org
upload = uploader.get_uploader("group")
upload.update_data_dict(data_dict, "image_url", "image_upload", "clear_upload")
# get the schema
group_type = data_dict.get("type", "organization" if is_org else "group")
group_plugin = lib_plugins.lookup_group_plugin(group_type)
try:
schema: Schema = group_plugin.form_to_db_schema_options(
{"type": "create", "api": "api_version" in context, "context": context}
)
except AttributeError:
schema = group_plugin.form_to_db_schema()
data, errors = lib_plugins.plugin_validate(
group_plugin,
context,
data_dict,
schema,
"organization_create" if is_org else "group_create",
)
log.debug(
"group_create validate_errs=%r user=%s group=%s data_dict=%r",
errors,
context.get("user"),
data_dict.get("name"),
data_dict,
)
if errors:
session.rollback()
raise ValidationError(errors)
group = model_save.group_dict_save(data, context)
# Needed to let extensions know the group id
session.flush()
if is_org:
plugin_type = plugins.IOrganizationController
else:
plugin_type = plugins.IGroupController
for item in plugins.PluginImplementations(plugin_type):
item.create(group)
user_obj = model.User.by_name(six.ensure_text(user))
assert user_obj
upload.upload(uploader.get_max_image_size())
if not context.get("defer_commit"):
model.repo.commit()
context["group"] = group
context["id"] = group.id
# creator of group/org becomes an admin
# this needs to be after the repo.commit or else revisions break
member_dict = {
"id": group.id,
"object": user_obj.id,
"object_type": "user",
"capacity": "admin",
}
member_create_context = fresh_context(context)
# We are not a member of the group at this point
member_create_context["ignore_auth"] = True
logic.get_action("member_create")(member_create_context, member_dict)
log.debug("Created object %s" % group.name)
return_id_only = context.get("return_id_only", False)
action = "organization_show" if is_org else "group_show"
output = (
context["id"]
if return_id_only
else _get_action(action)(context, {"id": group.id})
)
return output
def group_create(context: Context, data_dict: DataDict) -> ActionResult.GroupCreate:
"""Create a new group.
You must be authorized to create groups.
Plugins may change the parameters of this function depending on the value
of the ``type`` parameter, see the
:py:class:`~ckan.plugins.interfaces.IGroupForm` plugin interface.
:param name: the name of the group, a string between 2 and 100 characters
long, containing only lowercase alphanumeric characters, ``-`` and
``_``
:type name: string
:param id: the id of the group (optional)
:type id: string
:param title: the title of the group (optional)
:type title: string
:param description: the description of the group (optional)
:type description: string
:param image_url: the URL to an image to be displayed on the group's page
(optional)
:type image_url: string
:param type: the type of the group (optional, default: ``'group'``),
:py:class:`~ckan.plugins.interfaces.IGroupForm` plugins
associate themselves with different group types and provide custom
group handling behaviour for these types
Cannot be 'organization'
:type type: string
:param state: the current state of the group, e.g. ``'active'`` or
``'deleted'``, only active groups show up in search results and
other lists of groups, this parameter will be ignored if you are not
authorized to change the state of the group (optional, default:
``'active'``)
:type state: string
:param approval_status: (optional)
:type approval_status: string
:param extras: the group's extras (optional), extras are arbitrary
(key: value) metadata items that can be added to groups, each extra
dictionary should have keys ``'key'`` (a string), ``'value'`` (a
string), and optionally ``'deleted'``
:type extras: list of dataset extra dictionaries
:param packages: the datasets (packages) that belong to the group, a list
of dictionaries each with keys ``'name'`` (string, the id or name of
the dataset) and optionally ``'title'`` (string, the title of the
dataset)
:type packages: list of dictionaries
:param groups: the groups that belong to the group, a list of dictionaries
each with key ``'name'`` (string, the id or name of the group) and
optionally ``'capacity'`` (string, the capacity in which the group is
a member of the group)
:type groups: list of dictionaries
:param users: the users that belong to the group, a list of dictionaries
each with key ``'name'`` (string, the id or name of the user) and
optionally ``'capacity'`` (string, the capacity in which the user is
a member of the group)
:type users: list of dictionaries
:returns: the newly created group (unless 'return_id_only' is set to True
in the context, in which case just the group id will
be returned)
:rtype: dictionary
"""
# wrapper for creating groups
if data_dict.get("type") == "organization":
# FIXME better exception?
raise Exception(_("Trying to create an organization as a group"))
_check_access("group_create", context, data_dict)
return _group_or_org_create(context, data_dict)
def organization_create(
context: Context, data_dict: DataDict
) -> ActionResult.OrganizationCreate:
"""Create a new organization.
You must be authorized to create organizations.
Plugins may change the parameters of this function depending on the value
of the ``type`` parameter, see the
:py:class:`~ckan.plugins.interfaces.IGroupForm` plugin interface.
:param name: the name of the organization, a string between 2 and
100 characters long, containing only lowercase alphanumeric
characters, ``-`` and ``_``
:type name: string
:param id: the id of the organization (optional)
:type id: string
:param title: the title of the organization (optional)
:type title: string
:param description: the description of the organization (optional)
:type description: string
:param image_url: the URL to an image to be displayed on the
organization's page (optional)
:type image_url: string
:param state: the current state of the organization, e.g. ``'active'`` or
``'deleted'``, only active organizations show up in search results and
other lists of organizations, this parameter will be ignored if you
are not authorized to change the state of the organization
(optional, default: ``'active'``)
:type state: string
:param approval_status: (optional)
:type approval_status: string
:param extras: the organization's extras (optional), extras are arbitrary
(key: value) metadata items that can be added to organizations,
each extra
dictionary should have keys ``'key'`` (a string), ``'value'`` (a
string), and optionally ``'deleted'``
:type extras: list of dataset extra dictionaries
:param packages: the datasets (packages) that belong to the organization,
a list of dictionaries each with keys ``'name'`` (string, the id
or name of the dataset) and optionally ``'title'`` (string, the
title of the dataset)
:type packages: list of dictionaries
:param users: the users that belong to the organization, a list
of dictionaries each with key ``'name'`` (string, the id or name
of the user) and optionally ``'capacity'`` (string, the capacity
in which the user is a member of the organization)
:type users: list of dictionaries
:returns: the newly created organization (unless 'return_id_only' is set
to True in the context, in which case just the organization id
will be returned)
:rtype: dictionary
"""
# wrapper for creating organizations
data_dict.setdefault("type", "organization")
_check_access("organization_create", context, data_dict)
return _group_or_org_create(context, data_dict, is_org=True)
def user_create(context: Context, data_dict: DataDict) -> ActionResult.UserCreate:
"""Create a new user.
You must be authorized to create users.
:param name: the name of the new user, a string between 2 and 100
characters in length, containing only lowercase alphanumeric
characters, ``-`` and ``_``
:type name: string
:param email: the email address for the new user
:type email: string
:param password: the password of the new user, a string of at least 4
characters
:type password: string
:param id: the id of the new user (optional)
:type id: string
:param fullname: the full name of the new user (optional)
:type fullname: string
:param about: a description of the new user (optional)
:type about: string
:param image_url: the URL to an image to be displayed on the group's page
(optional)
:type image_url: string
:param plugin_extras: private extra user data belonging to plugins.
Only sysadmin users may set this value. It should be a dict that can
be dumped into JSON, and plugins should namespace their extras with
the plugin name to avoid collisions with other plugins, eg::
{
"name": "test_user",
"email": "test@example.com",
"plugin_extras": {
"my_plugin": {
"private_extra": 1
},
"another_plugin": {
"another_extra": True
}
}
}
:type plugin_extras: dict
:returns: the newly created user
:rtype: dictionary
"""
model = context["model"]
schema = context.get("schema") or ckan.logic.schema.default_user_schema()
session = context["session"]
_check_access("user_create", context, data_dict)
author_obj = model.User.get(context.get("user"))
if data_dict.get("id"):
is_sysadmin = author_obj and author_obj.sysadmin
if not is_sysadmin or model.User.get(data_dict["id"]):
data_dict.pop("id", None)
context.pop("user_obj", None)
upload = uploader.get_uploader("user")
upload.update_data_dict(data_dict, "image_url", "image_upload", "clear_upload")
data, errors = _validate(data_dict, schema, context)
if errors:
session.rollback()
raise ValidationError(errors)
# user schema prevents non-sysadmins from providing password_hash
if "password_hash" in data:
data["_password"] = data.pop("password_hash")
user = model_save.user_dict_save(data, context)
signals.user_created.send(user.name, user=user)
upload.upload(uploader.get_max_image_size())
if not context.get("defer_commit"):
with logic.guard_against_duplicated_email(data_dict["email"]):
model.repo.commit()
else:
# The Dashboard object below needs the user id, and if we didn't
# commit we need to flush the session in order to populate it
session.flush()
# A new context is required for dictizing the newly constructed user in
# order that all the new user's data is returned, in particular, the
# api_key.
#
# The context is copied so as not to clobber the caller's context dict.
user_dictize_context = context.copy()
user_dictize_context["keep_apikey"] = True
user_dictize_context["keep_email"] = True
include_plugin_extras = False
if author_obj:
include_plugin_extras = author_obj.sysadmin and "plugin_extras" in data
user_dict = model_dictize.user_dictize(
user, user_dictize_context, include_plugin_extras=include_plugin_extras
)
context["user_obj"] = user
context["id"] = user.id
# Create dashboard for user.
dashboard = model.Dashboard(user.id)
session.add(dashboard)
if not context.get("defer_commit"):
model.repo.commit()
log.debug("Created user {name}".format(name=user.name))
return user_dict
def user_invite(context: Context, data_dict: DataDict) -> ActionResult.UserInvite:
"""Invite a new user.
You must be authorized to create group members.
:param email: the email of the user to be invited to the group
:type email: string
:param group_id: the id or name of the group
:type group_id: string
:param role: role of the user in the group. One of ``member``, ``editor``,
or ``admin``
:type role: string
:returns: the newly created user
:rtype: dictionary
"""
_check_access("user_invite", context, data_dict)
schema = context.get("schema", ckan.logic.schema.default_user_invite_schema())
data, errors = _validate(data_dict, schema, context)
if errors:
raise ValidationError(errors)
model = context["model"]
group = model.Group.get(data["group_id"])
if not group:
raise NotFound()
name = _get_random_username_from_email(data["email"])
data["name"] = name
# send the proper schema when creating a user from here
# so the password field would be ignored.
invite_schema = ckan.logic.schema.create_user_for_user_invite_schema()
data["state"] = model.State.PENDING
user_dict = _get_action("user_create")(
Context(context, schema=invite_schema, ignore_auth=True), data
)
user = model.User.get(user_dict["id"])
assert user
member_dict = {"username": user.id, "id": data["group_id"], "role": data["role"]}
org_or_group = "organization" if group.is_organization else "group"
_get_action(f"{org_or_group}_member_create")(context, member_dict)
group_dict = _get_action(f"{org_or_group}_show")(context, {"id": data["group_id"]})
try:
mailer.send_invite(user, group_dict, data["role"])
except (socket_error, mailer.MailerException) as error:
# Email could not be sent, delete the pending user
_get_action("user_delete")(context, {"id": user.id})
message = _(
"Error sending the invite email, " "the user was not created: {0}"
).format(error)
raise ValidationError(message)
return model_dictize.user_dictize(user, context)
def _get_random_username_from_email(email: str):
localpart = email.split("@")[0]
cleaned_localpart = re.sub(r"[^\w]", "-", localpart).lower()
# if we can't create a unique user name within this many attempts
# then something else is probably wrong and we should give up
max_name_creation_attempts = 100
for _i in range(max_name_creation_attempts):
random_number = random.SystemRandom().random() * 10000
name = "%s-%d" % (cleaned_localpart, random_number)
if not ckan.model.User.get(name):
return name
return cleaned_localpart
def vocabulary_create(
context: Context, data_dict: DataDict
) -> ActionResult.VocabularyCreate:
"""Create a new tag vocabulary.
You must be a sysadmin to create vocabularies.
:param name: the name of the new vocabulary, e.g. ``'Genre'``
:type name: string
:param tags: the new tags to add to the new vocabulary, for the format of
tag dictionaries see :py:func:`tag_create`
:type tags: list of tag dictionaries
:returns: the newly-created vocabulary
:rtype: dictionary
"""
model = context["model"]
schema = (
context.get("schema") or ckan.logic.schema.default_create_vocabulary_schema()
)
_check_access("vocabulary_create", context, data_dict)
data, errors = _validate(data_dict, schema, context)
if errors:
model.Session.rollback()
raise ValidationError(errors)
vocabulary = model_save.vocabulary_dict_save(data, context)
if not context.get("defer_commit"):
model.repo.commit()
log.debug("Created Vocabulary %s" % vocabulary.name)
return model_dictize.vocabulary_dictize(vocabulary, context)
def tag_create(context: Context, data_dict: DataDict) -> ActionResult.TagCreate:
"""Create a new vocabulary tag.
You must be a sysadmin to create vocabulary tags.
You can only use this function to create tags that belong to a vocabulary,
not to create free tags. (To create a new free tag simply add the tag to
a package, e.g. using the
:py:func:`~ckan.logic.action.update.package_update` function.)
:param name: the name for the new tag, a string between 2 and 100
characters long containing only alphanumeric characters,
spaces and the characters ``-``,
``_`` and ``.``, e.g. ``'Jazz'``
:type name: string
:param vocabulary_id: the id of the vocabulary that the new tag
should be added to, e.g. the id of vocabulary ``'Genre'``
:type vocabulary_id: string
:returns: the newly-created tag
:rtype: dictionary
"""
model = context["model"]
_check_access("tag_create", context, data_dict)
schema = context.get("schema") or ckan.logic.schema.default_create_tag_schema()
_data, errors = _validate(data_dict, schema, context)
if errors:
raise ValidationError(errors)
tag = model_save.tag_dict_save(data_dict, context)
if not context.get("defer_commit"):
model.repo.commit()
log.debug("Created tag '%s' " % tag)
return model_dictize.tag_dictize(tag, context)
def follow_user(context: Context, data_dict: DataDict) -> ActionResult.FollowUser:
"""Start following another user.
You must provide your API key in the Authorization header.
:param id: the id or name of the user to follow, e.g. ``'joeuser'``
:type id: string
:returns: a representation of the 'follower' relationship between yourself
and the other user
:rtype: dictionary
"""
if not context.get("user"):
raise NotAuthorized(_("You must be logged in to follow users"))
model = context["model"]
userobj = model.User.get(context["user"])
if not userobj:
raise NotAuthorized(_("You must be logged in to follow users"))
schema = context.get("schema") or ckan.logic.schema.default_follow_user_schema()
validated_data_dict, errors = _validate(data_dict, schema, context)
if errors:
model.Session.rollback()
raise ValidationError(errors)
# Don't let a user follow herself.
if userobj.id == validated_data_dict["id"]:
message = _("You cannot follow yourself")
raise ValidationError({"message": message})
# Don't let a user follow someone she is already following.
if model.UserFollowingUser.is_following(userobj.id, validated_data_dict["id"]):
followeduserobj = model.User.get(validated_data_dict["id"])
assert followeduserobj
name = followeduserobj.display_name
message = _("You are already following {0}").format(name)
raise ValidationError({"message": message})
follower = model_save.follower_dict_save(
validated_data_dict, context, model.UserFollowingUser
)
if not context.get("defer_commit"):
model.repo.commit()
log.debug(
"User {follower} started following user {object}".format(
follower=follower.follower_id, object=follower.object_id
)
)
return model_dictize.user_following_user_dictize(follower, context)
def follow_dataset(context: Context, data_dict: DataDict) -> ActionResult.FollowDataset:
"""Start following a dataset.
You must provide your API key in the Authorization header.
:param id: the id or name of the dataset to follow, e.g. ``'warandpeace'``
:type id: string
:returns: a representation of the 'follower' relationship between yourself
and the dataset
:rtype: dictionary
"""
if not context.get("user"):
raise NotAuthorized(_("You must be logged in to follow a dataset."))
model = context["model"]
userobj = model.User.get(context["user"])
if not userobj:
raise NotAuthorized(_("You must be logged in to follow a dataset."))
schema = context.get("schema") or ckan.logic.schema.default_follow_dataset_schema()
validated_data_dict, errors = _validate(data_dict, schema, context)
if errors:
model.Session.rollback()
raise ValidationError(errors)
# Don't let a user follow a dataset she is already following.
if model.UserFollowingDataset.is_following(userobj.id, validated_data_dict["id"]):
# FIXME really package model should have this logic and provide
# 'display_name' like users and groups
pkgobj = model.Package.get(validated_data_dict["id"])
assert pkgobj
name = pkgobj.title or pkgobj.name or pkgobj.id
message = _("You are already following {0}").format(name)
raise ValidationError({"message": message})
follower = model_save.follower_dict_save(
validated_data_dict, context, model.UserFollowingDataset
)
if not context.get("defer_commit"):
model.repo.commit()
log.debug(
"User {follower} started following dataset {object}".format(
follower=follower.follower_id, object=follower.object_id
)
)
return model_dictize.user_following_dataset_dictize(follower, context)
def _group_or_org_member_create(
context: Context, data_dict: dict[str, Any], is_org: bool = False
) -> ActionResult.GroupOrOrgMemberCreate:
# creator of group/org becomes an admin
# this needs to be after the repo.commit or else revisions break
model = context["model"]
user = context["user"]
schema = ckan.logic.schema.member_schema()
_data, errors = _validate(data_dict, schema, context)
if errors:
model.Session.rollback()
raise ValidationError(errors)
username = _get_or_bust(data_dict, "username")
role = data_dict.get("role")
group_id = data_dict.get("id")
group = model.Group.get(group_id)
if not group:
msg = _("Organization not found") if is_org else _("Group not found")
raise NotFound(msg)
result = model.User.get(username)
if result:
user_id = result.id
else:
message = _("User {username} does not exist.").format(username=username)
raise ValidationError({"message": message})
member_dict: dict[str, Any] = {
"id": group.id,
"object": user_id,
"object_type": "user",
"capacity": role,
}
member_create_context: Context = {
"user": user,
"ignore_auth": context.get("ignore_auth", False),
}
return logic.get_action("member_create")(member_create_context, member_dict)
def group_member_create(
context: Context, data_dict: DataDict
) -> ActionResult.GroupMemberCreate:
"""Make a user a member of a group.
You must be authorized to edit the group.
:param id: the id or name of the group
:type id: string
:param username: name or id of the user to be made member of the group
:type username: string
:param role: role of the user in the group. One of ``member``, ``editor``,
or ``admin``
:type role: string
:returns: the newly created (or updated) membership
:rtype: dictionary
"""
_check_access("group_member_create", context, data_dict)
return _group_or_org_member_create(context, data_dict)
def organization_member_create(
context: Context, data_dict: DataDict
) -> ActionResult.OrganizationMemberCreate:
"""Make a user a member of an organization.
You must be authorized to edit the organization.
:param id: the id or name of the organization
:type id: string
:param username: name or id of the user to be made member of the
organization
:type username: string
:param role: role of the user in the organization. One of ``member``,
``editor``, or ``admin``
:type role: string
:returns: the newly created (or updated) membership
:rtype: dictionary
"""
_check_access("organization_member_create", context, data_dict)
return _group_or_org_member_create(context, data_dict, is_org=True)
def follow_group(context: Context, data_dict: DataDict) -> ActionResult.FollowGroup:
"""Start following a group.
You must provide your API key in the Authorization header.
:param id: the id or name of the group to follow, e.g. ``'roger'``
:type id: string
:returns: a representation of the 'follower' relationship between yourself
and the group
:rtype: dictionary
"""
if not context.get("user"):
raise NotAuthorized(_("You must be logged in to follow a group."))
model = context["model"]
userobj = model.User.get(context["user"])
if not userobj:
raise NotAuthorized(_("You must be logged in to follow a group."))
schema = context.get("schema", ckan.logic.schema.default_follow_group_schema())
validated_data_dict, errors = _validate(data_dict, schema, context)
if errors:
model.Session.rollback()
raise ValidationError(errors)
# Don't let a user follow a group she is already following.
if model.UserFollowingGroup.is_following(userobj.id, validated_data_dict["id"]):
groupobj = model.Group.get(validated_data_dict["id"])
assert groupobj
name = groupobj.display_name
message = _("You are already following {0}").format(name)
raise ValidationError({"message": message})
follower = model_save.follower_dict_save(
validated_data_dict, context, model.UserFollowingGroup
)
if not context.get("defer_commit"):
model.repo.commit()
log.debug(
"User {follower} started following group {object}".format(
follower=follower.follower_id, object=follower.object_id
)
)
return model_dictize.user_following_group_dictize(follower, context)
def api_token_create(
context: Context, data_dict: DataDict
) -> ActionResult.ApiTokenCreate:
"""Create new API Token for current user.
Apart from the `user` and `name` field that are required by
default implementation, there may be additional fields registered
by extensions.
:param user: name or id of the user who owns new API Token
:type user: string
:param name: distinctive name for API Token
:type name: string
:returns: Returns a dict with the key "token" containing the
encoded token value. Extensions can privide additional
fields via `add_extra` method of
:py:class:`~ckan.plugins.interfaces.IApiToken`
:rtype: dictionary
"""
model = context["model"]
user, name = _get_or_bust(data_dict, ["user", "name"])
if model.User.get(user) is None:
raise NotFound("User not found")
_check_access("api_token_create", context, data_dict)
schema = context.get("schema")
if not schema:
schema = api_token.get_schema()
validated_data_dict, errors = _validate(data_dict, schema, context)
if errors:
raise ValidationError(errors)
token_obj = model_save.api_token_save({"user": user, "name": name}, context)
model.Session.commit()
data = {"jti": token_obj.id, "iat": api_token.into_seconds(token_obj.created_at)}
data = api_token.postprocess(data, token_obj.id, validated_data_dict)
token = api_token.encode(data)
result = api_token.add_extra({"token": token})
return result
|
quodlibet | _init | # Copyright 2012 Christoph Reiter
# 2020 Nick Boultbee
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
import logging
import os
import sys
import warnings
from quodlibet import config
from quodlibet.const import MinVersions
from quodlibet.util import i18n, is_osx, is_windows
from quodlibet.util.dprint import PrintHandler, print_d, print_e
from quodlibet.util.urllib import install_urllib2_ca_file
from senf import fsn2text
from ._main import get_base_dir, get_cache_dir, get_image_dir, is_release
_cli_initialized = False
_initialized = False
def _init_gtk_debug(no_excepthook):
from quodlibet.errorreport import enable_errorhook
enable_errorhook(not no_excepthook)
def is_init():
"""Returns if init() was called"""
global _initialized
return _initialized
def init(no_translations=False, no_excepthook=False, config_file=None):
"""This needs to be called before any API can be used.
Might raise in case of an error.
Pass no_translations=True to disable translations (used by tests)
"""
global _initialized
if _initialized:
return
init_cli(no_translations=no_translations, config_file=config_file)
_init_gtk()
_init_gtk_debug(no_excepthook=no_excepthook)
_init_gst()
_init_dbus()
_initialized = True
def _init_gettext(no_translations=False):
"""Call before using gettext helpers"""
if no_translations:
language = "C"
else:
language = config.gettext("settings", "language")
if language:
print_d(f"Using language in QL settings: {language!r}")
else:
language = None
i18n.init(language)
# Use the locale dir in ../build/share/locale if there is one
localedir = os.path.join(
os.path.dirname(get_base_dir()), "build", "share", "locale"
)
if os.path.isdir(localedir):
print_d(f"Using local locale dir {localedir}")
else:
localedir = None
i18n.register_translation("quodlibet", localedir)
debug_text = os.environ.get("QUODLIBET_TEST_TRANS")
if debug_text is not None:
i18n.set_debug_text(fsn2text(debug_text))
def _init_python():
MinVersions.PYTHON3.check(sys.version_info)
if is_osx():
# We build our own openssl on OSX and need to make sure that
# our own ca file is used in all cases as the non-system openssl
# doesn't use the system certs
install_urllib2_ca_file()
if is_windows():
# Not really needed on Windows as pygi-aio seems to work fine, but
# wine doesn't have certs which we use for testing.
install_urllib2_ca_file()
if is_windows() and os.sep != "\\":
# In the MSYS2 console MSYSTEM is set, which breaks os.sep/os.path.sep
# If you hit this, do a "setup.py clean -all" to get rid of the
# bytecode cache then start things with "MSYSTEM= ..."
raise AssertionError("MSYSTEM is set (%r)" % os.environ.get("MSYSTEM"))
logging.getLogger().addHandler(PrintHandler())
def _init_formats():
from quodlibet.formats import init
init()
def init_cli(no_translations=False, config_file=None):
"""This needs to be called before any API can be used.
Might raise in case of an error.
Like init() but for code not using Gtk etc.
"""
global _cli_initialized
if _cli_initialized:
return
_init_python()
config.init_defaults()
if config_file is not None:
config.init(config_file)
_init_gettext(no_translations)
_init_formats()
_init_g()
_cli_initialized = True
def _init_dbus():
"""Setup dbus mainloop integration. Call before using dbus"""
# To make GDBus fail early and we don't have to wait for a timeout
if is_osx() or is_windows():
os.environ["DBUS_SYSTEM_BUS_ADDRESS"] = "something-invalid"
os.environ["DBUS_SESSION_BUS_ADDRESS"] = "something-invalid"
try:
from dbus.mainloop.glib import DBusGMainLoop, threads_init
except ImportError:
try:
import dbus.glib
dbus.glib
except ImportError:
return
else:
threads_init()
DBusGMainLoop(set_as_default=True)
def _fix_gst_leaks():
"""gst_element_add_pad and gst_bin_add are wrongly annotated and lead
to PyGObject refing the passed element.
Work around by adding a wrapper that unrefs afterwards.
Can be called multiple times.
https://bugzilla.gnome.org/show_bug.cgi?id=741390
https://bugzilla.gnome.org/show_bug.cgi?id=702960
"""
from gi.repository import Gst
assert Gst.is_initialized()
def do_wrap(func):
def wrap(self, obj):
result = func(self, obj)
obj.unref()
return result
return wrap
parent = Gst.Bin()
elm = Gst.Bin()
parent.add(elm)
if elm.__grefcount__ == 3:
elm.unref()
Gst.Bin.add = do_wrap(Gst.Bin.add)
pad = Gst.Pad.new("foo", Gst.PadDirection.SRC)
parent.add_pad(pad)
if pad.__grefcount__ == 3:
pad.unref()
Gst.Element.add_pad = do_wrap(Gst.Element.add_pad)
def _init_g():
"""Call before using GdkPixbuf/GLib/Gio/GObject"""
import gi
gi.require_version("GLib", "2.0")
gi.require_version("Gio", "2.0")
gi.require_version("GObject", "2.0")
gi.require_version("GdkPixbuf", "2.0")
# Newer glib is noisy regarding deprecated signals/properties
# even with stable releases.
if is_release():
warnings.filterwarnings(
"ignore", ".* It will be removed in a future version.", Warning
)
# blacklist some modules, simply loading can cause segfaults
sys.modules["glib"] = None
sys.modules["gobject"] = None
def _init_gtk():
"""Call before using Gtk/Gdk"""
import gi
if (
config.getboolean("settings", "pangocairo_force_fontconfig")
and "PANGOCAIRO_BACKEND" not in os.environ
):
os.environ["PANGOCAIRO_BACKEND"] = "fontconfig"
# disable for consistency and trigger events seem a bit flaky here
if config.getboolean("settings", "scrollbar_always_visible"):
os.environ["GTK_OVERLAY_SCROLLING"] = "0"
try:
# not sure if this is available under Windows
gi.require_version("GdkX11", "3.0")
from gi.repository import GdkX11
GdkX11
except (ValueError, ImportError):
pass
gi.require_version("Gtk", "3.0")
gi.require_version("Gdk", "3.0")
gi.require_version("Pango", "1.0")
gi.require_version("Soup", "3.0")
gi.require_version("PangoCairo", "1.0")
from gi.repository import Gtk
from quodlibet.qltk import ThemeOverrider, gtk_version
# PyGObject doesn't fail anymore when init fails, so do it ourselves
initialized, sys.argv[:] = Gtk.init_check(sys.argv)
if not initialized:
raise SystemExit("Gtk.init failed")
# include our own icon theme directory
theme = Gtk.IconTheme.get_default()
theme_search_path = get_image_dir()
assert os.path.exists(theme_search_path)
theme.append_search_path(theme_search_path)
# Force menu/button image related settings. We might show too many atm
# but this makes sure we don't miss cases where we forgot to force them
# per widget.
# https://bugzilla.gnome.org/show_bug.cgi?id=708676
warnings.filterwarnings("ignore", ".*g_value_get_int.*", Warning)
# some day... but not now
warnings.filterwarnings("ignore", ".*Stock items are deprecated.*", Warning)
warnings.filterwarnings("ignore", ".*:use-stock.*", Warning)
warnings.filterwarnings(
"ignore", r".*The property GtkAlignment:[^\s]+ is deprecated.*", Warning
)
settings = Gtk.Settings.get_default()
with warnings.catch_warnings():
warnings.simplefilter("ignore")
settings.set_property("gtk-button-images", True)
settings.set_property("gtk-menu-images", True)
if hasattr(settings.props, "gtk_primary_button_warps_slider"):
# https://bugzilla.gnome.org/show_bug.cgi?id=737843
settings.set_property("gtk-primary-button-warps-slider", True)
# Make sure PyGObject includes support for foreign cairo structs
try:
gi.require_foreign("cairo")
except ImportError:
print_e("PyGObject is missing cairo support")
sys.exit(1)
css_override = ThemeOverrider()
if sys.platform == "darwin":
# fix duplicated shadows for popups with Gtk+3.14
style_provider = Gtk.CssProvider()
style_provider.load_from_data(
b"""
GtkWindow {
box-shadow: none;
}
.tooltip {
border-radius: 0;
padding: 0;
}
.tooltip.background {
background-clip: border-box;
}
"""
)
css_override.register_provider("", style_provider)
if gtk_version[:2] >= (3, 20):
# https://bugzilla.gnome.org/show_bug.cgi?id=761435
style_provider = Gtk.CssProvider()
style_provider.load_from_data(
b"""
spinbutton, button {
min-height: 22px;
}
.view button {
min-height: 24px;
}
entry {
min-height: 28px;
}
entry.cell {
min-height: 0;
}
"""
)
css_override.register_provider("Adwaita", style_provider)
css_override.register_provider("HighContrast", style_provider)
# https://github.com/quodlibet/quodlibet/issues/2541
style_provider = Gtk.CssProvider()
style_provider.load_from_data(
b"""
treeview.view.separator {
min-height: 2px;
color: @borders;
}
"""
)
css_override.register_provider("Ambiance", style_provider)
css_override.register_provider("Radiance", style_provider)
# https://github.com/quodlibet/quodlibet/issues/2677
css_override.register_provider("Clearlooks-Phenix", style_provider)
# https://github.com/quodlibet/quodlibet/issues/2997
css_override.register_provider("Breeze", style_provider)
if gtk_version[:2] >= (3, 18):
# Hack to get some grab handle like thing for panes
style_provider = Gtk.CssProvider()
style_provider.load_from_data(
b"""
GtkPaned.vertical, paned.vertical >separator {
-gtk-icon-source: -gtk-icontheme("view-more-symbolic");
-gtk-icon-transform: rotate(90deg) scaleX(0.1) scaleY(3);
}
GtkPaned.horizontal, paned.horizontal >separator {
-gtk-icon-source: -gtk-icontheme("view-more-symbolic");
-gtk-icon-transform: rotate(0deg) scaleX(0.1) scaleY(3);
}
"""
)
css_override.register_provider("", style_provider)
# https://bugzilla.gnome.org/show_bug.cgi?id=708676
warnings.filterwarnings("ignore", ".*g_value_get_int.*", Warning)
# blacklist some modules, simply loading can cause segfaults
sys.modules["gtk"] = None
sys.modules["gpod"] = None
sys.modules["gnome"] = None
from quodlibet.qltk import gtk_version, pygobject_version
MinVersions.GTK.check(gtk_version)
MinVersions.PYGOBJECT.check(pygobject_version)
def _init_gst():
"""Call once before importing GStreamer"""
arch_key = "64" if sys.maxsize > 2**32 else "32"
registry_name = "gst-registry-%s-%s.bin" % (sys.platform, arch_key)
os.environ["GST_REGISTRY"] = os.path.join(get_cache_dir(), registry_name)
assert "gi.repository.Gst" not in sys.modules
import gi
# We don't want python-gst, it changes API..
assert "gi.overrides.Gst" not in sys.modules
sys.modules["gi.overrides.Gst"] = None
# blacklist some modules, simply loading can cause segfaults
sys.modules["gst"] = None
# We don't depend on Gst overrides, so make sure it's initialized.
try:
gi.require_version("Gst", "1.0")
from gi.repository import Gst
except (ValueError, ImportError):
return
if Gst.is_initialized():
return
from gi.repository import GLib
try:
ok, sys.argv[:] = Gst.init_check(sys.argv)
except GLib.GError:
print_e("Failed to initialize GStreamer")
# Uninited Gst segfaults: make sure no one can use it
sys.modules["gi.repository.Gst"] = None
else:
# monkey patching ahead
_fix_gst_leaks()
|
comic | tencentbase | #!/usr/bin/env python3
# encoding: utf-8
# http://ac.qq.com或者http://m.ac.qq.com网站的免费漫画的基类,简单提供几个信息实现一个子类即可推送特定的漫画
# Author: insert0003 <https://github.com/insert0003>
import base64
import json
import re
import urlparse
from books.base import BaseComicBook
from bs4 import BeautifulSoup
from lib.autodecoder import AutoDecoder
from lib.urlopener import URLOpener
class TencentBaseBook(BaseComicBook):
accept_domains = ("http://ac.qq.com", "http://m.ac.qq.com")
host = "http://m.ac.qq.com"
feeds = [] # 子类填充此列表[('name', mainurl),...]
# 获取漫画章节列表
def getChapterList(self, url):
decoder = AutoDecoder(isfeed=False)
opener = URLOpener(self.host, timeout=60)
chapterList = []
urlpaths = urlparse.urlsplit(url.lower()).path.split("/")
if ("id" in urlpaths) and (urlpaths.index("id") + 1 < len(urlpaths)):
comic_id = urlpaths[urlpaths.index("id") + 1]
if (not comic_id.isdigit()) or (comic_id == ""):
self.log.warn("can not get comic id: %s" % url)
return chapterList
url = "https://m.ac.qq.com/comic/chapterList/id/{}".format(comic_id)
result = opener.open(url)
if result.status_code != 200 or not result.content:
self.log.warn("fetch comic page failed: %s" % url)
return chapterList
content = self.AutoDecodeContent(
result.content, decoder, self.feed_encoding, opener.realurl, result.headers
)
soup = BeautifulSoup(content, "html.parser")
# <section class="chapter-list-box list-expanded" data-vip-free="1">
section = soup.find("section", {"class": "chapter-list-box list-expanded"})
if section is None:
self.log.warn("chapter-list-box is not exist.")
return chapterList
# <ul class="chapter-list normal">
# <ul class="chapter-list reverse">
reverse_list = section.find("ul", {"class": "chapter-list reverse"})
if reverse_list is None:
self.log.warn("chapter-list is not exist.")
return chapterList
for item in reverse_list.find_all("a"):
# <a class="chapter-link lock" data-cid="447" data-seq="360" href="/chapter/index/id/531490/cid/447">360</a>
# https://m.ac.qq.com/chapter/index/id/511915/cid/1
href = "https://m.ac.qq.com" + item.get("href")
isVip = "lock" in item.get("class")
if isVip == True:
self.log.info("Chapter {} is Vip, waiting for free.".format(href))
continue
chapterList.append((item.get_text(), href))
return chapterList
# 获取漫画图片列表
def getImgList(self, url):
decoder = AutoDecoder(isfeed=False)
opener = URLOpener(self.host, timeout=60)
imgList = []
result = opener.open(url)
if result.status_code != 200 or not result.content:
self.log.warn("fetch comic page failed: %s" % url)
return imgList
content = result.content
cid_page = self.AutoDecodeContent(
content, decoder, self.page_encoding, opener.realurl, result.headers
)
filter_result = re.findall(r"data\s*:\s*'(.+?)'", cid_page)
# "picture": [{},...{}]}
if len(filter_result) != 0:
# "picture" > InBpY3R1cmUi
# picture": > cGljdHVyZSI6
# icture":[ > aWN0dXJlIjpb
if "InBpY3R1cmUi" in filter_result[0]:
base64data = filter_result[0].split("InBpY3R1cmUi")[1]
self.log.warn("found flag string: %s" % "InBpY3R1cmUi")
elif "cGljdHVyZSI6" in filter_result[0]:
base64data = filter_result[0].split("cGljdHVyZSI6")[1]
self.log.warn("found flag string: %s" % "cGljdHVyZSI6")
elif "aWN0dXJlIjpb" in filter_result[0]:
base64data = filter_result[0].split("aWN0dXJl")[1]
self.log.warn("found flag string: %s" % "aWN0dXJlIjpb")
else:
self.log.warn(
"can not found flag string in data: %s" % filter_result[0]
)
return imgList
decodeData = base64.decodestring(base64data)
startIndex = decodeData.find("[")
endIndex = decodeData.find("]")
if startIndex > -1 and endIndex > -1:
img_detail_json = json.loads(decodeData[startIndex : endIndex + 1])
for img_url in img_detail_json:
if "url" in img_url:
imgList.append(img_url["url"])
else:
self.log.warn("no url in img_url:%s" % img_url)
else:
self.log.warn("can not found [] in decodeData:%s" % decodeData)
else:
self.log.warn("can not fount filter_result with data: .")
return imgList
|
extractor | baidu | # coding: utf-8
from __future__ import unicode_literals
import re
from ..utils import unescapeHTML
from .common import InfoExtractor
class BaiduVideoIE(InfoExtractor):
IE_DESC = "百度视频"
_VALID_URL = r"https?://v\.baidu\.com/(?P<type>[a-z]+)/(?P<id>\d+)\.htm"
_TESTS = [
{
"url": "http://v.baidu.com/comic/1069.htm?frp=bdbrand&q=%E4%B8%AD%E5%8D%8E%E5%B0%8F%E5%BD%93%E5%AE%B6",
"info_dict": {
"id": "1069",
"title": "中华小当家 TV版国语",
"description": "md5:51be07afe461cf99fa61231421b5397c",
},
"playlist_count": 52,
},
{
"url": "http://v.baidu.com/show/11595.htm?frp=bdbrand",
"info_dict": {
"id": "11595",
"title": "re:^奔跑吧兄弟",
"description": "md5:1bf88bad6d850930f542d51547c089b8",
},
"playlist_mincount": 12,
},
]
def _call_api(self, path, category, playlist_id, note):
return self._download_json(
"http://app.video.baidu.com/%s/?worktype=adnative%s&id=%s"
% (path, category, playlist_id),
playlist_id,
note,
)
def _real_extract(self, url):
category, playlist_id = re.match(self._VALID_URL, url).groups()
if category == "show":
category = "tvshow"
if category == "tv":
category = "tvplay"
playlist_detail = self._call_api(
"xqinfo", category, playlist_id, "Download playlist JSON metadata"
)
playlist_title = playlist_detail["title"]
playlist_description = unescapeHTML(playlist_detail.get("intro"))
episodes_detail = self._call_api(
"xqsingle", category, playlist_id, "Download episodes JSON metadata"
)
entries = [
self.url_result(episode["url"], video_title=episode["title"])
for episode in episodes_detail["videos"]
]
return self.playlist_result(
entries, playlist_id, playlist_title, playlist_description
)
|
Points | Init | # ***************************************************************************
# * Copyright (c) 2004,2005 Juergen Riegel <juergen.riegel@web.de> *
# * *
# * This file is part of the FreeCAD CAx development system. *
# * *
# * This program is free software; you can redistribute it and/or modify *
# * it under the terms of the GNU Lesser General Public License (LGPL) *
# * as published by the Free Software Foundation; either version 2 of *
# * the License, or (at your option) any later version. *
# * for detail see the LICENCE text file. *
# * *
# * FreeCAD is distributed in the hope that it will be useful, *
# * but WITHOUT ANY WARRANTY; without even the implied warranty of *
# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
# * GNU Lesser General Public License for more details. *
# * *
# * You should have received a copy of the GNU Library General Public *
# * License along with FreeCAD; if not, write to the Free Software *
# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
# * USA *
# * *
# ***************************************************************************/
# FreeCAD init script of the Points module
# Append the open handler
FreeCAD.addImportType("Point formats (*.asc *.pcd *.ply *.e57)", "Points")
FreeCAD.addExportType("Point formats (*.asc *.pcd *.ply)", "Points")
|
pwidgets | ctxmenu | # -*- coding: utf-8 -*-
#
# Copyright (C) 2018 by Ihor E. Novikov
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
import wal
from sk1 import config
STUB = [wal.ID_NEW, wal.ID_OPEN]
class ContextMenu(wal.Menu):
app = None
mw = None
insp = None
actions = None
entries = None
items = []
def __init__(self, app, parent, entries=None):
self.app = app
self.mw = app.mw
self.parent = parent
self.insp = self.app.insp
self.actions = self.app.actions
self.entries = entries or STUB
wal.Menu.__init__(self)
self.build_menu(self.entries)
self.items = []
def destroy(self):
items = self.__dict__.keys()
for item in items:
self.__dict__[item] = None
def rebuild(self):
self.build_menu(self.get_entries())
def build_menu(self, entries):
for item in self.items:
self.remove_item(item)
self.items = []
for item in entries:
if item is None:
self.items.append(self.append_separator())
else:
action = self.app.actions[item]
menuitem = ActionMenuItem(self.parent, self, action)
self.append_item(menuitem)
menuitem.update()
self.items.append(menuitem)
def get_entries(self):
return self.entries
class ActionMenuItem(wal.MenuItem):
def __init__(self, mw, parent, action):
self.mw = mw
self.parent = parent
self.action = action
action_id = action.action_id
text = action.get_menu_text()
if action.is_acc:
text += "\t" + action.get_shortcut_text()
wal.MenuItem.__init__(
self, parent, action_id, text=text, checkable=action.is_toggle()
)
if action.is_icon and not action.is_toggle():
self.set_bitmap(action.get_icon(config.menu_size, wal.ART_MENU))
action.register_as_menuitem(self)
self.bind_to(self.mw, action, action_id)
# For WX<4
if action.is_toggle():
self.set_checkable(True)
def update(self):
self.set_enable(self.action.enabled)
if self.action.is_toggle():
self.set_active(self.action.active)
|
internal | update_warnings | import json
from contextlib import nullcontext, suppress
from datetime import datetime, timedelta
from pathlib import Path
from typing import Any, Callable, Optional
import httpie
import requests
from httpie.context import Environment, LogLevel
from httpie.internal.__build_channel__ import BUILD_CHANNEL
from httpie.internal.daemons import spawn_daemon
from httpie.utils import is_version_greater, open_with_lockfile
# Automatically updated package version index.
PACKAGE_INDEX_LINK = "https://packages.httpie.io/latest.json"
FETCH_INTERVAL = timedelta(weeks=2)
WARN_INTERVAL = timedelta(weeks=1)
UPDATE_MESSAGE_FORMAT = """\
A new HTTPie release ({last_released_version}) is available.
To see how you can update, please visit https://httpie.io/docs/cli/{installation_method}
"""
ALREADY_UP_TO_DATE_MESSAGE = """\
You are already up-to-date.
"""
def _read_data_error_free(file: Path) -> Any:
# If the file is broken / non-existent, ignore it.
try:
with open(file) as stream:
return json.load(stream)
except (ValueError, OSError):
return {}
def _fetch_updates(env: Environment) -> str:
file = env.config.version_info_file
data = _read_data_error_free(file)
response = requests.get(PACKAGE_INDEX_LINK, verify=False)
response.raise_for_status()
data.setdefault("last_warned_date", None)
data["last_fetched_date"] = datetime.now().isoformat()
data["last_released_versions"] = response.json()
with open_with_lockfile(file, "w") as stream:
json.dump(data, stream)
def fetch_updates(env: Environment, lazy: bool = True):
if lazy:
spawn_daemon("fetch_updates")
else:
_fetch_updates(env)
def maybe_fetch_updates(env: Environment) -> None:
if env.config.get("disable_update_warnings"):
return None
data = _read_data_error_free(env.config.version_info_file)
if data:
current_date = datetime.now()
last_fetched_date = datetime.fromisoformat(data["last_fetched_date"])
earliest_fetch_date = last_fetched_date + FETCH_INTERVAL
if current_date < earliest_fetch_date:
return None
fetch_updates(env)
def _get_suppress_context(env: Environment) -> Any:
"""Return a context manager that suppress
all possible errors.
Note: if you have set the developer_mode=True in
your config, then it will show all errors for easier
debugging."""
if env.config.developer_mode:
return nullcontext()
else:
return suppress(BaseException)
def _update_checker(
func: Callable[[Environment], None]
) -> Callable[[Environment], None]:
"""Control the execution of the update checker (suppress errors, trigger
auto updates etc.)"""
def wrapper(env: Environment) -> None:
with _get_suppress_context(env):
func(env)
with _get_suppress_context(env):
maybe_fetch_updates(env)
return wrapper
def _get_update_status(env: Environment) -> Optional[str]:
"""If there is a new update available, return the warning text.
Otherwise just return None."""
file = env.config.version_info_file
if not file.exists():
return None
with _get_suppress_context(env):
# If the user quickly spawns multiple httpie processes
# we don't want to end in a race.
with open_with_lockfile(file) as stream:
version_info = json.load(stream)
available_channels = version_info["last_released_versions"]
if BUILD_CHANNEL not in available_channels:
return None
current_version = httpie.__version__
last_released_version = available_channels[BUILD_CHANNEL]
if not is_version_greater(last_released_version, current_version):
return None
text = UPDATE_MESSAGE_FORMAT.format(
last_released_version=last_released_version,
installation_method=BUILD_CHANNEL,
)
return text
def get_update_status(env: Environment) -> str:
return _get_update_status(env) or ALREADY_UP_TO_DATE_MESSAGE
@_update_checker
def check_updates(env: Environment) -> None:
if env.config.get("disable_update_warnings"):
return None
file = env.config.version_info_file
update_status = _get_update_status(env)
if not update_status:
return None
# If the user quickly spawns multiple httpie processes
# we don't want to end in a race.
with open_with_lockfile(file) as stream:
version_info = json.load(stream)
# We don't want to spam the user with too many warnings,
# so we'll only warn every once a while (WARN_INTERNAL).
current_date = datetime.now()
last_warned_date = version_info["last_warned_date"]
if last_warned_date is not None:
earliest_warn_date = datetime.fromisoformat(last_warned_date) + WARN_INTERVAL
if current_date < earliest_warn_date:
return None
env.log_error(update_status, level=LogLevel.INFO)
version_info["last_warned_date"] = current_date.isoformat()
with open_with_lockfile(file, "w") as stream:
json.dump(version_info, stream)
|
gui | properties_window | from __future__ import absolute_import
import grp
import locale
import os
import pwd
import time
from gi.repository import Gdk, Gio, GObject, Gtk, Pango
from sunflower import common
from sunflower.plugin_base.monitor import MonitorSignals
from sunflower.plugin_base.provider import Support
class Column:
SELECTED = 0
ICON_NAME = 1
APPLICATION_NAME = 2
APPLICATION_ID = 3
class EmblemColumn:
SELECTED = 0
NAME = 1
ICON_NAME = 2
class PropertiesWindow(Gtk.Window):
"""Properties window for files and directories"""
def __init__(self, application, provider, path):
Gtk.Window.__init__(self)
# store parameters locally
self._application = application
self._provider = provider
self._path = path
self._is_file = self._provider.is_file(self._path)
self._permission_updating = False
self._mode = None
# get content type
if self._provider.is_dir(self._path):
self._mime_type = "inode/directory"
else:
self._mime_type = application.associations_manager.get_mime_type(self._path)
# content type is unknown, try to detect using content
if application.associations_manager.is_mime_type_unknown(self._mime_type):
data = application.associations_manager.get_sample_data(path, provider)
self._mime_type = application.associations_manager.get_mime_type(
data=data
)
# file monitor, we'd like to update info if file changes
self._create_monitor()
# get item information
title = _('"{0}" Properties').format(os.path.basename(path))
icon_manager = application.icon_manager
if self._is_file:
# get icon for specified file
self._icon_name = icon_manager.get_icon_for_file(path)
else:
# get folder icon
self._icon_name = icon_manager.get_icon_for_directory(path)
# configure window
self.set_title(title)
hints = Gdk.Geometry()
hints.min_width = 410
hints.min_height = 410
self.set_geometry_hints(None, hints, Gdk.WindowHints.MIN_SIZE)
self.set_position(Gtk.WindowPosition.CENTER_ON_PARENT)
self.set_icon_name(self._icon_name)
self.connect("key-press-event", self._handle_key_press)
# create notebook
self._notebook = Gtk.Notebook.new()
self._notebook.append_page(
self._create_basic_tab(), Gtk.Label(label=_("Basic"))
)
self._notebook.append_page(
self._create_permissions_tab(), Gtk.Label(label=_("Permissions"))
)
self._notebook.append_page(
self._create_open_with_tab(), Gtk.Label(label=_("Open With"))
)
self._notebook.append_page(
self._create_emblems_tab(), Gtk.Label(label=_("Emblems"))
)
self.add(self._notebook)
# update widgets to represent item state
self._update_data()
# show all widgets
self.show_all()
def _close_window(self, widget=None, data=None):
"""Close properties window"""
self._monitor.cancel()
self.destroy()
def _item_changes(self, monitor, file, other_file, event, data=None):
"""Event triggered when monitored file changes"""
if event is Gio.FileMonitorEvent.DELETED:
# item was removed, close dialog
self.destroy()
elif event is Gio.FileMonitorEvent.MOVED:
# item was moved/renamed - probably within same file system but not necessarily within same directory - close dialog
self.destroy()
else:
# item was changed, update data
self._update_data()
def _rename_item(self, widget=None, data=None):
"""Handle renaming item"""
item_exists = self._provider.exists(
self._entry_name.get_text(), relative_to=os.path.dirname(self._path)
)
if item_exists:
# item with the same name already exists
dialog = Gtk.MessageDialog(
self,
Gtk.DialogFlags.DESTROY_WITH_PARENT,
Gtk.MessageType.ERROR,
Gtk.ButtonsType.OK,
_(
"File or directory with specified name already "
"exists in current directory. Item could not "
"be renamed."
),
)
dialog.run()
dialog.destroy()
# restore old name
self._entry_name.set_text(os.path.basename(self._path))
else:
# rename item
try:
self._provider.rename_path(
os.path.basename(self._path), self._entry_name.get_text()
)
self._path = os.path.join(
os.path.dirname(self._path), self._entry_name.get_text()
)
# recreate item monitor
self._create_monitor()
except IOError as error:
# problem renaming item
dialog = Gtk.MessageDialog(
self,
Gtk.DialogFlags.DESTROY_WITH_PARENT,
Gtk.MessageType.ERROR,
Gtk.ButtonsType.OK,
_(
"Error renaming specified item. Make sure "
"you have enough permissions."
)
+ "\n\n{0}".format(error),
)
dialog.run()
dialog.destroy()
def _create_monitor(self):
"""Create item monitor"""
path = common.encode_file_name(self._path)
self._monitor = Gio.File.new_for_path(path).monitor(
Gio.FileMonitorFlags.SEND_MOVED
)
self._monitor.connect("changed", self._item_changes)
def _load_associated_applications(self):
"""Get associated applications with file/directory"""
associations_manager = self._application.associations_manager
application_list = associations_manager.get_application_list_for_type(
self._mime_type
)
default_application = associations_manager.get_default_application_for_type(
self._mime_type
)
# clear existing list
self._store.clear()
# add all applications to the list
for application in application_list:
self._store.append(
(
application.id == default_application.id,
application.icon,
application.name,
application.id,
)
)
def _update_data(self):
"""Update widgets to represent item state"""
associations_manager = self._application.associations_manager
# get the rest of the information
description = associations_manager.get_mime_description(self._mime_type)
time_format = self._application.options.section("item_list").get("time_format")
size_format = self._application.options.get("size_format")
item_stat = self._provider.get_stat(self._path, extended=True)
# get item size
if self._is_file:
# file size
item_size = common.format_size(item_stat.size, size_format)
else:
# directory size
try:
dir_size = len(self._provider.list_dir(self._path))
except OSError:
dir_size = 0
finally:
item_size = "{0} {1}".format(
locale.format("%d", dir_size, True),
ngettext("item", "items", dir_size),
)
# set mode
self._mode = item_stat.mode
# time_format item time
item_a_date = time.strftime(time_format, time.localtime(item_stat.time_access))
item_m_date = time.strftime(time_format, time.localtime(item_stat.time_modify))
# get volume
try:
mount = Gio.File.new_for_commandline_arg(self._path).find_enclosing_mount()
volume_name = mount.get_name()
except Exception:
# item is not on any known volume
volume_name = _("unknown")
# update widgets
self._entry_name.set_text(os.path.basename(self._path))
self._label_type.set_text("{0}\n{1}".format(description, self._mime_type))
self._label_size.set_text(item_size)
self._label_location.set_text(os.path.dirname(self._path))
self._label_volume.set_text(volume_name)
self._label_accessed.set_text(item_a_date)
self._label_modified.set_text(item_m_date)
# update permissions list
self._permission_update_mode(initial_update=True)
# update ownership
self._ownership_update()
# update "open with" list
self._load_associated_applications()
def _permission_update_octal(self, widget, data=None):
"""Update octal entry box"""
if self._permission_updating:
return
data = int(str(data), 8)
self._mode += (-1, 1)[widget.get_active()] * data
self._permission_update_mode()
def _permission_update_checkboxes(self, widget=None, data=None):
"""Update checkboxes accordingly"""
self._permission_updating = True
self._permission_owner_read.set_active(self._mode & 0b100000000)
self._permission_owner_write.set_active(self._mode & 0b010000000)
self._permission_owner_execute.set_active(self._mode & 0b001000000)
self._permission_group_read.set_active(self._mode & 0b000100000)
self._permission_group_write.set_active(self._mode & 0b000010000)
self._permission_group_execute.set_active(self._mode & 0b000001000)
self._permission_others_read.set_active(self._mode & 0b000000100)
self._permission_others_write.set_active(self._mode & 0b000000010)
self._permission_others_execute.set_active(self._mode & 0b000000001)
self._permission_updating = False
def _permission_entry_activate(self, widget, data=None):
"""Handle octal mode change"""
self._mode = int(widget.get_text(), 8)
self._permission_update_mode()
def _permission_update_mode(self, initial_update=False):
"""Update widgets"""
self._permission_octal_entry.set_text("{0}".format(oct(self._mode)))
self._permission_update_checkboxes()
# set file mode
if not initial_update:
self._provider.set_mode(self._path, self._mode)
def _ownership_update(self):
"""Update owner and group"""
stat = self._provider.get_stat(self._path)
self._combobox_owner.handler_block_by_func(self._ownership_changed)
self._combobox_group.handler_block_by_func(self._ownership_changed)
# remove old entries
self._list_owner.clear()
self._list_group.clear()
# for local file system fill comboboxes with available user and group names
if self._provider.is_local:
for i, user in enumerate(pwd.getpwall()):
self._list_owner.append((user.pw_name, user.pw_uid))
if user.pw_uid == stat.user_id:
self._combobox_owner.set_active(i)
for i, group in enumerate(grp.getgrall()):
self._list_group.append((group.gr_name, group.gr_gid))
if group.gr_gid == stat.group_id:
self._combobox_group.set_active(i)
# for remote file systems simply set owner and group
else:
self._list_owner.append((str(stat.user_id), stat.user_id))
self._list_group.append((str(stat.group_id), stat.group_id))
self._combobox_owner.set_active(0)
self._combobox_group.set_active(0)
self._combobox_owner.handler_unblock_by_func(self._ownership_changed)
self._combobox_group.handler_unblock_by_func(self._ownership_changed)
def _ownership_changed(self, widget, data=None):
"""Handle changing owner or group"""
# get new owner and group
owner_iter = self._combobox_owner.get_active_iter()
group_iter = self._combobox_group.get_active_iter()
owner_id = self._list_owner.get_value(owner_iter, 1)
group_id = self._list_group.get_value(group_iter, 1)
# save new owner and group
try:
self._provider.set_owner(self._path, owner_id, group_id)
except OSError as error:
dialog = Gtk.MessageDialog(
self,
Gtk.DialogFlags.DESTROY_WITH_PARENT,
Gtk.MessageType.ERROR,
Gtk.ButtonsType.OK,
_("Error changing owner or group") + "\n\n{0}".format(error),
)
dialog.run()
dialog.destroy()
self._ownership_update()
def _change_default_application(self, renderer, path, data=None):
"""Handle changing default application"""
active_item = self._store[path]
application_id = active_item[Column.APPLICATION_ID]
associations_manager = self._application.associations_manager
# set default application for mime type
application_set = associations_manager.set_default_application_for_type(
self._mime_type, application_id
)
# select active item
if application_set:
for item in self._store:
item[Column.SELECTED] = item.path == active_item.path
return True
def _toggle_emblem(self, renderer, path, data=None):
"""Handle toggling emblem selection"""
active_item = self._emblems_store.get_iter(path)
is_selected = not self._emblems_store.get_value(
active_item, EmblemColumn.SELECTED
)
emblem = self._emblems_store.get_value(active_item, EmblemColumn.NAME)
# modify value in list store
self._emblems_store.set_value(active_item, EmblemColumn.SELECTED, is_selected)
# update emblem database
update_method = (
self._application.emblem_manager.remove_emblem,
self._application.emblem_manager.add_emblem,
)[is_selected]
path, item_name = os.path.split(self._path)
update_method(path, item_name, emblem)
# notify monitor of our change
parent = self._provider.get_parent()
parent_path = self._provider.get_path()
if parent_path == self._provider.get_root_path(parent_path):
item_path = self._path[len(parent_path) :]
else:
item_path = self._path[len(parent_path) + 1 :]
queue = parent.get_monitor().get_queue()
queue.put((MonitorSignals.EMBLEM_CHANGED, item_path, None))
return True
def _create_basic_tab(self):
"""Create tab containing basic information"""
tab = Gtk.VBox(False, 0)
table = Gtk.Table(7, 3)
# configure table
tab.set_border_width(10)
# create icon
icon = Gtk.Image()
icon.set_from_icon_name(self._icon_name, Gtk.IconSize.DIALOG)
vbox_icon = Gtk.VBox(False, 0)
vbox_icon.pack_start(icon, False, False, 0)
table.attach(vbox_icon, 0, 1, 0, 7, Gtk.AttachOptions.SHRINK)
# labels
label_name = Gtk.Label(label=_("Name:"))
label_type = Gtk.Label(label=_("Type:"))
label_size = Gtk.Label(label=_("Size:"))
label_location = Gtk.Label(label=_("Location:"))
label_volume = Gtk.Label(label=_("Volume:"))
label_accessed = Gtk.Label(label=_("Accessed:"))
label_modified = Gtk.Label(label=_("Modified:"))
# configure labels
label_name.set_alignment(0, 0.5)
label_type.set_alignment(0, 0)
label_size.set_alignment(0, 0)
label_location.set_alignment(0, 0)
label_volume.set_alignment(0, 0)
label_accessed.set_alignment(0, 0)
label_modified.set_alignment(0, 0)
# pack labels
table.attach(label_name, 1, 2, 0, 1)
table.attach(label_type, 1, 2, 1, 2)
table.attach(label_size, 1, 2, 2, 3)
table.attach(label_location, 1, 2, 3, 4)
table.attach(label_volume, 1, 2, 4, 5)
table.attach(label_accessed, 1, 2, 5, 6)
table.attach(label_modified, 1, 2, 6, 7)
# value containers
self._entry_name = Gtk.Entry()
self._label_type = Gtk.Label()
self._label_size = Gtk.Label()
self._label_location = Gtk.Label()
self._label_volume = Gtk.Label()
self._label_accessed = Gtk.Label()
self._label_modified = Gtk.Label()
# configure labels
self._label_type.set_alignment(0, 0)
self._label_type.set_selectable(True)
self._label_size.set_alignment(0, 0)
self._label_size.set_selectable(True)
self._label_location.set_alignment(0, 0)
self._label_location.set_selectable(True)
self._label_location.set_ellipsize(Pango.EllipsizeMode.MIDDLE)
self._label_volume.set_alignment(0, 0)
self._label_volume.set_selectable(True)
self._label_accessed.set_alignment(0, 0)
self._label_accessed.set_selectable(True)
self._label_modified.set_alignment(0, 0)
self._label_modified.set_selectable(True)
# pack value containers
table.attach(self._entry_name, 2, 3, 0, 1)
table.attach(self._label_type, 2, 3, 1, 2)
table.attach(self._label_size, 2, 3, 2, 3)
table.attach(self._label_location, 2, 3, 3, 4)
table.attach(self._label_volume, 2, 3, 4, 5)
table.attach(self._label_accessed, 2, 3, 5, 6)
table.attach(self._label_modified, 2, 3, 6, 7)
# connect events
self._entry_name.connect("activate", self._rename_item)
# configure table
table.set_row_spacings(5)
table.set_row_spacing(2, 30)
table.set_row_spacing(4, 30)
table.set_col_spacing(0, 10)
table.set_col_spacing(1, 10)
# pack table
tab.pack_start(table, False, False, 0)
return tab
def _create_permissions_tab(self):
"""Create tab containing item permissions and ownership"""
tab = Gtk.VBox(False, 5)
tab.set_border_width(10)
# create 'Access' frame
frame_access = Gtk.Frame()
frame_access.set_label(_("Access"))
table_access = Gtk.Table(4, 4, False)
table_access.set_border_width(5)
# create widgets
label = Gtk.Label(label=_("User:"))
label.set_alignment(0, 0.5)
table_access.attach(label, 0, 1, 0, 1)
label = Gtk.Label(label=_("Group:"))
label.set_alignment(0, 0.5)
table_access.attach(label, 0, 1, 1, 2)
label = Gtk.Label(label=_("Others:"))
label.set_alignment(0, 0.5)
table_access.attach(label, 0, 1, 2, 3)
# owner checkboxes
self._permission_owner_read = Gtk.CheckButton(_("Read"))
self._permission_owner_read.connect(
"toggled", self._permission_update_octal, (1 << 2) * 100
)
table_access.attach(self._permission_owner_read, 1, 2, 0, 1)
self._permission_owner_write = Gtk.CheckButton(_("Write"))
self._permission_owner_write.connect(
"toggled", self._permission_update_octal, (1 << 1) * 100
)
table_access.attach(self._permission_owner_write, 2, 3, 0, 1)
self._permission_owner_execute = Gtk.CheckButton(_("Execute"))
self._permission_owner_execute.connect(
"toggled", self._permission_update_octal, (1 << 0) * 100
)
table_access.attach(self._permission_owner_execute, 3, 4, 0, 1)
# group checkboxes
self._permission_group_read = Gtk.CheckButton(_("Read"))
self._permission_group_read.connect(
"toggled", self._permission_update_octal, (1 << 2) * 10
)
table_access.attach(self._permission_group_read, 1, 2, 1, 2)
self._permission_group_write = Gtk.CheckButton(_("Write"))
self._permission_group_write.connect(
"toggled", self._permission_update_octal, (1 << 1) * 10
)
table_access.attach(self._permission_group_write, 2, 3, 1, 2)
self._permission_group_execute = Gtk.CheckButton(_("Execute"))
self._permission_group_execute.connect(
"toggled", self._permission_update_octal, (1 << 0) * 10
)
table_access.attach(self._permission_group_execute, 3, 4, 1, 2)
# others checkboxes
self._permission_others_read = Gtk.CheckButton(_("Read"))
self._permission_others_read.connect(
"toggled", self._permission_update_octal, (1 << 2)
)
table_access.attach(self._permission_others_read, 1, 2, 2, 3)
self._permission_others_write = Gtk.CheckButton(_("Write"))
self._permission_others_write.connect(
"toggled", self._permission_update_octal, (1 << 1)
)
table_access.attach(self._permission_others_write, 2, 3, 2, 3)
self._permission_others_execute = Gtk.CheckButton(_("Execute"))
self._permission_others_execute.connect(
"toggled", self._permission_update_octal, (1 << 0)
)
table_access.attach(self._permission_others_execute, 3, 4, 2, 3)
# octal representation
label = Gtk.Label(label=_("Octal:"))
label.set_alignment(0, 0.5)
table_access.attach(label, 0, 1, 3, 4)
self._permission_octal_entry = Gtk.Entry()
self._permission_octal_entry.set_width_chars(5)
self._permission_octal_entry.connect(
"activate", self._permission_entry_activate
)
table_access.attach(self._permission_octal_entry, 1, 2, 3, 4)
table_access.set_row_spacing(2, 10)
# create ownership frame
frame_ownership = Gtk.Frame()
frame_ownership.set_label(_("Ownership"))
table_ownership = Gtk.Table(2, 2, False)
table_ownership.set_border_width(5)
# create widgets
label = Gtk.Label(label=_("User:"))
label.set_alignment(0, 0.5)
table_ownership.attach(label, 0, 1, 0, 1)
label = Gtk.Label(label=_("Group:"))
label.set_alignment(0, 0.5)
table_ownership.attach(label, 0, 1, 1, 2)
# create owner combobox
self._list_owner = Gtk.ListStore(str, GObject.TYPE_INT64)
cell_owner = Gtk.CellRendererText()
self._combobox_owner = Gtk.ComboBox.new_with_model(self._list_owner)
self._combobox_owner.connect("changed", self._ownership_changed)
self._combobox_owner.pack_start(cell_owner, True)
self._combobox_owner.add_attribute(cell_owner, "text", 0)
table_ownership.attach(self._combobox_owner, 1, 2, 0, 1)
# create group combobox
self._list_group = Gtk.ListStore(str, GObject.TYPE_INT64)
cell_group = Gtk.CellRendererText()
self._combobox_group = Gtk.ComboBox.new_with_model(self._list_group)
self._combobox_group.connect("changed", self._ownership_changed)
self._combobox_group.pack_start(cell_group, True)
self._combobox_group.add_attribute(cell_group, "text", 0)
table_ownership.attach(self._combobox_group, 1, 2, 1, 2)
# make controls insensitive if provider doesn't support them
supported_features = self._provider.get_support()
if Support.SET_OWNER not in supported_features:
self._combobox_owner.set_sensitive(False)
self._combobox_group.set_sensitive(False)
if Support.SET_ACCESS not in supported_features:
self._permission_owner_read.set_sensitive(False)
self._permission_owner_write.set_sensitive(False)
self._permission_owner_execute.set_sensitive(False)
self._permission_group_read.set_sensitive(False)
self._permission_group_write.set_sensitive(False)
self._permission_group_execute.set_sensitive(False)
self._permission_others_read.set_sensitive(False)
self._permission_others_write.set_sensitive(False)
self._permission_others_execute.set_sensitive(False)
self._permission_octal_entry.set_sensitive(False)
# pack interface
frame_access.add(table_access)
frame_ownership.add(table_ownership)
tab.pack_start(frame_access, False, False, 0)
tab.pack_start(frame_ownership, False, False, 0)
return tab
def _create_open_with_tab(self):
"""Create tab containing list of applications that can open this file"""
tab = Gtk.VBox(False, 5)
tab.set_border_width(10)
# get item description
description = self._application.associations_manager.get_mime_description(
self._mime_type
)
# create label
text = _(
"Select an application to open <i>{0}</i> and " 'other files of type "{1}"'
).format(os.path.basename(self._path).replace("&", "&"), description)
label = Gtk.Label(label=text)
label.set_alignment(0, 0)
label.set_line_wrap(True)
label.set_use_markup(True)
# create application list
container = Gtk.ScrolledWindow()
container.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
container.set_shadow_type(Gtk.ShadowType.IN)
self._store = Gtk.ListStore(bool, str, str, str)
self._list = Gtk.TreeView()
self._list.set_model(self._store)
self._list.set_headers_visible(False)
cell_radio = Gtk.CellRendererToggle()
cell_radio.set_radio(True)
cell_radio.connect("toggled", self._change_default_application)
cell_icon = Gtk.CellRendererPixbuf()
cell_name = Gtk.CellRendererText()
# create column_name
column_radio = Gtk.TreeViewColumn()
column_name = Gtk.TreeViewColumn()
# pack renderer
column_radio.pack_start(cell_radio, False)
column_name.pack_start(cell_icon, False)
column_name.pack_start(cell_name, True)
# configure renderer
column_radio.add_attribute(cell_radio, "active", Column.SELECTED)
column_name.add_attribute(cell_icon, "icon-name", Column.ICON_NAME)
column_name.add_attribute(cell_name, "text", Column.APPLICATION_NAME)
# add column_name to the list
self._list.append_column(column_radio)
self._list.append_column(column_name)
container.add(self._list)
tab.pack_start(label, False, False, 0)
tab.pack_start(container, True, True, 0)
return tab
def _create_emblems_tab(self):
"""Create tab for editing emblems"""
tab = Gtk.VBox(False, 5)
tab.set_border_width(10)
# create scrollable container
container = Gtk.ScrolledWindow()
container.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC)
container.set_shadow_type(Gtk.ShadowType.IN)
# create list
self._emblems_store = Gtk.ListStore(bool, str, str)
self._emblems = Gtk.TreeView(model=self._emblems_store)
cell_selected = Gtk.CellRendererToggle()
cell_icon = Gtk.CellRendererPixbuf()
cell_name = Gtk.CellRendererText()
cell_selected.connect("toggled", self._toggle_emblem)
column_name = Gtk.TreeViewColumn()
column_name.pack_start(cell_selected, False)
column_name.pack_start(cell_icon, False)
column_name.pack_start(cell_name, True)
column_name.add_attribute(cell_selected, "active", EmblemColumn.SELECTED)
column_name.add_attribute(cell_icon, "icon-name", EmblemColumn.ICON_NAME)
column_name.add_attribute(cell_name, "text", EmblemColumn.NAME)
self._emblems.set_headers_visible(False)
self._emblems.set_search_column(EmblemColumn.NAME)
self._emblems.append_column(column_name)
# set search function
compare = (
lambda model, column, key, iter_: key.lower()
not in model.get_value(iter_, column).lower()
)
self._emblems.set_search_equal_func(compare)
# get list of assigned emblems
path, item_name = os.path.split(self._path)
assigned_emblems = (
self._application.emblem_manager.get_emblems(path, item_name) or []
)
# populate emblem list
emblems = self._application.emblem_manager.get_available_emblems()
for emblem in emblems:
self._emblems_store.append((emblem in assigned_emblems, emblem, emblem))
# pack user interface
container.add(self._emblems)
tab.pack_start(container, True, True, 0)
return tab
def _handle_key_press(self, widget, event, data=None):
"""Handle pressing keys"""
if event.keyval == Gdk.KEY_Escape:
self._close_window()
|
AddonManager | addonmanager_uninstaller | # SPDX-License-Identifier: LGPL-2.1-or-later
# ***************************************************************************
# * *
# * Copyright (c) 2022 FreeCAD Project Association *
# * *
# * This file is part of FreeCAD. *
# * *
# * FreeCAD is free software: you can redistribute it and/or modify it *
# * under the terms of the GNU Lesser General Public License as *
# * published by the Free Software Foundation, either version 2.1 of the *
# * License, or (at your option) any later version. *
# * *
# * FreeCAD is distributed in the hope that it will be useful, but *
# * WITHOUT ANY WARRANTY; without even the implied warranty of *
# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
# * Lesser General Public License for more details. *
# * *
# * You should have received a copy of the GNU Lesser General Public *
# * License along with FreeCAD. If not, see *
# * <https://www.gnu.org/licenses/>. *
# * *
# ***************************************************************************
""" Contains the classes to manage Addon removal: intended as a stable API, safe for
external code to call and to rely upon existing. See classes AddonUninstaller and
MacroUninstaller for details."""
import os
from typing import List
import addonmanager_freecad_interface as fci
import addonmanager_utilities as utils
from Addon import Addon
from addonmanager_pyside_interface import QObject, Signal
translate = fci.translate
# pylint: disable=too-few-public-methods
class InvalidAddon(RuntimeError):
"""Raised when an object that cannot be uninstalled is passed to the constructor"""
class AddonUninstaller(QObject):
"""The core, non-GUI uninstaller class for non-macro addons. Usually instantiated
and moved to its own thread, otherwise it will block the GUI (if the GUI is
running) -- since all it does is delete files this is not a huge problem,
but in some cases the Addon might be quite large, and deletion may take a
non-trivial amount of time.
In all cases in this class, the generic Python 'object' argument to the init
function is intended to be an Addon-like object that provides, at a minimum,
a 'name' attribute. The Addon manager uses the Addon class for this purpose,
but external code may use any other class that meets that criterion.
Recommended Usage (when running with the GUI up, so you don't block the GUI thread):
addon_to_remove = MyAddon() # Some class with 'name' attribute
self.worker_thread = QThread()
self.uninstaller = AddonUninstaller(addon_to_remove)
self.uninstaller.moveToThread(self.worker_thread)
self.uninstaller.success.connect(self.removal_succeeded)
self.uninstaller.failure.connect(self.removal_failed)
self.uninstaller.finished.connect(self.worker_thread.quit)
self.worker_thread.started.connect(self.uninstaller.run)
self.worker_thread.start() # Returns immediately
# On success, the connections above result in self.removal_succeeded being
emitted, and # on failure, self.removal_failed is emitted.
Recommended non-GUI usage (blocks until complete):
addon_to_remove = MyAddon() # Some class with 'name' attribute
uninstaller = AddonInstaller(addon_to_remove)
uninstaller.run()
"""
# Signals: success and failure Emitted when the installation process is complete.
# The object emitted is the object that the installation was requested for.
success = Signal(object)
failure = Signal(object, str)
# Finished: regardless of the outcome, this is emitted when all work that is
# going to be done is done (i.e. whatever thread this is running in can quit).
finished = Signal()
def __init__(self, addon: Addon):
"""Initialize the uninstaller."""
super().__init__()
self.addon_to_remove = addon
self.installation_path = fci.DataPaths().mod_dir
self.macro_installation_path = fci.DataPaths().macro_dir
def run(self) -> bool:
"""Remove an addon. Returns True if the addon was removed cleanly, or False
if not. Emits either success or failure prior to returning."""
success = False
error_message = translate("AddonsInstaller", "An unknown error occurred")
if hasattr(self.addon_to_remove, "name") and self.addon_to_remove.name:
# Make sure we don't accidentally remove the Mod directory
path_to_remove = os.path.normpath(
os.path.join(self.installation_path, self.addon_to_remove.name)
)
if os.path.exists(path_to_remove) and not os.path.samefile(
path_to_remove, self.installation_path
):
try:
self.run_uninstall_script(path_to_remove)
self.remove_extra_files(path_to_remove)
success = utils.rmdir(path_to_remove)
if (
hasattr(self.addon_to_remove, "contains_workbench")
and self.addon_to_remove.contains_workbench()
):
self.addon_to_remove.desinstall_workbench()
except OSError as e:
error_message = str(e)
else:
error_message = translate(
"AddonsInstaller",
"Could not find addon {} to remove it.",
).format(self.addon_to_remove.name)
if success:
self.success.emit(self.addon_to_remove)
else:
self.failure.emit(self.addon_to_remove, error_message)
self.addon_to_remove.set_status(Addon.Status.NOT_INSTALLED)
self.finished.emit()
return success
@staticmethod
def run_uninstall_script(path_to_remove):
"""Run the addon's uninstaller.py script, if it exists"""
uninstall_script = os.path.join(path_to_remove, "uninstall.py")
if os.path.exists(uninstall_script):
# pylint: disable=broad-exception-caught
try:
with open(uninstall_script, encoding="utf-8") as f:
exec(f.read())
except Exception:
fci.Console.PrintError(
translate(
"AddonsInstaller",
"Execution of Addon's uninstall.py script failed. Proceeding with uninstall...",
)
+ "\n"
)
@staticmethod
def remove_extra_files(path_to_remove):
"""When installing, an extra file called AM_INSTALLATION_DIGEST.txt may be
created, listing extra files that the installer put into place. Remove those
files."""
digest = os.path.join(path_to_remove, "AM_INSTALLATION_DIGEST.txt")
if not os.path.exists(digest):
return
with open(digest, encoding="utf-8") as f:
lines = f.readlines()
for line in lines:
stripped = line.strip()
if (
len(stripped) > 0
and stripped[0] != "#"
and os.path.exists(stripped)
):
try:
os.unlink(stripped)
fci.Console.PrintMessage(
translate(
"AddonsInstaller", "Removed extra installed file {}"
).format(stripped)
+ "\n"
)
except FileNotFoundError:
pass # Great, no need to remove then!
except OSError as e:
# Strange error to receive here, but just continue and print
# out an error to the console
fci.Console.PrintWarning(
translate(
"AddonsInstaller",
"Error while trying to remove extra installed file {}",
).format(stripped)
+ "\n"
)
fci.Console.PrintWarning(str(e) + "\n")
class MacroUninstaller(QObject):
"""The core, non-GUI uninstaller class for macro addons. May be run directly on
the GUI thread if desired, since macros are intended to be relatively small and
shouldn't have too many files to delete. However, it is a QObject so may also be
moved into a QThread -- see AddonUninstaller documentation for details of that
implementation.
The Python object passed in is expected to provide a "macro" subobject,
which itself is required to provide at least a "filename" attribute, and may also
provide an "icon", "xpm", and/or "other_files" attribute. All filenames provided
by those attributes are expected to be relative to the installed location of the
"filename" macro file (usually the main FreeCAD user macros directory)."""
# Signals: success and failure Emitted when the removal process is complete. The
# object emitted is the object that the removal was requested for.
success = Signal(object)
failure = Signal(object, str)
# Finished: regardless of the outcome, this is emitted when all work that is
# going to be done is done (i.e. whatever thread this is running in can quit).
finished = Signal()
def __init__(self, addon):
super().__init__()
self.installation_location = fci.DataPaths().macro_dir
self.addon_to_remove = addon
if (
not hasattr(self.addon_to_remove, "macro")
or not self.addon_to_remove.macro
or not hasattr(self.addon_to_remove.macro, "filename")
or not self.addon_to_remove.macro.filename
):
raise InvalidAddon()
def run(self):
"""Execute the removal process."""
success = True
errors = []
directories = set()
for f in self._get_files_to_remove():
normed = os.path.normpath(f)
full_path = os.path.join(self.installation_location, normed)
if "/" in f:
directories.add(os.path.dirname(full_path))
try:
os.unlink(full_path)
fci.Console.PrintLog(f"Removed macro file {full_path}\n")
except FileNotFoundError:
pass # Great, no need to remove then!
except OSError as e:
# Probably permission denied, or something like that
errors.append(
translate(
"AddonsInstaller",
"Error while trying to remove macro file {}: ",
).format(full_path)
+ str(e)
)
success = False
self._cleanup_directories(directories)
if success:
self.success.emit(self.addon_to_remove)
else:
self.failure.emit(self.addon_to_remove, "\n".join(errors))
self.addon_to_remove.set_status(Addon.Status.NOT_INSTALLED)
self.finished.emit()
def _get_files_to_remove(self) -> List[os.PathLike]:
"""Get the list of files that should be removed"""
files_to_remove = [self.addon_to_remove.macro.filename]
if self.addon_to_remove.macro.icon:
files_to_remove.append(self.addon_to_remove.macro.icon)
if self.addon_to_remove.macro.xpm:
files_to_remove.append(
self.addon_to_remove.macro.name.replace(" ", "_") + "_icon.xpm"
)
for f in self.addon_to_remove.macro.other_files:
files_to_remove.append(f)
return files_to_remove
@staticmethod
def _cleanup_directories(directories):
"""Clean up any extra directories that are leftover and are empty"""
for directory in directories:
if os.path.isdir(directory):
utils.remove_directory_if_empty(directory)
|
Gui | Preferences | # -*- coding: utf-8 -*-
# ***************************************************************************
# * Copyright (c) 2016 sliptonic <shopinthewoods@gmail.com> *
# * *
# * This program is free software; you can redistribute it and/or modify *
# * it under the terms of the GNU Lesser General Public License (LGPL) *
# * as published by the Free Software Foundation; either version 2 of *
# * the License, or (at your option) any later version. *
# * for detail see the LICENCE text file. *
# * *
# * This program is distributed in the hope that it will be useful, *
# * but WITHOUT ANY WARRANTY; without even the implied warranty of *
# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
# * GNU Library General Public License for more details. *
# * *
# * You should have received a copy of the GNU Library General Public *
# * License along with this program; if not, write to the Free Software *
# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
# * USA *
# * *
# ***************************************************************************
import FreeCAD
from PySide import QtCore, QtGui
translate = FreeCAD.Qt.translate
_dressups = []
def RegisterDressup(dressup):
_dressups.append(dressup)
class DressupPreferencesPage:
def __init__(self, parent=None):
self.form = QtGui.QToolBox()
self.form.setWindowTitle(translate("Path_PreferencesPathDressup", "Dressups"))
pages = []
for dressup in _dressups:
page = dressup.preferencesPage()
if hasattr(page, "icon") and page.icon:
self.form.addItem(page.form, page.icon, page.label)
else:
self.form.addItem(page.form, page.label)
pages.append(page)
self.pages = pages
def saveSettings(self):
for page in self.pages:
page.saveSettings()
def loadSettings(self):
for page in self.pages:
page.loadSettings()
|
PrinterOutput | PrinterOutputDevice | # Copyright (c) 2022 Ultimaker B.V.
# Cura is released under the terms of the LGPLv3 or higher.
from enum import IntEnum
from typing import Callable, List, Optional, Union
import cura.CuraApplication # Imported like this to prevent circular imports.
from PyQt6.QtCore import QObject, QTimer, QUrl, pyqtProperty, pyqtSignal
from PyQt6.QtWidgets import QMessageBox
from UM.FlameProfiler import pyqtSlot
from UM.i18n import i18nCatalog
from UM.Logger import Logger
from UM.OutputDevice.OutputDevice import OutputDevice
from UM.Qt.QtApplication import QtApplication
from UM.Signal import signalemitter
MYPY = False
if MYPY:
from UM.FileHandler.FileHandler import FileHandler
from UM.Scene.SceneNode import SceneNode
from .FirmwareUpdater import FirmwareUpdater
from .Models.PrinterConfigurationModel import PrinterConfigurationModel
from .Models.PrinterOutputModel import PrinterOutputModel
i18n_catalog = i18nCatalog("cura")
class ConnectionState(IntEnum):
"""The current processing state of the backend."""
Closed = 0
Connecting = 1
Connected = 2
Busy = 3
Error = 4
class ConnectionType(IntEnum):
NotConnected = 0
UsbConnection = 1
NetworkConnection = 2
CloudConnection = 3
@signalemitter
class PrinterOutputDevice(QObject, OutputDevice):
"""Printer output device adds extra interface options on top of output device.
The assumption is made the printer is a FDM printer.
Note that a number of settings are marked as "final". This is because decorators
are not inherited by children. To fix this we use the private counterpart of those
functions to actually have the implementation.
For all other uses it should be used in the same way as a "regular" OutputDevice.
"""
printersChanged = pyqtSignal()
connectionStateChanged = pyqtSignal(str)
acceptsCommandsChanged = pyqtSignal()
# Signal to indicate that the material of the active printer on the remote changed.
materialIdChanged = pyqtSignal()
# # Signal to indicate that the hotend of the active printer on the remote changed.
hotendIdChanged = pyqtSignal()
# Signal to indicate that the info text about the connection has changed.
connectionTextChanged = pyqtSignal()
# Signal to indicate that the configuration of one of the printers has changed.
uniqueConfigurationsChanged = pyqtSignal()
def __init__(
self,
device_id: str,
connection_type: "ConnectionType" = ConnectionType.NotConnected,
parent: QObject = None,
) -> None:
super().__init__(device_id=device_id, parent=parent) # type: ignore # MyPy complains with the multiple inheritance
self._printers = [] # type: List[PrinterOutputModel]
self._unique_configurations = [] # type: List[PrinterConfigurationModel]
self._monitor_view_qml_path = "" # type: str
self._monitor_component = None # type: Optional[QObject]
self._monitor_item = None # type: Optional[QObject]
self._control_view_qml_path = "" # type: str
self._control_component = None # type: Optional[QObject]
self._control_item = None # type: Optional[QObject]
self._accepts_commands = False # type: bool
self._update_timer = QTimer() # type: QTimer
self._update_timer.setInterval(2000) # TODO; Add preference for update interval
self._update_timer.setSingleShot(False)
self._update_timer.timeout.connect(self._update)
self._connection_state = ConnectionState.Closed # type: ConnectionState
self._connection_type = connection_type # type: ConnectionType
self._firmware_updater = None # type: Optional[FirmwareUpdater]
self._firmware_name = None # type: Optional[str]
self._address = "" # type: str
self._connection_text = "" # type: str
self.printersChanged.connect(self._onPrintersChanged)
QtApplication.getInstance().getOutputDeviceManager().outputDevicesChanged.connect(
self._updateUniqueConfigurations
)
@pyqtProperty(str, notify=connectionTextChanged)
def address(self) -> str:
return self._address
def setConnectionText(self, connection_text):
if self._connection_text != connection_text:
self._connection_text = connection_text
self.connectionTextChanged.emit()
@pyqtProperty(str, constant=True)
def connectionText(self) -> str:
return self._connection_text
def materialHotendChangedMessage(self, callback: Callable[[int], None]) -> None:
Logger.log(
"w", "materialHotendChangedMessage needs to be implemented, returning 'Yes'"
)
callback(QMessageBox.Yes)
def isConnected(self) -> bool:
"""
Returns whether we could theoretically send commands to this printer.
:return: `True` if we are connected, or `False` if not.
"""
return (
self.connectionState != ConnectionState.Closed
and self.connectionState != ConnectionState.Error
)
def setConnectionState(self, connection_state: "ConnectionState") -> None:
"""
Store the connection state of the printer.
Causes everything that displays the connection state to update its QML models.
:param connection_state: The new connection state to store.
"""
if self.connectionState != connection_state:
self._connection_state = connection_state
application = cura.CuraApplication.CuraApplication.getInstance()
if (
application is not None
): # Might happen during the closing of Cura or in a test.
global_stack = application.getGlobalContainerStack()
if global_stack is not None:
global_stack.setMetaDataEntry("is_online", self.isConnected())
self.connectionStateChanged.emit(self._id)
@pyqtProperty(int, constant=True)
def connectionType(self) -> "ConnectionType":
return self._connection_type
@pyqtProperty(int, notify=connectionStateChanged)
def connectionState(self) -> "ConnectionState":
"""
Get the connection state of the printer, e.g. whether it is connected, still connecting, error state, etc.
:return: The current connection state of this output device.
"""
return self._connection_state
def _update(self) -> None:
pass
def _getPrinterByKey(self, key: str) -> Optional["PrinterOutputModel"]:
for printer in self._printers:
if printer.key == key:
return printer
return None
def requestWrite(
self,
nodes: List["SceneNode"],
file_name: Optional[str] = None,
limit_mimetypes: bool = False,
file_handler: Optional["FileHandler"] = None,
filter_by_machine: bool = False,
**kwargs,
) -> None:
raise NotImplementedError("requestWrite needs to be implemented")
@pyqtProperty(QObject, notify=printersChanged)
def activePrinter(self) -> Optional["PrinterOutputModel"]:
if self._printers:
return self._printers[0]
return None
@pyqtProperty("QVariantList", notify=printersChanged)
def printers(self) -> List["PrinterOutputModel"]:
return self._printers
@pyqtProperty(QObject, constant=True)
def monitorItem(self) -> QObject:
# Note that we specifically only check if the monitor component is created.
# It could be that it failed to actually create the qml item! If we check if the item was created, it will try
# to create the item (and fail) every time.
if not self._monitor_component:
self._createMonitorViewFromQML()
return self._monitor_item
@pyqtProperty(QObject, constant=True)
def controlItem(self) -> QObject:
if not self._control_component:
self._createControlViewFromQML()
return self._control_item
def _createControlViewFromQML(self) -> None:
if not self._control_view_qml_path:
return
if self._control_item is None:
self._control_item = QtApplication.getInstance().createQmlComponent(
self._control_view_qml_path, {"OutputDevice": self}
)
def _createMonitorViewFromQML(self) -> None:
if not self._monitor_view_qml_path:
return
if self._monitor_item is None:
self._monitor_item = QtApplication.getInstance().createQmlComponent(
self._monitor_view_qml_path, {"OutputDevice": self}
)
def connect(self) -> None:
"""Attempt to establish connection"""
self.setConnectionState(ConnectionState.Connecting)
self._update_timer.start()
def close(self) -> None:
"""Attempt to close the connection"""
self._update_timer.stop()
self.setConnectionState(ConnectionState.Closed)
def __del__(self) -> None:
"""Ensure that close gets called when object is destroyed"""
self.close()
@pyqtProperty(bool, notify=acceptsCommandsChanged)
def acceptsCommands(self) -> bool:
return self._accepts_commands
def _setAcceptsCommands(self, accepts_commands: bool) -> None:
"""Set a flag to signal the UI that the printer is not (yet) ready to receive commands"""
if self._accepts_commands != accepts_commands:
self._accepts_commands = accepts_commands
self.acceptsCommandsChanged.emit()
@pyqtProperty("QVariantList", notify=uniqueConfigurationsChanged)
def uniqueConfigurations(self) -> List["PrinterConfigurationModel"]:
"""Returns the unique configurations of the printers within this output device"""
return self._unique_configurations
def _updateUniqueConfigurations(self) -> None:
all_configurations = set()
for printer in self._printers:
if (
printer.printerConfiguration is not None
and printer.printerConfiguration.hasAnyMaterialLoaded()
):
all_configurations.add(printer.printerConfiguration)
all_configurations.update(printer.availableConfigurations)
if None in all_configurations:
# Shouldn't happen, but it does. I don't see how it could ever happen. Skip adding that configuration.
# List could end up empty!
Logger.log("e", "Found a broken configuration in the synced list!")
all_configurations.remove(None)
new_configurations = sorted(
all_configurations,
key=lambda config: config.printerType or "",
reverse=True,
)
if new_configurations != self._unique_configurations:
self._unique_configurations = new_configurations
self.uniqueConfigurationsChanged.emit()
@pyqtProperty("QStringList", notify=uniqueConfigurationsChanged)
def uniquePrinterTypes(self) -> List[str]:
"""Returns the unique configurations of the printers within this output device"""
return list(
sorted(
set(
[
configuration.printerType or ""
for configuration in self._unique_configurations
]
)
)
)
def _onPrintersChanged(self) -> None:
for printer in self._printers:
printer.configurationChanged.connect(self._updateUniqueConfigurations)
printer.availableConfigurationsChanged.connect(
self._updateUniqueConfigurations
)
# At this point there may be non-updated configurations
self._updateUniqueConfigurations()
def _setFirmwareName(self, name: str) -> None:
"""Set the device firmware name
:param name: The name of the firmware.
"""
self._firmware_name = name
def getFirmwareName(self) -> Optional[str]:
"""Get the name of device firmware
This name can be used to define device type
"""
return self._firmware_name
def getFirmwareUpdater(self) -> Optional["FirmwareUpdater"]:
return self._firmware_updater
@pyqtSlot(str)
def updateFirmware(self, firmware_file: Union[str, QUrl]) -> None:
if not self._firmware_updater:
return
self._firmware_updater.updateFirmware(firmware_file)
|
analog | wfm_rcv | #
# Copyright 2005,2007,2012,2020 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# SPDX-License-Identifier: GPL-3.0-or-later
#
#
import math
from gnuradio import fft, filter, gr
from . import analog_python as analog
from .fm_emph import fm_deemph
class wfm_rcv(gr.hier_block2):
def __init__(self, quad_rate, audio_decimation, deemph_tau=75e-6):
"""
Hierarchical block for demodulating a broadcast FM signal.
The input is the downconverted complex baseband signal (gr_complex).
The output is the demodulated audio (float).
Args:
quad_rate: input sample rate of complex baseband input. (float)
audio_decimation: how much to decimate quad_rate to get to audio. (integer)
deemph_tau: deemphasis ime constant in seconds (75us in US and South Korea, 50us everywhere else). (float)
"""
gr.hier_block2.__init__(
self,
"wfm_rcv",
# Input signature
gr.io_signature(1, 1, gr.sizeof_gr_complex),
gr.io_signature(1, 1, gr.sizeof_float),
) # Output signature
if audio_decimation != int(audio_decimation):
raise ValueError("audio_decimation needs to be an integer")
audio_decimation = int(audio_decimation)
volume = 20.0
max_dev = 75e3
fm_demod_gain = quad_rate / (2 * math.pi * max_dev)
audio_rate = quad_rate / audio_decimation
# We assign to self so that outsiders can grab the demodulator
# if they need to. E.g., to plot its output.
#
# input: complex; output: float
self.fm_demod = analog.quadrature_demod_cf(fm_demod_gain)
# input: float; output: float
self.deemph_tau = deemph_tau
self.deemph = fm_deemph(audio_rate, tau=deemph_tau)
# compute FIR filter taps for audio filter
width_of_transition_band = audio_rate / 32
audio_coeffs = filter.firdes.low_pass(
1.0, # gain
quad_rate, # sampling rate
audio_rate / 2 - width_of_transition_band,
width_of_transition_band,
fft.window.WIN_HAMMING,
)
# input: float; output: float
self.audio_filter = filter.fir_filter_fff(audio_decimation, audio_coeffs)
self.connect(self, self.fm_demod, self.audio_filter, self.deemph, self)
|
gst | dynamic_sink | # Copyright (C) 2008-2010 Adam Olsen
# Copyright (C) 2013-2015 Dustin Spicuzza
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
#
# The developers of the Exaile media player hereby grant permission
# for non-GPL compatible GStreamer and Exaile plugins to be used and
# distributed together with GStreamer and Exaile. This permission is
# above and beyond the permissions granted by the GPL license by which
# Exaile is covered. If you modify this code, you may extend this
# exception to your version of the code, but you are not obligated to
# do so. If you do not wish to do so, delete this exception statement
# from your version.
import logging
import threading
from gi.repository import GLib, Gst
logger = logging.getLogger(__name__)
class DynamicAudioSink(Gst.Bin):
"""
An audio sink that can dynamically switch its output
TODO: When switching outputs rapidly, sometimes it tends to seek
ahead quite a bit. Not sure why.
"""
def __init__(self, name):
Gst.Bin.__init__(self, name=name)
self.audio_sink = None
self.__audio_sink_lock = threading.Lock()
# Create an identity object so we don't need to deal with linking
# the audio sink with anything external to this bin
self.identity = Gst.ElementFactory.make("identity", None)
self.identity.props.signal_handoffs = False
self.add(self.identity)
# Create a ghost sink pad so this bin appears to be an audio sink
sinkpad = self.identity.get_static_pad("sink")
self.add_pad(Gst.GhostPad.new("sink", sinkpad))
def reconfigure(self, audio_sink):
# don't try to switch more than one source at a time
release_lock = True
self.__audio_sink_lock.acquire()
try:
# If this is the first time we added a sink, just add it to
# the pipeline and we're done.
if not self.audio_sink:
self._add_audiosink(audio_sink, None)
return
old_audio_sink = self.audio_sink
# Ok, time to replace the old sink. If it's not in a playing state,
# then this isn't so bad.
# if we don't use the timeout, when we set it to READY, it may be performing
# an async wait for PAUSE, so we use the timeout here.
state = old_audio_sink.get_state(timeout=50 * Gst.MSECOND)[1]
if state != Gst.State.PLAYING:
buffer_position = None
if state != Gst.State.NULL:
try:
buffer_position = old_audio_sink.query_position(Gst.Format.TIME)
except Exception:
pass
self.remove(old_audio_sink)
old_audio_sink.set_state(Gst.State.NULL)
# Then add the new sink
self._add_audiosink(audio_sink, buffer_position)
return
#
# Otherwise, disconnecting the old device is a bit complex. Code is
# derived from algorithm/code described at the following link:
#
# https://gstreamer.freedesktop.org/documentation/application-development/advanced/pipeline-manipulation.html
#
# Start off by blocking the src pad of the prior element
spad = old_audio_sink.get_static_pad("sink").get_peer()
spad.add_probe(
Gst.PadProbeType.BLOCK_DOWNSTREAM, self._pad_blocked_cb, audio_sink
)
# Don't release the lock until pad block is done
release_lock = False
finally:
if release_lock:
self.__audio_sink_lock.release()
def _pad_blocked_cb(self, pad, info, new_audio_sink):
pad.remove_probe(info.id)
old_audio_sink = self.audio_sink
buffer_position = old_audio_sink.query_position(Gst.Format.TIME)
# No data is flowing at this point. Unlink the element, add the new one
self.remove(old_audio_sink)
def _flush_old_sink():
old_audio_sink.set_state(Gst.State.NULL)
GLib.timeout_add(2000, _flush_old_sink)
# Add the new element
self._add_audiosink(new_audio_sink, buffer_position)
self.__audio_sink_lock.release()
# And drop the probe, which will cause data to flow again
return Gst.PadProbeReturn.DROP
def _add_audiosink(self, audio_sink, buffer_position):
"""Sets up the new audiosink and syncs it"""
self.add(audio_sink)
audio_sink.sync_state_with_parent()
self.identity.link(audio_sink)
if buffer_position is not None:
# buffer position is the output from get_position. If set, we
# seek to that position.
# TODO: this actually seems to skip ahead a tiny bit. why?
# Note! this is super important in paused mode too, because when
# we switch the sinks around the new sink never goes into
# the paused state because there's no buffer. This forces
# a resync of the buffer, so things still work.
seek_event = Gst.Event.new_seek(
1.0,
Gst.Format.TIME,
Gst.SeekFlags.FLUSH,
Gst.SeekType.SET,
buffer_position[1],
Gst.SeekType.NONE,
0,
)
self.send_event(seek_event)
self.audio_sink = audio_sink
# vim: et sts=4 sw=4
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.