id
int64 0
458k
| file_name
stringlengths 4
119
| file_path
stringlengths 14
227
| content
stringlengths 24
9.96M
| size
int64 24
9.96M
| language
stringclasses 1
value | extension
stringclasses 14
values | total_lines
int64 1
219k
| avg_line_length
float64 2.52
4.63M
| max_line_length
int64 5
9.91M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 7
101
| repo_stars
int64 100
139k
| repo_forks
int64 0
26.4k
| repo_open_issues
int64 0
2.27k
| repo_license
stringclasses 12
values | repo_extraction_date
stringclasses 433
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
16,000
|
legos.py
|
OpenRCE_sulley/unit_tests/legos.py
|
from sulley import *
def run ():
tag()
ndr_string()
ber()
# clear out the requests.
blocks.REQUESTS = {}
blocks.CURRENT = None
########################################################################################################################
def tag ():
s_initialize("UNIT TEST TAG 1")
s_lego("tag", value="pedram")
req = s_get("UNIT TEST TAG 1")
print "LEGO MUTATION COUNTS:"
print "\ttag: %d" % req.num_mutations()
########################################################################################################################
def ndr_string ():
s_initialize("UNIT TEST NDR 1")
s_lego("ndr_string", value="pedram")
req = s_get("UNIT TEST NDR 1")
# TODO: unfinished!
#print req.render()
########################################################################################################################
def ber ():
s_initialize("UNIT TEST BER 1")
s_lego("ber_string", value="pedram")
req = s_get("UNIT TEST BER 1")
assert(s_render() == "\x04\x84\x00\x00\x00\x06\x70\x65\x64\x72\x61\x6d")
s_mutate()
assert(s_render() == "\x04\x84\x00\x00\x00\x00\x70\x65\x64\x72\x61\x6d")
s_initialize("UNIT TEST BER 2")
s_lego("ber_integer", value=0xdeadbeef)
req = s_get("UNIT TEST BER 2")
assert(s_render() == "\x02\x04\xde\xad\xbe\xef")
s_mutate()
assert(s_render() == "\x02\x04\x00\x00\x00\x00")
s_mutate()
assert(s_render() == "\x02\x04\x00\x00\x00\x01")
| 1,500
|
Python
|
.py
| 38
| 35.026316
| 120
| 0.458994
|
OpenRCE/sulley
| 1,416
| 338
| 56
|
GPL-2.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
16,001
|
blocks.py
|
OpenRCE_sulley/unit_tests/blocks.py
|
from sulley import *
def run ():
groups_and_num_test_cases()
dependencies()
repeaters()
return_current_mutant()
exhaustion()
# clear out the requests.
blocks.REQUESTS = {}
blocks.CURRENT = None
########################################################################################################################
def groups_and_num_test_cases ():
s_initialize("UNIT TEST 1")
s_size("BLOCK", length=4, name="sizer")
s_group("group", values=["\x01", "\x05", "\x0a", "\xff"])
if s_block_start("BLOCK"):
s_delim(">", name="delim")
s_string("pedram", name="string")
s_byte(0xde, name="byte")
s_word(0xdead, name="word")
s_dword(0xdeadbeef, name="dword")
s_qword(0xdeadbeefdeadbeef, name="qword")
s_random(0, 5, 10, 100, name="random")
s_block_end()
# count how many mutations we get per primitive type.
req1 = s_get("UNIT TEST 1")
print "PRIMITIVE MUTATION COUNTS (SIZES):"
print "\tdelim: %d\t(%s)" % (req1.names["delim"].num_mutations(), sum(map(len, req1.names["delim"].fuzz_library)))
print "\tstring: %d\t(%s)" % (req1.names["string"].num_mutations(), sum(map(len, req1.names["string"].fuzz_library)))
print "\tbyte: %d" % req1.names["byte"].num_mutations()
print "\tword: %d" % req1.names["word"].num_mutations()
print "\tdword: %d" % req1.names["dword"].num_mutations()
print "\tqword: %d" % req1.names["qword"].num_mutations()
print "\tsizer: %d" % req1.names["sizer"].num_mutations()
# we specify the number of mutations in a random field, so ensure that matches.
assert(req1.names["random"].num_mutations() == 100)
# we specify the number of values in a group field, so ensure that matches.
assert(req1.names["group"].num_mutations() == 4)
# assert that the number of block mutations equals the sum of the number of mutations of its components.
assert(req1.names["BLOCK"].num_mutations() == req1.names["delim"].num_mutations() + \
req1.names["string"].num_mutations() + \
req1.names["byte"].num_mutations() + \
req1.names["word"].num_mutations() + \
req1.names["dword"].num_mutations() + \
req1.names["qword"].num_mutations() + \
req1.names["random"].num_mutations())
s_initialize("UNIT TEST 2")
s_group("group", values=["\x01", "\x05", "\x0a", "\xff"])
if s_block_start("BLOCK", group="group"):
s_delim(">", name="delim")
s_string("pedram", name="string")
s_byte(0xde, name="byte")
s_word(0xdead, name="word")
s_dword(0xdeadbeef, name="dword")
s_qword(0xdeadbeefdeadbeef, name="qword")
s_random(0, 5, 10, 100, name="random")
s_block_end()
# assert that the number of block mutations in request 2 is len(group.values) (4) times that of request 1.
req2 = s_get("UNIT TEST 2")
assert(req2.names["BLOCK"].num_mutations() == req1.names["BLOCK"].num_mutations() * 4)
########################################################################################################################
def dependencies ():
s_initialize("DEP TEST 1")
s_group("group", values=["1", "2"])
if s_block_start("ONE", dep="group", dep_values=["1"]):
s_static("ONE" * 100)
s_block_end()
if s_block_start("TWO", dep="group", dep_values=["2"]):
s_static("TWO" * 100)
s_block_end()
assert(s_num_mutations() == 2)
assert(s_mutate() == True)
assert(s_render().find("TWO") == -1)
assert(s_mutate() == True)
assert(s_render().find("ONE") == -1)
assert(s_mutate() == False)
########################################################################################################################
def repeaters ():
s_initialize("REP TEST 1")
if s_block_start("BLOCK"):
s_delim(">", name="delim", fuzzable=False)
s_string("pedram", name="string", fuzzable=False)
s_byte(0xde, name="byte", fuzzable=False)
s_word(0xdead, name="word", fuzzable=False)
s_dword(0xdeadbeef, name="dword", fuzzable=False)
s_qword(0xdeadbeefdeadbeef, name="qword", fuzzable=False)
s_random(0, 5, 10, 100, name="random", fuzzable=False)
s_block_end()
s_repeat("BLOCK", min_reps=5, max_reps=15, step=5)
data = s_render()
length = len(data)
s_mutate()
data = s_render()
assert(len(data) == length + length * 5)
s_mutate()
data = s_render()
assert(len(data) == length + length * 10)
s_mutate()
data = s_render()
assert(len(data) == length + length * 15)
s_mutate()
data = s_render()
assert(len(data) == length)
########################################################################################################################
def return_current_mutant ():
s_initialize("RETURN CURRENT MUTANT TEST 1")
s_dword(0xdeadbeef, name="boss hog")
s_string("bloodhound gang", name="vagina")
if s_block_start("BLOCK1"):
s_string("foo", name="foo")
s_string("bar", name="bar")
s_dword(0x20)
s_block_end()
s_dword(0xdead)
s_dword(0x0fed)
s_string("sucka free at 2 in morning 7/18", name="uhntiss")
req1 = s_get("RETURN CURRENT MUTANT TEST 1")
# calculate the length of the mutation libraries dynamically since they may change with time.
num_str_mutations = req1.names["foo"].num_mutations()
num_int_mutations = req1.names["boss hog"].num_mutations()
for i in xrange(1, num_str_mutations + num_int_mutations - 10 + 1):
req1.mutate()
assert(req1.mutant.name == "vagina")
req1.reset()
for i in xrange(1, num_int_mutations + num_str_mutations + 1 + 1):
req1.mutate()
assert(req1.mutant.name == "foo")
req1.reset()
for i in xrange(num_str_mutations * 2 + num_int_mutations + 1):
req1.mutate()
assert(req1.mutant.name == "bar")
req1.reset()
for i in xrange(num_str_mutations * 3 + num_int_mutations * 4 + 1):
req1.mutate()
assert(req1.mutant.name == "uhntiss")
req1.reset()
########################################################################################################################
def exhaustion ():
s_initialize("EXHAUSTION 1")
s_string("just wont eat", name="VIP")
s_dword(0x4141, name="eggos_rule")
s_dword(0x4242, name="danny_glover_is_the_man")
req1 = s_get("EXHAUSTION 1")
num_str_mutations = req1.names["VIP"].num_mutations()
# if we mutate string halfway, then exhaust, then mutate one time, we should be in the 2nd primitive
for i in xrange(num_str_mutations/2):
req1.mutate()
req1.mutant.exhaust()
req1.mutate()
assert(req1.mutant.name == "eggos_rule")
req1.reset()
# if we mutate through the first primitive, then exhaust the 2nd, we should be in the 3rd
for i in xrange(num_str_mutations + 2):
req1.mutate()
req1.mutant.exhaust()
req1.mutate()
assert(req1.mutant.name == "danny_glover_is_the_man")
req1.reset()
# if we exhaust the first two primitives, we should be in the third
req1.mutant.exhaust()
req1.mutant.exhaust()
assert(req1.mutant.name == "danny_glover_is_the_man")
| 7,552
|
Python
|
.py
| 162
| 38.993827
| 121
| 0.547337
|
OpenRCE/sulley
| 1,416
| 338
| 56
|
GPL-2.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
16,002
|
primitives.py
|
OpenRCE_sulley/unit_tests/primitives.py
|
from sulley import *
def run ():
signed_tests()
string_tests()
fuzz_extension_tests()
# clear out the requests.
blocks.REQUESTS = {}
blocks.CURRENT = None
########################################################################################################################
def signed_tests ():
s_initialize("UNIT TEST 1")
s_byte(0, format="ascii", signed=True, name="byte_1")
s_byte(0xff/2, format="ascii", signed=True, name="byte_2")
s_byte(0xff/2+1, format="ascii", signed=True, name="byte_3")
s_byte(0xff, format="ascii", signed=True, name="byte_4")
s_word(0, format="ascii", signed=True, name="word_1")
s_word(0xffff/2, format="ascii", signed=True, name="word_2")
s_word(0xffff/2+1, format="ascii", signed=True, name="word_3")
s_word(0xffff, format="ascii", signed=True, name="word_4")
s_dword(0, format="ascii", signed=True, name="dword_1")
s_dword(0xffffffff/2, format="ascii", signed=True, name="dword_2")
s_dword(0xffffffff/2+1, format="ascii", signed=True, name="dword_3")
s_dword(0xffffffff, format="ascii", signed=True, name="dword_4")
s_qword(0, format="ascii", signed=True, name="qword_1")
s_qword(0xffffffffffffffff/2, format="ascii", signed=True, name="qword_2")
s_qword(0xffffffffffffffff/2+1, format="ascii", signed=True, name="qword_3")
s_qword(0xffffffffffffffff, format="ascii", signed=True, name="qword_4")
req = s_get("UNIT TEST 1")
assert(req.names["byte_1"].render() == "0")
assert(req.names["byte_2"].render() == "127")
assert(req.names["byte_3"].render() == "-128")
assert(req.names["byte_4"].render() == "-1")
assert(req.names["word_1"].render() == "0")
assert(req.names["word_2"].render() == "32767")
assert(req.names["word_3"].render() == "-32768")
assert(req.names["word_4"].render() == "-1")
assert(req.names["dword_1"].render() == "0")
assert(req.names["dword_2"].render() == "2147483647")
assert(req.names["dword_3"].render() == "-2147483648")
assert(req.names["dword_4"].render() == "-1")
assert(req.names["qword_1"].render() == "0")
assert(req.names["qword_2"].render() == "9223372036854775807")
assert(req.names["qword_3"].render() == "-9223372036854775808")
assert(req.names["qword_4"].render() == "-1")
########################################################################################################################
def string_tests ():
s_initialize("STRING UNIT TEST 1")
s_string("foo", size=200, name="sized_string")
req = s_get("STRING UNIT TEST 1")
assert(len(req.names["sized_string"].render()) == 3)
# check that string padding and truncation are working correctly.
for i in xrange(0, 50):
s_mutate()
assert(len(req.names["sized_string"].render()) == 200)
########################################################################################################################
def fuzz_extension_tests ():
import shutil
# backup existing fuzz extension libraries.
try:
shutil.move(".fuzz_strings", ".fuzz_strings_backup")
shutil.move(".fuzz_ints", ".fuzz_ints_backup")
except:
pass
# create extension libraries for unit test.
fh = open(".fuzz_strings", "w+")
fh.write("pedram\n")
fh.write("amini\n")
fh.close()
fh = open(".fuzz_ints", "w+")
fh.write("deadbeef\n")
fh.write("0xc0cac01a\n")
fh.close()
s_initialize("EXTENSION TEST")
s_string("foo", name="string")
s_int(200, name="int")
s_char("A", name="char")
req = s_get("EXTENSION TEST")
# these should be here now.
assert(0xdeadbeef in req.names["int"].fuzz_library)
assert(0xc0cac01a in req.names["int"].fuzz_library)
# these should not as a char is too small to store them.
assert(0xdeadbeef not in req.names["char"].fuzz_library)
assert(0xc0cac01a not in req.names["char"].fuzz_library)
# these should be here now.
assert("pedram" in req.names["string"].fuzz_library)
assert("amini" in req.names["string"].fuzz_library)
# restore existing fuzz extension libraries.
try:
shutil.move(".fuzz_strings_backup", ".fuzz_strings")
shutil.move(".fuzz_ints_backup", ".fuzz_ints")
except:
pass
| 4,385
|
Python
|
.py
| 92
| 42.391304
| 120
| 0.570291
|
OpenRCE/sulley
| 1,416
| 338
| 56
|
GPL-2.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
16,003
|
generate_epydocs.bat
|
OpenRCE_sulley/docs/generate_epydocs.bat
|
c:\Python27\python.exe c:\Python27\Scripts\epydoc.py -o Sulley --css blue --name "Sulley: Fuzzing Framework" --url "http://pedram.openrce.org" ..\sulley
| 152
|
Python
|
.py
| 1
| 152
| 152
| 0.730263
|
OpenRCE/sulley
| 1,416
| 338
| 56
|
GPL-2.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
16,004
|
sessions.py
|
OpenRCE_sulley/sulley/sessions.py
|
import os
import re
import sys
import zlib
import time
import socket
import httplib
import cPickle
import threading
import BaseHTTPServer
import httplib
import logging
import blocks
import pedrpc
import pgraph
import sex
import primitives
########################################################################################################################
class target:
'''
Target descriptor container.
'''
def __init__ (self, host, port, **kwargs):
'''
@type host: String
@param host: Hostname or IP address of target system
@type port: Integer
@param port: Port of target service
'''
self.host = host
self.port = port
# set these manually once target is instantiated.
self.netmon = None
self.procmon = None
self.vmcontrol = None
self.netmon_options = {}
self.procmon_options = {}
self.vmcontrol_options = {}
def pedrpc_connect (self):
'''
Pass specified target parameters to the PED-RPC server.
'''
# If the process monitor is alive, set it's options
if self.procmon:
while 1:
try:
if self.procmon.alive():
break
except:
pass
time.sleep(1)
# connection established.
for key in self.procmon_options.keys():
eval('self.procmon.set_%s(self.procmon_options["%s"])' % (key, key))
# If the network monitor is alive, set it's options
if self.netmon:
while 1:
try:
if self.netmon.alive():
break
except:
pass
time.sleep(1)
# connection established.
for key in self.netmon_options.keys():
eval('self.netmon.set_%s(self.netmon_options["%s"])' % (key, key))
########################################################################################################################
class connection (pgraph.edge.edge):
def __init__ (self, src, dst, callback=None):
'''
Extends pgraph.edge with a callback option. This allows us to register a function to call between node
transmissions to implement functionality such as challenge response systems. The callback method must follow
this prototype::
def callback(session, node, edge, sock)
Where node is the node about to be sent, edge is the last edge along the current fuzz path to "node", session
is a pointer to the session instance which is useful for snagging data such as sesson.last_recv which contains
the data returned from the last socket transmission and sock is the live socket. A callback is also useful in
situations where, for example, the size of the next packet is specified in the first packet.
@type src: Integer
@param src: Edge source ID
@type dst: Integer
@param dst: Edge destination ID
@type callback: Function
@param callback: (Optional, def=None) Callback function to pass received data to between node xmits
'''
# run the parent classes initialization routine first.
pgraph.edge.edge.__init__(self, src, dst)
self.callback = callback
########################################################################################################################
class session (pgraph.graph):
def __init__(
self,
session_filename=None,
skip=0,
sleep_time=1.0,
log_level=logging.INFO,
logfile=None,
logfile_level=logging.DEBUG,
proto="tcp",
bind=None,
restart_interval=0,
timeout=5.0,
web_port=26000,
crash_threshold=3,
restart_sleep_time=300
):
'''
Extends pgraph.graph and provides a container for architecting protocol dialogs.
@type session_filename: String
@kwarg session_filename: (Optional, def=None) Filename to serialize persistant data to
@type skip: Integer
@kwarg skip: (Optional, def=0) Number of test cases to skip
@type sleep_time: Float
@kwarg sleep_time: (Optional, def=1.0) Time to sleep in between tests
@type log_level: Integer
@kwarg log_level: (Optional, def=logger.INFO) Set the log level
@type logfile: String
@kwarg logfile: (Optional, def=None) Name of log file
@type logfile_level: Integer
@kwarg logfile_level: (Optional, def=logger.INFO) Set the log level for the logfile
@type proto: String
@kwarg proto: (Optional, def="tcp") Communication protocol ("tcp", "udp", "ssl")
@type bind: Tuple (host, port)
@kwarg bind: (Optional, def=random) Socket bind address and port
@type timeout: Float
@kwarg timeout: (Optional, def=5.0) Seconds to wait for a send/recv prior to timing out
@type restart_interval: Integer
@kwarg restart_interval (Optional, def=0) Restart the target after n test cases, disable by setting to 0
@type crash_threshold: Integer
@kwarg crash_threshold (Optional, def=3) Maximum number of crashes allowed before a node is exhaust
@type restart_sleep_time: Integer
@kwarg restart_sleep_time: Optional, def=300) Time in seconds to sleep when target can't be restarted
@type web_port: Integer
@kwarg web_port: (Optional, def=26000) Port for monitoring fuzzing campaign via a web browser
'''
# run the parent classes initialization routine first.
pgraph.graph.__init__(self)
self.session_filename = session_filename
self.skip = skip
self.sleep_time = sleep_time
self.proto = proto.lower()
self.bind = bind
self.ssl = False
self.restart_interval = restart_interval
self.timeout = timeout
self.web_port = web_port
self.crash_threshold = crash_threshold
self.restart_sleep_time = restart_sleep_time
# Initialize logger
self.logger = logging.getLogger("Sulley_logger")
self.logger.setLevel(log_level)
formatter = logging.Formatter('[%(asctime)s] [%(levelname)s] -> %(message)s')
if logfile != None:
filehandler = logging.FileHandler(logfile)
filehandler.setLevel(logfile_level)
filehandler.setFormatter(formatter)
self.logger.addHandler(filehandler)
consolehandler = logging.StreamHandler()
consolehandler.setFormatter(formatter)
consolehandler.setLevel(log_level)
self.logger.addHandler(consolehandler)
self.total_num_mutations = 0
self.total_mutant_index = 0
self.fuzz_node = None
self.targets = []
self.netmon_results = {}
self.procmon_results = {}
self.protmon_results = {}
self.pause_flag = False
self.crashing_primitives = {}
if self.proto == "tcp":
self.proto = socket.SOCK_STREAM
elif self.proto == "ssl":
self.proto = socket.SOCK_STREAM
self.ssl = True
elif self.proto == "udp":
self.proto = socket.SOCK_DGRAM
else:
raise sex.SullyRuntimeError("INVALID PROTOCOL SPECIFIED: %s" % self.proto)
# import settings if they exist.
self.import_file()
# create a root node. we do this because we need to start fuzzing from a single point and the user may want
# to specify a number of initial requests.
self.root = pgraph.node()
self.root.name = "__ROOT_NODE__"
self.root.label = self.root.name
self.last_recv = None
self.add_node(self.root)
####################################################################################################################
def add_node (self, node):
'''
Add a pgraph node to the graph. We overload this routine to automatically generate and assign an ID whenever a
node is added.
@type node: pGRAPH Node
@param node: Node to add to session graph
'''
node.number = len(self.nodes)
node.id = len(self.nodes)
if not self.nodes.has_key(node.id):
self.nodes[node.id] = node
return self
####################################################################################################################
def add_target (self, target):
'''
Add a target to the session. Multiple targets can be added for parallel fuzzing.
@type target: session.target
@param target: Target to add to session
'''
# pass specified target parameters to the PED-RPC server.
target.pedrpc_connect()
# add target to internal list.
self.targets.append(target)
####################################################################################################################
def connect (self, src, dst=None, callback=None):
'''
Create a connection between the two requests (nodes) and register an optional callback to process in between
transmissions of the source and destination request. Leverage this functionality to handle situations such as
challenge response systems. The session class maintains a top level node that all initial requests must be
connected to. Example::
sess = sessions.session()
sess.connect(sess.root, s_get("HTTP"))
If given only a single parameter, sess.connect() will default to attaching the supplied node to the root node.
This is a convenient alias and is identical to the second line from the above example::
sess.connect(s_get("HTTP"))
If you register callback method, it must follow this prototype::
def callback(session, node, edge, sock)
Where node is the node about to be sent, edge is the last edge along the current fuzz path to "node", session
is a pointer to the session instance which is useful for snagging data such as sesson.last_recv which contains
the data returned from the last socket transmission and sock is the live socket. A callback is also useful in
situations where, for example, the size of the next packet is specified in the first packet. As another
example, if you need to fill in the dynamic IP address of the target register a callback that snags the IP
from sock.getpeername()[0].
@type src: String or Request (Node)
@param src: Source request name or request node
@type dst: String or Request (Node)
@param dst: Destination request name or request node
@type callback: Function
@param callback: (Optional, def=None) Callback function to pass received data to between node xmits
@rtype: pgraph.edge
@return: The edge between the src and dst.
'''
# if only a source was provided, then make it the destination and set the source to the root node.
if not dst:
dst = src
src = self.root
# if source or destination is a name, resolve the actual node.
if type(src) is str:
src = self.find_node("name", src)
if type(dst) is str:
dst = self.find_node("name", dst)
# if source or destination is not in the graph, add it.
if src != self.root and not self.find_node("name", src.name):
self.add_node(src)
if not self.find_node("name", dst.name):
self.add_node(dst)
# create an edge between the two nodes and add it to the graph.
edge = connection(src.id, dst.id, callback)
self.add_edge(edge)
return edge
####################################################################################################################
def export_file (self):
'''
Dump various object values to disk.
@see: import_file()
'''
if not self.session_filename:
return
data = {}
data["session_filename"] = self.session_filename
data["skip"] = self.total_mutant_index
data["sleep_time"] = self.sleep_time
data["restart_sleep_time"] = self.restart_sleep_time
data["proto"] = self.proto
data["restart_interval"] = self.restart_interval
data["timeout"] = self.timeout
data["web_port"] = self.web_port
data["crash_threshold"] = self.crash_threshold
data["total_num_mutations"] = self.total_num_mutations
data["total_mutant_index"] = self.total_mutant_index
data["netmon_results"] = self.netmon_results
data["procmon_results"] = self.procmon_results
data['protmon_results'] = self.protmon_results
data["pause_flag"] = self.pause_flag
fh = open(self.session_filename, "wb+")
fh.write(zlib.compress(cPickle.dumps(data, protocol=2)))
fh.close()
####################################################################################################################
def fuzz (self, this_node=None, path=[]):
'''
Call this routine to get the ball rolling. No arguments are necessary as they are both utilized internally
during the recursive traversal of the session graph.
@type this_node: request (node)
@param this_node: (Optional, def=None) Current node that is being fuzzed.
@type path: List
@param path: (Optional, def=[]) Nodes along the path to the current one being fuzzed.
'''
# if no node is specified, then we start from the root node and initialize the session.
if not this_node:
# we can't fuzz if we don't have at least one target and one request.
if not self.targets:
raise sex.SullyRuntimeError("NO TARGETS SPECIFIED IN SESSION")
if not self.edges_from(self.root.id):
raise sex.SullyRuntimeError("NO REQUESTS SPECIFIED IN SESSION")
this_node = self.root
try: self.server_init()
except: return
# TODO: complete parallel fuzzing, will likely have to thread out each target
target = self.targets[0]
# step through every edge from the current node.
for edge in self.edges_from(this_node.id):
# the destination node is the one actually being fuzzed.
self.fuzz_node = self.nodes[edge.dst]
num_mutations = self.fuzz_node.num_mutations()
# keep track of the path as we fuzz through it, don't count the root node.
# we keep track of edges as opposed to nodes because if there is more then one path through a set of
# given nodes we don't want any ambiguity.
path.append(edge)
current_path = " -> ".join([self.nodes[e.src].name for e in path[1:]])
current_path += " -> %s" % self.fuzz_node.name
self.logger.info("current fuzz path: %s" % current_path)
self.logger.info("fuzzed %d of %d total cases" % (self.total_mutant_index, self.total_num_mutations))
done_with_fuzz_node = False
crash_count = 0
# loop through all possible mutations of the fuzz node.
while not done_with_fuzz_node:
# if we need to pause, do so.
self.pause()
# if we have exhausted the mutations of the fuzz node, break out of the while(1).
# note: when mutate() returns False, the node has been reverted to the default (valid) state.
if not self.fuzz_node.mutate():
self.logger.error("all possible mutations for current fuzz node exhausted")
done_with_fuzz_node = True
continue
# make a record in the session that a mutation was made.
self.total_mutant_index += 1
# if we've hit the restart interval, restart the target.
if self.restart_interval and self.total_mutant_index % self.restart_interval == 0:
self.logger.error("restart interval of %d reached" % self.restart_interval)
self.restart_target(target)
# exception error handling routine, print log message and restart target.
def error_handler (e, msg, target, sock=None):
if sock:
sock.close()
msg += "\nException caught: %s" % repr(e)
msg += "\nRestarting target and trying again"
self.logger.critical(msg)
self.restart_target(target)
# if we don't need to skip the current test case.
if self.total_mutant_index > self.skip:
self.logger.info("fuzzing %d of %d" % (self.fuzz_node.mutant_index, num_mutations))
# attempt to complete a fuzz transmission. keep trying until we are successful, whenever a failure
# occurs, restart the target.
while 1:
# instruct the debugger/sniffer that we are about to send a new fuzz.
if target.procmon:
try:
target.procmon.pre_send(self.total_mutant_index)
except Exception, e:
error_handler(e, "failed on procmon.pre_send()", target)
continue
if target.netmon:
try:
target.netmon.pre_send(self.total_mutant_index)
except Exception, e:
error_handler(e, "failed on netmon.pre_send()", target)
continue
try:
# establish a connection to the target.
(family, socktype, proto, canonname, sockaddr)=socket.getaddrinfo(target.host, target.port)[0]
sock = socket.socket(family, self.proto)
except Exception, e:
error_handler(e, "failed creating socket", target)
continue
if self.bind:
try:
sock.bind(self.bind)
except Exception, e:
error_handler(e, "failed binding on socket", target, sock)
continue
try:
sock.settimeout(self.timeout)
# Connect is needed only for TCP stream
if self.proto == socket.SOCK_STREAM:
sock.connect((target.host, target.port))
except Exception, e:
error_handler(e, "failed connecting on socket", target, sock)
continue
# if SSL is requested, then enable it.
if self.ssl:
try:
ssl = socket.ssl(sock)
sock = httplib.FakeSocket(sock, ssl)
except Exception, e:
error_handler(e, "failed ssl setup", target, sock)
continue
# if the user registered a pre-send function, pass it the sock and let it do the deed.
try:
self.pre_send(sock)
except Exception, e:
error_handler(e, "pre_send() failed", target, sock)
continue
# send out valid requests for each node in the current path up to the node we are fuzzing.
try:
for e in path[:-1]:
node = self.nodes[e.dst]
self.transmit(sock, node, e, target)
except Exception, e:
error_handler(e, "failed transmitting a node up the path", target, sock)
continue
# now send the current node we are fuzzing.
try:
self.transmit(sock, self.fuzz_node, edge, target)
except Exception, e:
error_handler(e, "failed transmitting fuzz node", target, sock)
continue
# if we reach this point the send was successful for break out of the while(1).
break
# if the user registered a post-send function, pass it the sock and let it do the deed.
# we do this outside the try/except loop because if our fuzz causes a crash then the post_send()
# will likely fail and we don't want to sit in an endless loop.
try:
self.post_send(sock)
except Exception, e:
error_handler(e, "post_send() failed", target, sock)
# done with the socket.
sock.close()
# delay in between test cases.
self.logger.info("sleeping for %f seconds" % self.sleep_time)
time.sleep(self.sleep_time)
# poll the PED-RPC endpoints (netmon, procmon etc...) for the target.
self.poll_pedrpc(target)
# serialize the current session state to disk.
self.export_file()
# recursively fuzz the remainder of the nodes in the session graph.
self.fuzz(self.fuzz_node, path)
# finished with the last node on the path, pop it off the path stack.
if path:
path.pop()
# loop to keep the main thread running and be able to receive signals
if self.signal_module:
# wait for a signal only if fuzzing is finished (this function is recursive)
# if fuzzing is not finished, web interface thread will catch it
if self.total_mutant_index == self.total_num_mutations:
import signal
try:
while True:
signal.pause()
except AttributeError:
# signal.pause() is missing for Windows; wait 1ms and loop instead
while True:
time.sleep(0.001)
####################################################################################################################
def import_file (self):
'''
Load varous object values from disk.
@see: export_file()
'''
try:
fh = open(self.session_filename, "rb")
data = cPickle.loads(zlib.decompress(fh.read()))
fh.close()
except:
return
# update the skip variable to pick up fuzzing from last test case.
self.skip = data["total_mutant_index"]
self.session_filename = data["session_filename"]
self.sleep_time = data["sleep_time"]
self.restart_sleep_time = data["restart_sleep_time"]
self.proto = data["proto"]
self.restart_interval = data["restart_interval"]
self.timeout = data["timeout"]
self.web_port = data["web_port"]
self.crash_threshold = data["crash_threshold"]
self.total_num_mutations = data["total_num_mutations"]
self.total_mutant_index = data["total_mutant_index"]
self.netmon_results = data["netmon_results"]
self.procmon_results = data["procmon_results"]
self.protmon_results = data["protmon_results"]
self.pause_flag = data["pause_flag"]
####################################################################################################################
#def log (self, msg, level=1):
'''
If the supplied message falls under the current log level, print the specified message to screen.
@type msg: String
@param msg: Message to log
'''
#
#if self.log_level >= level:
#print "[%s] %s" % (time.strftime("%I:%M.%S"), msg)
####################################################################################################################
def num_mutations (self, this_node=None, path=[]):
'''
Number of total mutations in the graph. The logic of this routine is identical to that of fuzz(). See fuzz()
for inline comments. The member varialbe self.total_num_mutations is updated appropriately by this routine.
@type this_node: request (node)
@param this_node: (Optional, def=None) Current node that is being fuzzed.
@type path: List
@param path: (Optional, def=[]) Nodes along the path to the current one being fuzzed.
@rtype: Integer
@return: Total number of mutations in this session.
'''
if not this_node:
this_node = self.root
self.total_num_mutations = 0
for edge in self.edges_from(this_node.id):
next_node = self.nodes[edge.dst]
self.total_num_mutations += next_node.num_mutations()
if edge.src != self.root.id:
path.append(edge)
self.num_mutations(next_node, path)
# finished with the last node on the path, pop it off the path stack.
if path:
path.pop()
return self.total_num_mutations
####################################################################################################################
def pause (self):
'''
If thet pause flag is raised, enter an endless loop until it is lowered.
'''
while 1:
if self.pause_flag:
time.sleep(1)
else:
break
####################################################################################################################
def poll_pedrpc (self, target):
'''
Poll the PED-RPC endpoints (netmon, procmon etc...) for the target.
@type target: session.target
@param target: Session target whose PED-RPC services we are polling
'''
# kill the pcap thread and see how many bytes the sniffer recorded.
if target.netmon:
bytes = target.netmon.post_send()
self.logger.info("netmon captured %d bytes for test case #%d" % (bytes, self.total_mutant_index))
self.netmon_results[self.total_mutant_index] = bytes
# check if our fuzz crashed the target. procmon.post_send() returns False if the target access violated.
if target.procmon and not target.procmon.post_send():
self.logger.info("procmon detected access violation on test case #%d" % self.total_mutant_index)
# retrieve the primitive that caused the crash and increment it's individual crash count.
self.crashing_primitives[self.fuzz_node.mutant] = self.crashing_primitives.get(self.fuzz_node.mutant, 0) + 1
# notify with as much information as possible.
if self.fuzz_node.mutant.name:
msg = "primitive name: %s, " % self.fuzz_node.mutant.name
else:
msg = "primitive lacks a name, "
msg += "type: %s, default value: %s" % (self.fuzz_node.mutant.s_type, self.fuzz_node.mutant.original_value)
self.logger.info(msg)
# print crash synopsis
self.procmon_results[self.total_mutant_index] = target.procmon.get_crash_synopsis()
self.logger.info(self.procmon_results[self.total_mutant_index].split("\n")[0])
# if the user-supplied crash threshold is reached, exhaust this node.
if self.crashing_primitives[self.fuzz_node.mutant] >= self.crash_threshold:
# as long as we're not a group and not a repeat.
if not isinstance(self.fuzz_node.mutant, primitives.group):
if not isinstance(self.fuzz_node.mutant, blocks.repeat):
skipped = self.fuzz_node.mutant.exhaust()
self.logger.warning("crash threshold reached for this primitive, exhausting %d mutants." % skipped)
self.total_mutant_index += skipped
self.fuzz_node.mutant_index += skipped
# start the target back up.
# If it returns False, stop the test
if self.restart_target(target, stop_first=False) == False:
self.logger.critical("Restarting the target failed, exiting.")
self.export_file()
try:
self.thread.join()
except:
self.logger.debug("No server launched")
sys.exit(0)
####################################################################################################################
def post_send (self, sock):
'''
Overload or replace this routine to specify actions to run after to each fuzz request. The order of events is
as follows::
pre_send() - req - callback ... req - callback - post_send()
When fuzzing RPC for example, register this method to tear down the RPC request.
@see: pre_send()
@type sock: Socket
@param sock: Connected socket to target
'''
# default to doing nothing.
pass
####################################################################################################################
def pre_send (self, sock):
'''
Overload or replace this routine to specify actions to run prior to each fuzz request. The order of events is
as follows::
pre_send() - req - callback ... req - callback - post_send()
When fuzzing RPC for example, register this method to establish the RPC bind.
@see: pre_send()
@type sock: Socket
@param sock: Connected socket to target
'''
# default to doing nothing.
pass
####################################################################################################################
def restart_target (self, target, stop_first=True):
'''
Restart the fuzz target. If a VMControl is available revert the snapshot, if a process monitor is available
restart the target process. Otherwise, do nothing.
@type target: session.target
@param target: Target we are restarting
'''
# vm restarting is the preferred method so try that first.
if target.vmcontrol:
self.logger.warning("restarting target virtual machine")
target.vmcontrol.restart_target()
# if we have a connected process monitor, restart the target process.
elif target.procmon:
self.logger.warning("restarting target process")
if stop_first:
target.procmon.stop_target()
if not target.procmon.start_target():
return False
# give the process a few seconds to settle in.
time.sleep(3)
# otherwise all we can do is wait a while for the target to recover on its own.
else:
self.logger.error("no vmcontrol or procmon channel available ... sleeping for %d seconds" % self.restart_sleep_time)
time.sleep(self.restart_sleep_time)
# TODO: should be good to relaunch test for crash before returning False
return False
# pass specified target parameters to the PED-RPC server to re-establish connections.
target.pedrpc_connect()
####################################################################################################################
def server_init (self):
'''
Called by fuzz() on first run (not on recursive re-entry) to initialize variables, web interface, etc...
'''
self.total_mutant_index = 0
self.total_num_mutations = self.num_mutations()
# web interface thread doesn't catch KeyboardInterrupt
# add a signal handler, and exit on SIGINT
# TODO: should wait for the end of the ongoing test case, and stop gracefully netmon and procmon
# TODO: doesn't work on OS where the signal module isn't available
try:
import signal
self.signal_module = True
except:
self.signal_module = False
if self.signal_module:
def exit_abruptly(signal, frame):
'''Save current settings (just in case) and exit'''
self.export_file()
self.logger.critical("SIGINT received ... exiting")
try:
self.thread.join()
except:
self.logger.debug( "No server launched")
sys.exit(0)
signal.signal(signal.SIGINT, exit_abruptly)
# spawn the web interface.
self.thread = web_interface_thread(self)
self.thread.start()
####################################################################################################################
def transmit (self, sock, node, edge, target):
'''
Render and transmit a node, process callbacks accordingly.
@type sock: Socket
@param sock: Socket to transmit node on
@type node: Request (Node)
@param node: Request/Node to transmit
@type edge: Connection (pgraph.edge)
@param edge: Edge along the current fuzz path from "node" to next node.
@type target: session.target
@param target: Target we are transmitting to
'''
data = None
# if the edge has a callback, process it. the callback has the option to render the node, modify it and return.
if edge.callback:
data = edge.callback(self, node, edge, sock)
self.logger.info("xmitting: [%d.%d]" % (node.id, self.total_mutant_index))
# if no data was returned by the callback, render the node here.
if not data:
data = node.render()
# if data length is > 65507 and proto is UDP, truncate it.
# TODO: this logic does not prevent duplicate test cases, need to address this in the future.
if self.proto == socket.SOCK_DGRAM:
# max UDP packet size.
# TODO: anyone know how to determine this value smarter?
# - See http://stackoverflow.com/questions/25841/maximum-buffer-length-for-sendto to fix this
MAX_UDP = 65507
if os.name != "nt" and os.uname()[0] == "Darwin":
MAX_UDP = 9216
if len(data) > MAX_UDP:
self.logger.debug("Too much data for UDP, truncating to %d bytes" % MAX_UDP)
data = data[:MAX_UDP]
try:
if self.proto == socket.SOCK_STREAM:
sock.send(data)
else:
sock.sendto(data, (self.targets[0].host, self.targets[0].port))
self.logger.debug("Packet sent : " + repr(data))
except Exception, inst:
self.logger.error("Socket error, send: %s" % inst)
if self.proto == (socket.SOCK_STREAM or socket.SOCK_DGRAM):
# TODO: might have a need to increase this at some point. (possibly make it a class parameter)
try:
self.last_recv = sock.recv(10000)
except Exception, e:
self.last_recv = ""
else:
self.last_recv = ""
if len(self.last_recv) > 0:
self.logger.debug("received: [%d] %s" % (len(self.last_recv), repr(self.last_recv)))
else:
self.logger.warning("Nothing received on socket.")
# Increment individual crash count
self.crashing_primitives[self.fuzz_node.mutant] = self.crashing_primitives.get(self.fuzz_node.mutant,0) +1
# Note crash information
self.protmon_results[self.total_mutant_index] = data ;
#print self.protmon_results
########################################################################################################################
class web_interface_handler (BaseHTTPServer.BaseHTTPRequestHandler):
def __init__(self, request, client_address, server):
BaseHTTPServer.BaseHTTPRequestHandler.__init__(self, request, client_address, server)
self.session = None
def commify (self, number):
number = str(number)
processing = 1
regex = re.compile(r"^(-?\d+)(\d{3})")
while processing:
(number, processing) = regex.subn(r"\1,\2",number)
return number
def do_GET (self):
self.do_everything()
def do_HEAD (self):
self.do_everything()
def do_POST (self):
self.do_everything()
def do_everything (self):
if "pause" in self.path:
self.session.pause_flag = True
if "resume" in self.path:
self.session.pause_flag = False
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
if "view_crash" in self.path:
response = self.view_crash(self.path)
elif "view_pcap" in self.path:
response = self.view_pcap(self.path)
else:
response = self.view_index()
self.wfile.write(response)
def log_error (self, *args, **kwargs):
pass
def log_message (self, *args, **kwargs):
pass
def version_string (self):
return "Sulley Fuzz Session"
def view_crash (self, path):
test_number = int(path.split("/")[-1])
return "<html><pre>%s</pre></html>" % self.session.procmon_results[test_number]
def view_pcap (self, path):
return path
def view_index (self):
response = """
<html>
<head>
<meta http-equiv="refresh" content="5">
<title>Sulley Fuzz Control</title>
<style>
a:link {color: #FF8200; text-decoration: none;}
a:visited {color: #FF8200; text-decoration: none;}
a:hover {color: #C5C5C5; text-decoration: none;}
body
{
background-color: #000000;
font-family: Arial, Helvetica, sans-serif;
font-size: 12px;
color: #FFFFFF;
}
td
{
font-family: Arial, Helvetica, sans-serif;
font-size: 12px;
color: #A0B0B0;
}
.fixed
{
font-family: Courier New;
font-size: 12px;
color: #A0B0B0;
}
.input
{
font-family: Arial, Helvetica, sans-serif;
font-size: 11px;
color: #FFFFFF;
background-color: #333333;
border: thin none;
height: 20px;
}
</style>
</head>
<body>
<center>
<table border=0 cellpadding=5 cellspacing=0 width=750><tr><td>
<!-- begin bounding table -->
<table border=0 cellpadding=5 cellspacing=0 width="100%%">
<tr bgcolor="#333333">
<td><div style="font-size: 20px;">Sulley Fuzz Control</div></td>
<td align=right><div style="font-weight: bold; font-size: 20px;">%(status)s</div></td>
</tr>
<tr bgcolor="#111111">
<td colspan=2 align="center">
<table border=0 cellpadding=0 cellspacing=5>
<tr bgcolor="#111111">
<td><b>Total:</b></td>
<td>%(total_mutant_index)s</td>
<td>of</td>
<td>%(total_num_mutations)s</td>
<td class="fixed">%(progress_total_bar)s</td>
<td>%(progress_total)s</td>
</tr>
<tr bgcolor="#111111">
<td><b>%(current_name)s:</b></td>
<td>%(current_mutant_index)s</td>
<td>of</td>
<td>%(current_num_mutations)s</td>
<td class="fixed">%(progress_current_bar)s</td>
<td>%(progress_current)s</td>
</tr>
</table>
</td>
</tr>
<tr>
<td>
<form method=get action="/pause">
<input class="input" type="submit" value="Pause">
</form>
</td>
<td align=right>
<form method=get action="/resume">
<input class="input" type="submit" value="Resume">
</form>
</td>
</tr>
</table>
<!-- begin procmon results -->
<table border=0 cellpadding=5 cellspacing=0 width="100%%">
<tr bgcolor="#333333">
<td nowrap>Test Case #</td>
<td>Crash Synopsis</td>
<td nowrap>Captured Bytes</td>
</tr>
"""
keys = self.session.procmon_results.keys()
keys.sort()
for key in keys:
val = self.session.procmon_results[key]
bytes = " "
if self.session.netmon_results.has_key(key):
bytes = self.commify(self.session.netmon_results[key])
response += '<tr><td class="fixed"><a href="/view_crash/%d">%06d</a></td><td>%s</td><td align=right>%s</td></tr>' % (key, key, val.split("\n")[0], bytes)
response += """
<!-- end procmon results -->
</table>
<!-- end bounding table -->
</td></tr></table>
</center>
</body>
</html>
"""
# what is the fuzzing status.
if self.session.pause_flag:
status = "<font color=red>PAUSED</font>"
else:
status = "<font color=green>RUNNING</font>"
# if there is a current fuzz node.
if self.session.fuzz_node:
# which node (request) are we currently fuzzing.
if self.session.fuzz_node.name:
current_name = self.session.fuzz_node.name
else:
current_name = "[N/A]"
# render sweet progress bars.
progress_current = float(self.session.fuzz_node.mutant_index) / float(self.session.fuzz_node.num_mutations())
num_bars = int(progress_current * 50)
progress_current_bar = "[" + "=" * num_bars + " " * (50 - num_bars) + "]"
progress_current = "%.3f%%" % (progress_current * 100)
progress_total = float(self.session.total_mutant_index) / float(self.session.total_num_mutations)
num_bars = int(progress_total * 50)
progress_total_bar = "[" + "=" * num_bars + " " * (50 - num_bars) + "]"
progress_total = "%.3f%%" % (progress_total * 100)
response %= \
{
"current_mutant_index" : self.commify(self.session.fuzz_node.mutant_index),
"current_name" : current_name,
"current_num_mutations" : self.commify(self.session.fuzz_node.num_mutations()),
"progress_current" : progress_current,
"progress_current_bar" : progress_current_bar,
"progress_total" : progress_total,
"progress_total_bar" : progress_total_bar,
"status" : status,
"total_mutant_index" : self.commify(self.session.total_mutant_index),
"total_num_mutations" : self.commify(self.session.total_num_mutations),
}
else:
response %= \
{
"current_mutant_index" : "",
"current_name" : "",
"current_num_mutations" : "",
"progress_current" : "",
"progress_current_bar" : "",
"progress_total" : "",
"progress_total_bar" : "",
"status" : "<font color=yellow>UNAVAILABLE</font>",
"total_mutant_index" : "",
"total_num_mutations" : "",
}
return response
########################################################################################################################
class web_interface_server (BaseHTTPServer.HTTPServer):
'''
http://docs.python.org/lib/module-BaseHTTPServer.html
'''
def __init__(self, server_address, RequestHandlerClass, session):
BaseHTTPServer.HTTPServer.__init__(self, server_address, RequestHandlerClass)
self.RequestHandlerClass.session = session
########################################################################################################################
class web_interface_thread (threading.Thread):
def __init__ (self, session):
threading.Thread.__init__(self, name="SulleyWebServer")
self._stopevent = threading.Event()
self.session = session
self.server = None
def run (self):
self.server = web_interface_server(('', self.session.web_port), web_interface_handler, self.session)
while not self._stopevent.isSet():
self.server.handle_request()
def join(self, timeout=None):
# A little dirty but no other solution afaik
self._stopevent.set()
conn = httplib.HTTPConnection("localhost:%d" % self.session.web_port)
conn.request("GET", "/")
conn.getresponse()
| 48,671
|
Python
|
.py
| 940
| 37.501064
| 165
| 0.510676
|
OpenRCE/sulley
| 1,416
| 338
| 56
|
GPL-2.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
16,005
|
pedrpc.py
|
OpenRCE_sulley/sulley/pedrpc.py
|
import sys
import struct
import time
import socket
import cPickle
########################################################################################################################
class client:
def __init__ (self, host, port):
self.__host = host
self.__port = port
self.__dbg_flag = False
self.__server_sock = None
self.__retry = 0
self.NOLINGER = struct.pack('ii', 1, 0)
####################################################################################################################
def __getattr__ (self, method_name):
'''
This routine is called by default when a requested attribute (or method) is accessed that has no definition.
Unfortunately __getattr__ only passes the requested method name and not the arguments. So we extend the
functionality with a little lambda magic to the routine method_missing(). Which is actually how Ruby handles
missing methods by default ... with arguments. Now we are just as cool as Ruby.
@type method_name: String
@param method_name: The name of the requested and undefined attribute (or method in our case).
@rtype: Lambda
@return: Lambda magic passing control (and in turn the arguments we want) to self.method_missing().
'''
return lambda *args, **kwargs: self.__method_missing(method_name, *args, **kwargs)
####################################################################################################################
def __connect (self):
'''
Connect to the PED-RPC server.
'''
# if we have a pre-existing server socket, ensure it's closed.
self.__disconnect()
# connect to the server, timeout on failure.
try:
self.__server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.__server_sock.settimeout(3.0)
self.__server_sock.connect((self.__host, self.__port))
except:
if self.__retry != 5:
self.__retry += 1
time.sleep(5)
self.__connect()
else:
sys.stderr.write("PED-RPC> unable to connect to server %s:%d\n" % (self.__host, self.__port))
raise Exception
# disable timeouts and lingering.
self.__server_sock.settimeout(None)
self.__server_sock.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, self.NOLINGER)
####################################################################################################################
def __disconnect (self):
'''
Ensure the socket is torn down.
'''
if self.__server_sock != None:
self.__debug("closing server socket")
self.__server_sock.close()
self.__server_sock = None
####################################################################################################################
def __debug (self, msg):
if self.__dbg_flag:
print "PED-RPC> %s" % msg
####################################################################################################################
def __method_missing (self, method_name, *args, **kwargs):
'''
See the notes for __getattr__ for related notes. This method is called, in the Ruby fashion, with the method
name and arguments for any requested but undefined class method.
@type method_name: String
@param method_name: The name of the requested and undefined attribute (or method in our case).
@type *args: Tuple
@param *args: Tuple of arguments.
@type **kwargs Dictionary
@param **kwargs: Dictioanry of arguments.
@rtype: Mixed
@return: Return value of the mirrored method.
'''
# return a value so lines of code like the following work:
# x = pedrpc.client(host, port)
# if x:
# x.do_something()
if method_name == "__nonzero__":
return 1
# ignore all other attempts to access a private member.
if method_name.startswith("__"):
return
# connect to the PED-RPC server.
self.__connect()
# transmit the method name and arguments.
while 1:
try:
self.__pickle_send((method_name, (args, kwargs)))
break
except:
# re-connect to the PED-RPC server if the sock died.
self.__connect()
# snag the return value.
ret = self.__pickle_recv()
# close the sock and return.
self.__disconnect()
return ret
####################################################################################################################
def __pickle_recv (self):
'''
This routine is used for marshaling arbitrary data from the PyDbg server. We can send pretty much anything here.
For example a tuple containing integers, strings, arbitrary objects and structures. Our "protocol" is a simple
length-value protocol where each datagram is prefixed by a 4-byte length of the data to be received.
@raise pdx: An exception is raised if the connection was severed.
@rtype: Mixed
@return: Whatever is received over the socket.
'''
try:
# TODO: this should NEVER fail, but alas, it does and for the time being i can't figure out why.
# it gets worse. you would think that simply returning here would break things, but it doesn't.
# gotta track this down at some point.
length = struct.unpack("<L", self.__server_sock.recv(4))[0]
except:
return
try:
received = ""
while length:
chunk = self.__server_sock.recv(length)
received += chunk
length -= len(chunk)
except:
sys.stderr.write("PED-RPC> connection to server severed during recv()\n")
raise Exception
return cPickle.loads(received)
####################################################################################################################
def __pickle_send (self, data):
'''
This routine is used for marshaling arbitrary data to the PyDbg server. We can send pretty much anything here.
For example a tuple containing integers, strings, arbitrary objects and structures. Our "protocol" is a simple
length-value protocol where each datagram is prefixed by a 4-byte length of the data to be received.
@type data: Mixed
@param data: Data to marshal and transmit. Data can *pretty much* contain anything you throw at it.
@raise pdx: An exception is raised if the connection was severed.
'''
data = cPickle.dumps(data, protocol=2)
self.__debug("sending %d bytes" % len(data))
try:
self.__server_sock.send(struct.pack("<L", len(data)))
self.__server_sock.send(data)
except:
sys.stderr.write("PED-RPC> connection to server severed during send()\n")
raise Exception
########################################################################################################################
class server:
def __init__ (self, host, port):
self.__host = host
self.__port = port
self.__dbg_flag = False
self.__client_sock = None
self.__client_address = None
try:
# create a socket and bind to the specified port.
self.__server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.__server.settimeout(None)
self.__server.bind((host, port))
self.__server.listen(1)
except:
sys.stderr.write("unable to bind to %s:%d\n" % (host, port))
sys.exit(1)
####################################################################################################################
def __disconnect (self):
'''
Ensure the socket is torn down.
'''
if self.__client_sock != None:
self.__debug("closing client socket")
self.__client_sock.close()
self.__client_sock = None
####################################################################################################################
def __debug (self, msg):
if self.__dbg_flag:
print "PED-RPC> %s" % msg
####################################################################################################################
def __pickle_recv (self):
'''
This routine is used for marshaling arbitrary data from the PyDbg server. We can send pretty much anything here.
For example a tuple containing integers, strings, arbitrary objects and structures. Our "protocol" is a simple
length-value protocol where each datagram is prefixed by a 4-byte length of the data to be received.
@raise pdx: An exception is raised if the connection was severed.
@rtype: Mixed
@return: Whatever is received over the socket.
'''
try:
length = struct.unpack("<L", self.__client_sock.recv(4))[0]
received = ""
while length:
chunk = self.__client_sock.recv(length)
received += chunk
length -= len(chunk)
except:
sys.stderr.write("PED-RPC> connection client severed during recv()\n")
raise Exception
return cPickle.loads(received)
####################################################################################################################
def __pickle_send (self, data):
'''
This routine is used for marshaling arbitrary data to the PyDbg server. We can send pretty much anything here.
For example a tuple containing integers, strings, arbitrary objects and structures. Our "protocol" is a simple
length-value protocol where each datagram is prefixed by a 4-byte length of the data to be received.
@type data: Mixed
@param data: Data to marshal and transmit. Data can *pretty much* contain anything you throw at it.
@raise pdx: An exception is raised if the connection was severed.
'''
data = cPickle.dumps(data, protocol=2)
self.__debug("sending %d bytes" % len(data))
try:
self.__client_sock.send(struct.pack("<L", len(data)))
self.__client_sock.send(data)
except:
sys.stderr.write("PED-RPC> connection to client severed during send()\n")
raise Exception
####################################################################################################################
def serve_forever (self):
self.__debug("serving up a storm")
while 1:
# close any pre-existing socket.
self.__disconnect()
# accept a client connection.
(self.__client_sock, self.__client_address) = self.__server.accept()
self.__debug("accepted connection from %s:%d" % (self.__client_address[0], self.__client_address[1]))
# recieve the method name and arguments, continue on socket disconnect.
try:
(method_name, (args, kwargs)) = self.__pickle_recv()
self.__debug("%s(args=%s, kwargs=%s)" % (method_name, args, kwargs))
except:
continue
try:
# resolve a pointer to the requested method and call it.
exec("method_pointer = self.%s" % method_name)
ret = method_pointer(*args, **kwargs)
except AttributeError:
# if the method can't be found notify the user and raise an error
sys.stderr.write("PED-RPC> remote method %s cannot be found\n" % method_name)
continue
# transmit the return value to the client, continue on socket disconnect.
try:
self.__pickle_send(ret)
except:
continue
| 12,383
|
Python
|
.py
| 243
| 40.534979
| 120
| 0.504555
|
OpenRCE/sulley
| 1,416
| 338
| 56
|
GPL-2.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
16,006
|
__init__.py
|
OpenRCE_sulley/sulley/__init__.py
|
import sulley.blocks
import sulley.instrumentation
import sulley.legos
import sulley.pedrpc
import sulley.primitives
import sulley.sex
import sulley.sessions
import sulley.utils
BIG_ENDIAN = ">"
LITTLE_ENDIAN = "<"
########################################################################################################################
### REQUEST MANAGEMENT
########################################################################################################################
def s_get (name=None):
'''
Return the request with the specified name or the current request if name is not specified. Use this to switch from
global function style request manipulation to direct object manipulation. Example::
req = s_get("HTTP BASIC")
print req.num_mutations()
The selected request is also set as the default current. (ie: s_switch(name) is implied).
@type name: String
@param name: (Optional, def=None) Name of request to return or current request if name is None.
@rtype: blocks.request
@return: The requested request.
'''
if not name:
return blocks.CURRENT
# ensure this gotten request is the new current.
s_switch(name)
if not blocks.REQUESTS.has_key(name):
raise sex.SullyRuntimeError("blocks.REQUESTS NOT FOUND: %s" % name)
return blocks.REQUESTS[name]
def s_initialize (name):
'''
Initialize a new block request. All blocks / primitives generated after this call apply to the named request.
Use s_switch() to jump between factories.
@type name: String
@param name: Name of request
'''
if blocks.REQUESTS.has_key(name):
raise sex.SullyRuntimeError("blocks.REQUESTS ALREADY EXISTS: %s" % name)
blocks.REQUESTS[name] = blocks.request(name)
blocks.CURRENT = blocks.REQUESTS[name]
def s_mutate ():
'''
Mutate the current request and return False if mutations are exhausted, in which case the request has been reverted
back to its normal form.
@rtype: Boolean
@return: True on mutation success, False if mutations exhausted.
'''
return blocks.CURRENT.mutate()
def s_num_mutations ():
'''
Determine the number of repetitions we will be making.
@rtype: Integer
@return: Number of mutated forms this primitive can take.
'''
return blocks.CURRENT.num_mutations()
def s_render ():
'''
Render out and return the entire contents of the current request.
@rtype: Raw
@return: Rendered contents
'''
return blocks.CURRENT.render()
def s_switch (name):
'''
Change the currect request to the one specified by "name".
@type name: String
@param name: Name of request
'''
if not blocks.REQUESTS.has_key(name):
raise sex.SullyRuntimeError("blocks.REQUESTS NOT FOUND: %s" % name)
blocks.CURRENT = blocks.REQUESTS[name]
########################################################################################################################
### BLOCK MANAGEMENT
########################################################################################################################
def s_block_start (name, group=None, encoder=None, dep=None, dep_value=None, dep_values=[], dep_compare="=="):
'''
Open a new block under the current request. This routine always returns True so you can make your fuzzer pretty
with indenting::
if s_block_start("header"):
s_static("\\x00\\x01")
if s_block_start("body"):
...
@type name: String
@param name: Name of block being opened
@type group: String
@param group: (Optional, def=None) Name of group to associate this block with
@type encoder: Function Pointer
@param encoder: (Optional, def=None) Optional pointer to a function to pass rendered data to prior to return
@type dep: String
@param dep: (Optional, def=None) Optional primitive whose specific value this block is dependant on
@type dep_value: Mixed
@param dep_value: (Optional, def=None) Value that field "dep" must contain for block to be rendered
@type dep_values: List of Mixed Types
@param dep_values: (Optional, def=[]) Values that field "dep" may contain for block to be rendered
@type dep_compare: String
@param dep_compare: (Optional, def="==") Comparison method to use on dependency (==, !=, >, >=, <, <=)
'''
block = blocks.block(name, blocks.CURRENT, group, encoder, dep, dep_value, dep_values, dep_compare)
blocks.CURRENT.push(block)
return True
def s_block_end (name=None):
'''
Close the last opened block. Optionally specify the name of the block being closed (purely for aesthetic purposes).
@type name: String
@param name: (Optional, def=None) Name of block to closed.
'''
blocks.CURRENT.pop()
def s_checksum (block_name, algorithm="crc32", length=0, endian="<", name=None):
'''
Create a checksum block bound to the block with the specified name. You *can not* create a checksum for any
currently open blocks.
@type block_name: String
@param block_name: Name of block to apply sizer to
@type algorithm: String
@param algorithm: (Optional, def=crc32) Checksum algorithm to use. (crc32, adler32, md5, sha1)
@type length: Integer
@param length: (Optional, def=0) Length of checksum, specify 0 to auto-calculate
@type endian: Character
@param endian: (Optional, def=LITTLE_ENDIAN) Endianess of the bit field (LITTLE_ENDIAN: <, BIG_ENDIAN: >)
@type name: String
@param name: Name of this checksum field
'''
# you can't add a checksum for a block currently in the stack.
if block_name in blocks.CURRENT.block_stack:
raise sex.SullyRuntimeError("CAN N0T ADD A CHECKSUM FOR A BLOCK CURRENTLY IN THE STACK")
checksum = blocks.checksum(block_name, blocks.CURRENT, algorithm, length, endian, name)
blocks.CURRENT.push(checksum)
def s_repeat (block_name, min_reps=0, max_reps=None, step=1, variable=None, fuzzable=True, name=None):
'''
Repeat the rendered contents of the specified block cycling from min_reps to max_reps counting by step. By
default renders to nothing. This block modifier is useful for fuzzing overflows in table entries. This block
modifier MUST come after the block it is being applied to.
@see: Aliases: s_repeater()
@type block_name: String
@param block_name: Name of block to apply sizer to
@type min_reps: Integer
@param min_reps: (Optional, def=0) Minimum number of block repetitions
@type max_reps: Integer
@param max_reps: (Optional, def=None) Maximum number of block repetitions
@type step: Integer
@param step: (Optional, def=1) Step count between min and max reps
@type variable: Sulley Integer Primitive
@param variable: (Optional, def=None) An integer primitive which will specify the number of repitions
@type fuzzable: Boolean
@param fuzzable: (Optional, def=True) Enable/disable fuzzing of this primitive
@type name: String
@param name: (Optional, def=None) Specifying a name gives you direct access to a primitive
'''
repeat = blocks.repeat(block_name, blocks.CURRENT, min_reps, max_reps, step, variable, fuzzable, name)
blocks.CURRENT.push(repeat)
def s_size (block_name, offset=0, length=4, endian="<", format="binary", inclusive=False, signed=False, math=None, fuzzable=False, name=None):
'''
Create a sizer block bound to the block with the specified name. You *can not* create a sizer for any
currently open blocks.
@see: Aliases: s_sizer()
@type block_name: String
@param block_name: Name of block to apply sizer to
@type offset: Integer
@param offset: (Optional, def=0) Offset to calculated size of block
@type length: Integer
@param length: (Optional, def=4) Length of sizer
@type endian: Character
@param endian: (Optional, def=LITTLE_ENDIAN) Endianess of the bit field (LITTLE_ENDIAN: <, BIG_ENDIAN: >)
@type format: String
@param format: (Optional, def=binary) Output format, "binary" or "ascii"
@type inclusive: Boolean
@param inclusive: (Optional, def=False) Should the sizer count its own length?
@type signed: Boolean
@param signed: (Optional, def=False) Make size signed vs. unsigned (applicable only with format="ascii")
@type math: Function
@param math: (Optional, def=None) Apply the mathematical operations defined in this function to the size
@type fuzzable: Boolean
@param fuzzable: (Optional, def=False) Enable/disable fuzzing of this sizer
@type name: String
@param name: Name of this sizer field
'''
# you can't add a size for a block currently in the stack.
if block_name in blocks.CURRENT.block_stack:
raise sex.SullyRuntimeError("CAN NOT ADD A SIZE FOR A BLOCK CURRENTLY IN THE STACK")
size = blocks.size(block_name, blocks.CURRENT, offset, length, endian, format, inclusive, signed, math, fuzzable, name)
blocks.CURRENT.push(size)
def s_update (name, value):
'''
Update the value of the named primitive in the currently open request.
@type name: String
@param name: Name of object whose value we wish to update
@type value: Mixed
@param value: Updated value
'''
if not blocks.CURRENT.names.has_key(name):
raise sex.SullyRuntimeError("NO OBJECT WITH NAME '%s' FOUND IN CURRENT REQUEST" % name)
blocks.CURRENT.names[name].value = value
########################################################################################################################
### PRIMITIVES
########################################################################################################################
def s_binary (value, name=None):
'''
Parse a variable format binary string into a static value and push it onto the current block stack.
@type value: String
@param value: Variable format binary string
@type name: String
@param name: (Optional, def=None) Specifying a name gives you direct access to a primitive
'''
# parse the binary string into.
parsed = value
parsed = parsed.replace(" ", "")
parsed = parsed.replace("\t", "")
parsed = parsed.replace("\r", "")
parsed = parsed.replace("\n", "")
parsed = parsed.replace(",", "")
parsed = parsed.replace("0x", "")
parsed = parsed.replace("\\x", "")
value = ""
while parsed:
pair = parsed[:2]
parsed = parsed[2:]
value += chr(int(pair, 16))
static = primitives.static(value, name)
blocks.CURRENT.push(static)
def s_delim (value, fuzzable=True, name=None):
'''
Push a delimiter onto the current block stack.
@type value: Character
@param value: Original value
@type fuzzable: Boolean
@param fuzzable: (Optional, def=True) Enable/disable fuzzing of this primitive
@type name: String
@param name: (Optional, def=None) Specifying a name gives you direct access to a primitive
'''
delim = primitives.delim(value, fuzzable, name)
blocks.CURRENT.push(delim)
def s_group (name, values):
'''
This primitive represents a list of static values, stepping through each one on mutation. You can tie a block
to a group primitive to specify that the block should cycle through all possible mutations for *each* value
within the group. The group primitive is useful for example for representing a list of valid opcodes.
@type name: String
@param name: Name of group
@type values: List or raw data
@param values: List of possible raw values this group can take.
'''
group = primitives.group(name, values)
blocks.CURRENT.push(group)
def s_lego (lego_type, value=None, options={}):
'''
Legos are pre-built blocks... TODO: finish this doc
'''
# as legos are blocks they must have a name.
# generate a unique name for this lego.
name = "LEGO_%08x" % len(blocks.CURRENT.names)
if not legos.BIN.has_key(lego_type):
raise sex.SullyRuntimeError("INVALID LEGO TYPE SPECIFIED: %s" % lego_type)
lego = legos.BIN[lego_type](name, blocks.CURRENT, value, options)
# push the lego onto the stack and immediately pop to close the block.
blocks.CURRENT.push(lego)
blocks.CURRENT.pop()
def s_random (value, min_length, max_length, num_mutations=25, fuzzable=True, step=None, name=None):
'''
Generate a random chunk of data while maintaining a copy of the original. A random length range can be specified.
For a static length, set min/max length to be the same.
@type value: Raw
@param value: Original value
@type min_length: Integer
@param min_length: Minimum length of random block
@type max_length: Integer
@param max_length: Maximum length of random block
@type num_mutations: Integer
@param num_mutations: (Optional, def=25) Number of mutations to make before reverting to default
@type fuzzable: Boolean
@param fuzzable: (Optional, def=True) Enable/disable fuzzing of this primitive
@type step: Integer
@param step: (Optional, def=None) If not null, step count between min and max reps, otherwise random
@type name: String
@param name: (Optional, def=None) Specifying a name gives you direct access to a primitive
'''
random = primitives.random_data(value, min_length, max_length, num_mutations, fuzzable, step, name)
blocks.CURRENT.push(random)
def s_static (value, name=None):
'''
Push a static value onto the current block stack.
@see: Aliases: s_dunno(), s_raw(), s_unknown()
@type value: Raw
@param value: Raw static data
@type name: String
@param name: (Optional, def=None) Specifying a name gives you direct access to a primitive
'''
static = primitives.static(value, name)
blocks.CURRENT.push(static)
def s_string (value, size=-1, padding="\x00", encoding="ascii", fuzzable=True, max_len=0, name=None):
'''
Push a string onto the current block stack.
@type value: String
@param value: Default string value
@type size: Integer
@param size: (Optional, def=-1) Static size of this field, leave -1 for dynamic.
@type padding: Character
@param padding: (Optional, def="\\x00") Value to use as padding to fill static field size.
@type encoding: String
@param encoding: (Optonal, def="ascii") String encoding, ex: utf_16_le for Microsoft Unicode.
@type fuzzable: Boolean
@param fuzzable: (Optional, def=True) Enable/disable fuzzing of this primitive
@type max_len: Integer
@param max_len: (Optional, def=0) Maximum string length
@type name: String
@param name: (Optional, def=None) Specifying a name gives you direct access to a primitive
'''
s = primitives.string(value, size, padding, encoding, fuzzable, max_len, name)
blocks.CURRENT.push(s)
def s_bit_field (value, width, endian="<", format="binary", signed=False, full_range=False, fuzzable=True, name=None):
'''
Push a variable length bit field onto the current block stack.
@see: Aliases: s_bit(), s_bits()
@type value: Integer
@param value: Default integer value
@type width: Integer
@param width: Width of bit fields
@type endian: Character
@param endian: (Optional, def=LITTLE_ENDIAN) Endianess of the bit field (LITTLE_ENDIAN: <, BIG_ENDIAN: >)
@type format: String
@param format: (Optional, def=binary) Output format, "binary" or "ascii"
@type signed: Boolean
@param signed: (Optional, def=False) Make size signed vs. unsigned (applicable only with format="ascii")
@type full_range: Boolean
@param full_range: (Optional, def=False) If enabled the field mutates through *all* possible values.
@type fuzzable: Boolean
@param fuzzable: (Optional, def=True) Enable/disable fuzzing of this primitive
@type name: String
@param name: (Optional, def=None) Specifying a name gives you direct access to a primitive
'''
bit_field = primitives.bit_field(value, width, None, endian, format, signed, full_range, fuzzable, name)
blocks.CURRENT.push(bit_field)
def s_byte (value, endian="<", format="binary", signed=False, full_range=False, fuzzable=True, name=None):
'''
Push a byte onto the current block stack.
@see: Aliases: s_char()
@type value: Integer
@param value: Default integer value
@type endian: Character
@param endian: (Optional, def=LITTLE_ENDIAN) Endianess of the bit field (LITTLE_ENDIAN: <, BIG_ENDIAN: >)
@type format: String
@param format: (Optional, def=binary) Output format, "binary" or "ascii"
@type signed: Boolean
@param signed: (Optional, def=False) Make size signed vs. unsigned (applicable only with format="ascii")
@type full_range: Boolean
@param full_range: (Optional, def=False) If enabled the field mutates through *all* possible values.
@type fuzzable: Boolean
@param fuzzable: (Optional, def=True) Enable/disable fuzzing of this primitive
@type name: String
@param name: (Optional, def=None) Specifying a name gives you direct access to a primitive
'''
byte = primitives.byte(value, endian, format, signed, full_range, fuzzable, name)
blocks.CURRENT.push(byte)
def s_word (value, endian="<", format="binary", signed=False, full_range=False, fuzzable=True, name=None):
'''
Push a word onto the current block stack.
@see: Aliases: s_short()
@type value: Integer
@param value: Default integer value
@type endian: Character
@param endian: (Optional, def=LITTLE_ENDIAN) Endianess of the bit field (LITTLE_ENDIAN: <, BIG_ENDIAN: >)
@type format: String
@param format: (Optional, def=binary) Output format, "binary" or "ascii"
@type signed: Boolean
@param signed: (Optional, def=False) Make size signed vs. unsigned (applicable only with format="ascii")
@type full_range: Boolean
@param full_range: (Optional, def=False) If enabled the field mutates through *all* possible values.
@type fuzzable: Boolean
@param fuzzable: (Optional, def=True) Enable/disable fuzzing of this primitive
@type name: String
@param name: (Optional, def=None) Specifying a name gives you direct access to a primitive
'''
word = primitives.word(value, endian, format, signed, full_range, fuzzable, name)
blocks.CURRENT.push(word)
def s_dword (value, endian="<", format="binary", signed=False, full_range=False, fuzzable=True, name=None):
'''
Push a double word onto the current block stack.
@see: Aliases: s_long(), s_int()
@type value: Integer
@param value: Default integer value
@type endian: Character
@param endian: (Optional, def=LITTLE_ENDIAN) Endianess of the bit field (LITTLE_ENDIAN: <, BIG_ENDIAN: >)
@type format: String
@param format: (Optional, def=binary) Output format, "binary" or "ascii"
@type signed: Boolean
@param signed: (Optional, def=False) Make size signed vs. unsigned (applicable only with format="ascii")
@type full_range: Boolean
@param full_range: (Optional, def=False) If enabled the field mutates through *all* possible values.
@type fuzzable: Boolean
@param fuzzable: (Optional, def=True) Enable/disable fuzzing of this primitive
@type name: String
@param name: (Optional, def=None) Specifying a name gives you direct access to a primitive
'''
dword = primitives.dword(value, endian, format, signed, full_range, fuzzable, name)
blocks.CURRENT.push(dword)
def s_qword (value, endian="<", format="binary", signed=False, full_range=False, fuzzable=True, name=None):
'''
Push a quad word onto the current block stack.
@see: Aliases: s_double()
@type value: Integer
@param value: Default integer value
@type endian: Character
@param endian: (Optional, def=LITTLE_ENDIAN) Endianess of the bit field (LITTLE_ENDIAN: <, BIG_ENDIAN: >)
@type format: String
@param format: (Optional, def=binary) Output format, "binary" or "ascii"
@type signed: Boolean
@param signed: (Optional, def=False) Make size signed vs. unsigned (applicable only with format="ascii")
@type full_range: Boolean
@param full_range: (Optional, def=False) If enabled the field mutates through *all* possible values.
@type fuzzable: Boolean
@param fuzzable: (Optional, def=True) Enable/disable fuzzing of this primitive
@type name: String
@param name: (Optional, def=None) Specifying a name gives you direct access to a primitive
'''
qword = primitives.qword(value, endian, format, signed, full_range, fuzzable, name)
blocks.CURRENT.push(qword)
########################################################################################################################
### ALIASES
########################################################################################################################
s_dunno = s_raw = s_unknown = s_static
s_sizer = s_size
s_bit = s_bits = s_bit_field
s_char = s_byte
s_short = s_word
s_long = s_int = s_dword
s_double = s_qword
s_repeater = s_repeat
### SPIKE Aliases
def custom_raise (argument, msg):
def _(x):
raise msg, argument(x)
return _
s_intelword = lambda x: s_long(x, endian=LITTLE_ENDIAN)
s_intelhalfword = lambda x: s_short(x, endian=LITTLE_ENDIAN)
s_bigword = lambda x: s_long(x, endian=BIG_ENDIAN)
s_string_lf = custom_raise(ValueError, "NotImplementedError: s_string_lf is not currently implemented, arguments were")
s_string_or_env = custom_raise(ValueError, "NotImplementedError: s_string_or_env is not currently implemented, arguments were")
s_string_repeat = custom_raise(ValueError, "NotImplementedError: s_string_repeat is not currently implemented, arguments were")
s_string_variable = custom_raise(ValueError, "NotImplementedError: s_string_variable is not currently implemented, arguments were")
s_string_variables = custom_raise(ValueError, "NotImplementedError: s_string_variables is not currently implemented, arguments were")
s_binary_repeat = custom_raise(ValueError, "NotImplementedError: s_string_variables is not currently implemented, arguments were")
s_unistring = lambda x: s_string(x, encoding="utf_16_le")
s_unistring_variable = custom_raise(ValueError, "NotImplementedError: s_unistring_variable is not currently implemented, arguments were")
s_xdr_string = custom_raise(ValueError, "LegoNotUtilizedError: XDR strings are available in the XDR lego, arguments were")
def s_cstring (x):
s_string(x)
s_static("\x00")
s_binary_block_size_intel_halfword_plus_variable = custom_raise(ValueError, "SizerNotUtilizedError: Use the s_size primitive for including sizes, arguments were")
s_binary_block_size_halfword_bigendian_variable = custom_raise(ValueError, "SizerNotUtilizedError: Use the s_size primitive for including sizes, arguments were")
s_binary_block_size_word_bigendian_plussome = custom_raise(ValueError, "SizerNotUtilizedError: Use the s_size primitive for including sizes, arguments were")
s_binary_block_size_word_bigendian_variable = custom_raise(ValueError, "SizerNotUtilizedError: Use the s_size primitive for including sizes, arguments were")
s_binary_block_size_halfword_bigendian_mult = custom_raise(ValueError, "SizerNotUtilizedError: Use the s_size primitive for including sizes, arguments were")
s_binary_block_size_intel_halfword_variable = custom_raise(ValueError, "SizerNotUtilizedError: Use the s_size primitive for including sizes, arguments were")
s_binary_block_size_intel_halfword_mult = custom_raise(ValueError, "SizerNotUtilizedError: Use the s_size primitive for including sizes, arguments were")
s_binary_block_size_intel_halfword_plus = custom_raise(ValueError, "SizerNotUtilizedError: Use the s_size primitive for including sizes, arguments were")
s_binary_block_size_halfword_bigendian = custom_raise(ValueError, "SizerNotUtilizedError: Use the s_size primitive for including sizes, arguments were")
s_binary_block_size_word_intel_mult_plus = custom_raise(ValueError, "SizerNotUtilizedError: Use the s_size primitive for including sizes, arguments were")
s_binary_block_size_intel_word_variable = custom_raise(ValueError, "SizerNotUtilizedError: Use the s_size primitive for including sizes, arguments were")
s_binary_block_size_word_bigendian_mult = custom_raise(ValueError, "SizerNotUtilizedError: Use the s_size primitive for including sizes, arguments were")
s_blocksize_unsigned_string_variable = custom_raise(ValueError, "SizerNotUtilizedError: Use the s_size primitive for including sizes, arguments were")
s_binary_block_size_intel_word_plus = custom_raise(ValueError, "SizerNotUtilizedError: Use the s_size primitive for including sizes, arguments were")
s_binary_block_size_intel_halfword = custom_raise(ValueError, "SizerNotUtilizedError: Use the s_size primitive for including sizes, arguments were")
s_binary_block_size_word_bigendian = custom_raise(ValueError, "SizerNotUtilizedError: Use the s_size primitive for including sizes, arguments were")
s_blocksize_signed_string_variable = custom_raise(ValueError, "SizerNotUtilizedError: Use the s_size primitive for including sizes, arguments were")
s_binary_block_size_byte_variable = custom_raise(ValueError, "SizerNotUtilizedError: Use the s_size primitive for including sizes, arguments were")
s_binary_block_size_intel_word = custom_raise(ValueError, "SizerNotUtilizedError: Use the s_size primitive for including sizes, arguments were")
s_binary_block_size_byte_plus = custom_raise(ValueError, "SizerNotUtilizedError: Use the s_size primitive for including sizes, arguments were")
s_binary_block_size_byte_mult = custom_raise(ValueError, "SizerNotUtilizedError: Use the s_size primitive for including sizes, arguments were")
s_blocksize_asciihex_variable = custom_raise(ValueError, "SizerNotUtilizedError: Use the s_size primitive for including sizes, arguments were")
s_binary_block_size_byte = custom_raise(ValueError, "SizerNotUtilizedError: Use the s_size primitive for including sizes, arguments were")
s_blocksize_asciihex = custom_raise(ValueError, "SizerNotUtilizedError: Use the s_size primitive for including sizes, arguments were")
s_blocksize_string = custom_raise(ValueError, "SizerNotUtilizedError: Use the s_size primitive for including sizes, arguments were")
########################################################################################################################
### MISC
########################################################################################################################
def s_hex_dump (data, addr=0):
'''
Return the hex dump of the supplied data starting at the offset address specified.
@type data: Raw
@param data: Data to show hex dump of
@type addr: Integer
@param addr: (Optional, def=0) Offset to start displaying hex dump addresses from
@rtype: String
@return: Hex dump of raw data
'''
dump = slice = ""
for byte in data:
if addr % 16 == 0:
dump += " "
for char in slice:
if ord(char) >= 32 and ord(char) <= 126:
dump += char
else:
dump += "."
dump += "\n%04x: " % addr
slice = ""
dump += "%02x " % ord(byte)
slice += byte
addr += 1
remainder = addr % 16
if remainder != 0:
dump += " " * (16 - remainder) + " "
for char in slice:
if ord(char) >= 32 and ord(char) <= 126:
dump += char
else:
dump += "."
return dump + "\n"
| 28,700
|
Python
|
.py
| 510
| 51.319608
| 162
| 0.659142
|
OpenRCE/sulley
| 1,416
| 338
| 56
|
GPL-2.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
16,007
|
instrumentation.py
|
OpenRCE_sulley/sulley/instrumentation.py
|
class external:
'''
External instrumentation class
Monitor a target which doesn't support a debugger, allowing external
commands to be called
'''
def __init__(self, pre=None, post=None, start=None, stop=None):
'''
@type pre: Function
@param pre: Callback called before each test case
@type post: Function
@param post: Callback called after each test case for instrumentation. Must return True if the target is still active, False otherwise.
@type start: Function
@param start: Callback called to start the target
@type stop: Function
@param stop: Callback called to stop the target
'''
self.pre = pre
self.post = post
self.start = start
self.stop = stop
self.__dbg_flag = False
def alive(self):
'''
Check if this script is alive. Always True.
'''
return True
def debug(self, msg):
'''
Print a debug mesage.
'''
if self.__dbg_flag:
print "EXT-INSTR> %s" % msg
def pre_send(self, test_number):
'''
This routine is called before the fuzzer transmits a test case and ensure the target is alive.
@type test_number: Integer
@param test_number: Test number.
'''
if self.pre:
self.pre()
def post_send(self):
'''
This routine is called after the fuzzer transmits a test case and returns the status of the target.
@rtype: Boolean
@return: Return True if the target is still active, False otherwise.
'''
if self.post:
return self.post()
else:
return True
def start_target(self):
'''
Start up the target. Called when post_send failed.
Returns success of failure of the action
If no method defined, false is returned
'''
if self.start:
return self.start()
else:
return False
def stop_target(self):
'''
Stop the target.
'''
if self.stop:
self.stop()
def get_crash_synopsis(self):
'''
Return the last recorded crash synopsis.
@rtype: String
@return: Synopsis of last recorded crash.
'''
return 'External instrumentation detects a crash...\n'
| 2,452
|
Python
|
.py
| 74
| 24.216216
| 144
| 0.575255
|
OpenRCE/sulley
| 1,416
| 338
| 56
|
GPL-2.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
16,008
|
blocks.py
|
OpenRCE_sulley/sulley/blocks.py
|
import pgraph
import primitives
import sex
from utils.crc16 import CRC16
import zlib
import hashlib
import struct
REQUESTS = {}
CURRENT = None
########################################################################################################################
class request (pgraph.node):
def __init__ (self, name):
'''
Top level container instantiated by s_initialize(). Can hold any block structure or primitive. This can
essentially be thought of as a super-block, root-block, daddy-block or whatever other alias you prefer.
@type name: String
@param name: Name of this request
'''
self.name = name
self.label = name # node label for graph rendering.
self.stack = [] # the request stack.
self.block_stack = [] # list of open blocks, -1 is last open block.
self.closed_blocks = {} # dictionary of closed blocks.
self.callbacks = {} # dictionary of list of sizers / checksums that were unable to complete rendering.
self.names = {} # dictionary of directly accessible primitives.
self.rendered = "" # rendered block structure.
self.mutant_index = 0 # current mutation index.
self.mutant = None # current primitive being mutated.
def mutate (self):
mutated = False
for item in self.stack:
if item.fuzzable and item.mutate():
mutated = True
if not isinstance(item, block):
self.mutant = item
break
if mutated:
self.mutant_index += 1
return mutated
def num_mutations (self):
'''
Determine the number of repetitions we will be making.
@rtype: Integer
@return: Number of mutated forms this primitive can take.
'''
num_mutations = 0
for item in self.stack:
if item.fuzzable:
num_mutations += item.num_mutations()
return num_mutations
def pop (self):
'''
The last open block was closed, so pop it off of the block stack.
'''
if not self.block_stack:
raise sex.SullyRuntimeError("BLOCK STACK OUT OF SYNC")
self.block_stack.pop()
def push (self, item):
'''
Push an item into the block structure. If no block is open, the item goes onto the request stack. otherwise,
the item goes onto the last open blocks stack.
'''
# if the item has a name, add it to the internal dictionary of names.
if hasattr(item, "name") and item.name:
# ensure the name doesn't already exist.
if item.name in self.names.keys():
raise sex.SullyRuntimeError("BLOCK NAME ALREADY EXISTS: %s" % item.name)
self.names[item.name] = item
# if there are no open blocks, the item gets pushed onto the request stack.
# otherwise, the pushed item goes onto the stack of the last opened block.
if not self.block_stack:
self.stack.append(item)
else:
self.block_stack[-1].push(item)
# add the opened block to the block stack.
if isinstance(item, block):
self.block_stack.append(item)
def render (self):
# ensure there are no open blocks lingering.
if self.block_stack:
raise sex.SullyRuntimeError("UNCLOSED BLOCK: %s" % self.block_stack[-1].name)
# render every item in the stack.
for item in self.stack:
item.render()
# process remaining callbacks.
for key in self.callbacks.keys():
for item in self.callbacks[key]:
item.render()
def update_size(stack, name):
# walk recursively through each block to update its size
blocks = []
for item in stack:
if isinstance(item, size):
item.render()
elif isinstance(item, block):
blocks += [item]
for b in blocks:
update_size(b.stack, b.name)
b.render()
# call update_size on each block of the request
for item in self.stack:
if isinstance(item, block):
update_size(item.stack, item.name)
item.render()
# now collect, merge and return the rendered items.
self.rendered = ""
for item in self.stack:
self.rendered += item.rendered
return self.rendered
def reset (self):
'''
Reset every block and primitives mutant state under this request.
'''
self.mutant_index = 1
self.closed_blocks = {}
for item in self.stack:
if item.fuzzable:
item.reset()
def walk (self, stack=None):
'''
Recursively walk through and yield every primitive and block on the request stack.
@rtype: Sulley Primitives
@return: Sulley Primitives
'''
if not stack:
stack = self.stack
for item in stack:
# if the item is a block, step into it and continue looping.
if isinstance(item, block):
for item in self.walk(item.stack):
yield item
else:
yield item
########################################################################################################################
class block:
def __init__ (self, name, request, group=None, encoder=None, dep=None, dep_value=None, dep_values=[], dep_compare="=="):
'''
The basic building block. Can contain primitives, sizers, checksums or other blocks.
@type name: String
@param name: Name of the new block
@type request: s_request
@param request: Request this block belongs to
@type group: String
@param group: (Optional, def=None) Name of group to associate this block with
@type encoder: Function Pointer
@param encoder: (Optional, def=None) Optional pointer to a function to pass rendered data to prior to return
@type dep: String
@param dep: (Optional, def=None) Optional primitive whose specific value this block is dependant on
@type dep_value: Mixed
@param dep_value: (Optional, def=None) Value that field "dep" must contain for block to be rendered
@type dep_values: List of Mixed Types
@param dep_values: (Optional, def=[]) Values that field "dep" may contain for block to be rendered
@type dep_compare: String
@param dep_compare: (Optional, def="==") Comparison method to apply to dependency (==, !=, >, >=, <, <=)
'''
self.name = name
self.request = request
self.group = group
self.encoder = encoder
self.dep = dep
self.dep_value = dep_value
self.dep_values = dep_values
self.dep_compare = dep_compare
self.stack = [] # block item stack.
self.rendered = "" # rendered block contents.
self.fuzzable = True # blocks are always fuzzable because they may contain fuzzable items.
self.group_idx = 0 # if this block is tied to a group, the index within that group.
self.fuzz_complete = False # whether or not we are done fuzzing this block.
self.mutant_index = 0 # current mutation index.
def mutate (self):
mutated = False
# are we done with this block?
if self.fuzz_complete:
return False
#
# mutate every item on the stack for every possible group value.
#
if self.group:
group_count = self.request.names[self.group].num_mutations()
# update the group value to that at the current index.
self.request.names[self.group].value = self.request.names[self.group].values[self.group_idx]
# mutate every item on the stack at the current group value.
for item in self.stack:
if item.fuzzable and item.mutate():
mutated = True
if not isinstance(item, block):
self.request.mutant = item
break
# if the possible mutations for the stack are exhausted.
if not mutated:
# increment the group value index.
self.group_idx += 1
# if the group values are exhausted, we are done with this block.
if self.group_idx == group_count:
# restore the original group value.
self.request.names[self.group].value = self.request.names[self.group].original_value
# otherwise continue mutating this group/block.
else:
# update the group value to that at the current index.
self.request.names[self.group].value = self.request.names[self.group].values[self.group_idx]
# this the mutate state for every item in this blocks stack.
# NOT THE BLOCK ITSELF THOUGH! (hence why we didn't call self.reset())
for item in self.stack:
if item.fuzzable:
item.reset()
# now mutate the first field in this block before continuing.
# (we repeat a test case if we don't mutate something)
for item in self.stack:
if item.fuzzable and item.mutate():
mutated = True
if not isinstance(item, block):
self.request.mutant = item
break
#
# no grouping, mutate every item on the stack once.
#
else:
for item in self.stack:
if item.fuzzable and item.mutate():
mutated = True
if not isinstance(item, block):
self.request.mutant = item
break
# if this block is dependant on another field, then manually update that fields value appropriately while we
# mutate this block. we'll restore the original value of the field prior to continuing.
if mutated and self.dep:
# if a list of values was specified, use the first item in the list.
if self.dep_values:
self.request.names[self.dep].value = self.dep_values[0]
# if a list of values was not specified, assume a single value is present.
else:
self.request.names[self.dep].value = self.dep_value
# we are done mutating this block.
if not mutated:
self.fuzz_complete = True
# if we had a dependancy, make sure we restore the original value.
if self.dep:
self.request.names[self.dep].value = self.request.names[self.dep].original_value
if mutated:
if not isinstance(item, block):
self.request.mutant = item
return mutated
def num_mutations (self):
'''
Determine the number of repetitions we will be making.
@rtype: Integer
@return: Number of mutated forms this primitive can take.
'''
num_mutations = 0
for item in self.stack:
if item.fuzzable:
num_mutations += item.num_mutations()
# if this block is associated with a group, then multiply out the number of possible mutations.
if self.group:
num_mutations *= len(self.request.names[self.group].values)
return num_mutations
def push (self, item):
'''
Push an arbitrary item onto this blocks stack.
'''
self.stack.append(item)
def render (self):
'''
Step through every item on this blocks stack and render it. Subsequent blocks recursively render their stacks.
'''
# add the completed block to the request dictionary.
self.request.closed_blocks[self.name] = self
#
# if this block is dependant on another field and the value is not met, render nothing.
#
if self.dep:
if self.dep_compare == "==":
if self.dep_values and self.request.names[self.dep].value not in self.dep_values:
self.rendered = ""
return
elif not self.dep_values and self.request.names[self.dep].value != self.dep_value:
self.rendered = ""
return
if self.dep_compare == "!=":
if self.dep_values and self.request.names[self.dep].value in self.dep_values:
self.rendered = ""
return
elif self.request.names[self.dep].value == self.dep_value:
self.rendered = ""
return
if self.dep_compare == ">" and self.dep_value <= self.request.names[self.dep].value:
self.rendered = ""
return
if self.dep_compare == ">=" and self.dep_value < self.request.names[self.dep].value:
self.rendered = ""
return
if self.dep_compare == "<" and self.dep_value >= self.request.names[self.dep].value:
self.rendered = ""
return
if self.dep_compare == "<=" and self.dep_value > self.request.names[self.dep].value:
self.rendered = ""
return
#
# otherwise, render and encode as usual.
#
# recursively render the items on the stack.
for item in self.stack:
item.render()
# now collect and merge the rendered items.
self.rendered = ""
for item in self.stack:
self.rendered += item.rendered
# if an encoder was attached to this block, call it.
if self.encoder:
self.rendered = self.encoder(self.rendered)
# the block is now closed, clear out all the entries from the request back splice dictionary.
if self.request.callbacks.has_key(self.name):
for item in self.request.callbacks[self.name]:
item.render()
def reset (self):
'''
Reset the primitives on this blocks stack to the starting mutation state.
'''
self.fuzz_complete = False
self.group_idx = 0
for item in self.stack:
if item.fuzzable:
item.reset()
########################################################################################################################
class checksum:
checksum_lengths = {"crc16": 2, "crc32":4, "adler32":4, "md5":16, "sha1":20}
def __init__(self, block_name, request, algorithm="crc32", length=0, endian="<", name=None):
'''
Create a checksum block bound to the block with the specified name. You *can not* create a checksm for any
currently open blocks.
@type block_name: String
@param block_name: Name of block to apply sizer to
@type request: s_request
@param request: Request this block belongs to
@type algorithm: String
@param algorithm: (Optional, def=crc32) Checksum algorithm to use. (crc16, crc32, adler32, md5, sha1)
@type length: Integer
@param length: (Optional, def=0) Length of checksum, specify 0 to auto-calculate
@type endian: Character
@param endian: (Optional, def=LITTLE_ENDIAN) Endianess of the bit field (LITTLE_ENDIAN: <, BIG_ENDIAN: >)
@type name: String
@param name: Name of this checksum field
'''
self.block_name = block_name
self.request = request
self.algorithm = algorithm
self.length = length
self.endian = endian
self.name = name
self.rendered = ""
self.fuzzable = False
if not self.length and self.checksum_lengths.has_key(self.algorithm):
self.length = self.checksum_lengths[self.algorithm]
def checksum (self, data):
'''
Calculate and return the checksum (in raw bytes) over the supplied data.
@type data: Raw
@param data: Rendered block data to calculate checksum over.
@rtype: Raw
@return: Checksum.
'''
if type(self.algorithm) is str:
if self.algorithm == "crc32":
return struct.pack(self.endian+"L", (zlib.crc32(data) & 0xFFFFFFFFL))
elif self.algorithm == "adler32":
return struct.pack(self.endian+"L", (zlib.adler32(data) & 0xFFFFFFFFL))
elif self.algorithm == "md5":
digest = hashlib.md5(data).digest()
# TODO: is this right?
if self.endian == ">":
(a, b, c, d) = struct.unpack("<LLLL", digest)
digest = struct.pack(">LLLL", a, b, c, d)
return digest
elif self.algorithm == "sha1":
digest = hashlib.sha1(data).digest()
# TODO: is this right?
if self.endian == ">":
(a, b, c, d, e) = struct.unpack("<LLLLL", digest)
digest = struct.pack(">LLLLL", a, b, c, d, e)
return digest
elif self.algorithm == "crc16":
return struct.pack(self.endian+"H", CRC16(data).intchecksum())
else:
raise sex.SullyRuntimeError("INVALID CHECKSUM ALGORITHM SPECIFIED: %s" % self.algorithm)
else:
return self.algorithm(data)
def render (self):
'''
Calculate the checksum of the specified block using the specified algorithm.
'''
self.rendered = ""
# if the target block for this sizer is already closed, render the checksum.
if self.block_name in self.request.closed_blocks:
block_data = self.request.closed_blocks[self.block_name].rendered
self.rendered = self.checksum(block_data)
# otherwise, add this checksum block to the requests callback list.
else:
if not self.request.callbacks.has_key(self.block_name):
self.request.callbacks[self.block_name] = []
self.request.callbacks[self.block_name].append(self)
########################################################################################################################
class repeat:
'''
This block type is kind of special in that it is a hybrid between a block and a primitive (it can be fuzzed). The
user does not need to be wary of this fact.
'''
def __init__ (self, block_name, request, min_reps=0, max_reps=None, step=1, variable=None, fuzzable=True, name=None):
'''
Repeat the rendered contents of the specified block cycling from min_reps to max_reps counting by step. By
default renders to nothing. This block modifier is useful for fuzzing overflows in table entries. This block
modifier MUST come after the block it is being applied to.
@type block_name: String
@param block_name: Name of block to apply sizer to
@type request: s_request
@param request: Request this block belongs to
@type min_reps: Integer
@param min_reps: (Optional, def=0) Minimum number of block repetitions
@type max_reps: Integer
@param max_reps: (Optional, def=None) Maximum number of block repetitions
@type step: Integer
@param step: (Optional, def=1) Step count between min and max reps
@type variable: Sulley Integer Primitive
@param variable: (Optional, def=None) Repititions will be derived from this variable, disables fuzzing
@type fuzzable: Boolean
@param fuzzable: (Optional, def=True) Enable/disable fuzzing of this primitive
@type name: String
@param name: (Optional, def=None) Specifying a name gives you direct access to a primitive
'''
self.block_name = block_name
self.request = request
self.variable = variable
self.min_reps = min_reps
self.max_reps = max_reps
self.step = step
self.fuzzable = fuzzable
self.name = name
self.value = self.original_value = "" # default to nothing!
self.rendered = "" # rendered value
self.fuzz_complete = False # flag if this primitive has been completely fuzzed
self.fuzz_library = [] # library of static fuzz heuristics to cycle through.
self.mutant_index = 0 # current mutation number
self.current_reps = min_reps # current number of repetitions
# ensure the target block exists.
if self.block_name not in self.request.names:
raise sex.SullyRuntimeError("CAN NOT ADD REPEATER FOR NON-EXISTANT BLOCK: %s" % self.block_name)
# ensure the user specified either a variable to tie this repeater to or a min/max val.
if self.variable == None and self.max_reps == None:
raise sex.SullyRuntimeError("REPEATER FOR BLOCK %s DOES NOT HAVE A MIN/MAX OR VARIABLE BINDING" % self.block_name)
# if a variable is specified, ensure it is an integer type.
if self.variable and not isinstance(self.variable, primitives.bit_field):
print self.variable
raise sex.SullyRuntimeError("ATTEMPT TO BIND THE REPEATER FOR BLOCK %s TO A NON INTEGER PRIMITIVE" % self.block_name)
# if not binding variable was specified, propogate the fuzz library with the repetition counts.
if not self.variable:
self.fuzz_library = range(self.min_reps, self.max_reps + 1, self.step)
# otherwise, disable fuzzing as the repitition count is determined by the variable.
else:
self.fuzzable = False
def mutate (self):
'''
Mutate the primitive by stepping through the fuzz library, return False on completion. If variable-bounding is
specified then fuzzing is implicitly disabled. Instead, the render() routine will properly calculate the
correct repitition and return the appropriate data.
@rtype: Boolean
@return: True on success, False otherwise.
'''
# render the contents of the block we are repeating.
self.request.names[self.block_name].render()
# if the target block for this sizer is not closed, raise an exception.
if self.block_name not in self.request.closed_blocks:
raise sex.SullyRuntimeError("CAN NOT APPLY REPEATER TO UNCLOSED BLOCK: %s" % self.block_name)
# if we've run out of mutations, raise the completion flag.
if self.mutant_index == self.num_mutations():
self.fuzz_complete = True
# if fuzzing was disabled or complete, and mutate() is called, ensure the original value is restored.
if not self.fuzzable or self.fuzz_complete:
self.value = self.original_value
self.current_reps = self.min_reps
return False
if self.variable:
self.current_reps = self.variable.value
else:
self.current_reps = self.fuzz_library[self.mutant_index]
# set the current value as a multiple of the rendered block based on the current fuzz library count.
block = self.request.closed_blocks[self.block_name]
self.value = block.rendered * self.fuzz_library[self.mutant_index]
# increment the mutation count.
self.mutant_index += 1
return True
def num_mutations (self):
'''
Determine the number of repetitions we will be making.
@rtype: Integer
@return: Number of mutated forms this primitive can take.
'''
return len(self.fuzz_library)
def render (self):
'''
Nothing fancy on render, simply return the value.
'''
# if the target block for this sizer is not closed, raise an exception.
if self.block_name not in self.request.closed_blocks:
raise sex.SullyRuntimeError("CAN NOT APPLY REPEATER TO UNCLOSED BLOCK: %s" % self.block_name)
# if a variable-bounding was specified then set the value appropriately.
if self.variable:
block = self.request.closed_blocks[self.block_name]
self.value = block.rendered * self.variable.value
self.rendered = self.value
return self.rendered
def reset (self):
'''
Reset the fuzz state of this primitive.
'''
self.fuzz_complete = False
self.mutant_index = 0
self.value = self.original_value
########################################################################################################################
class size:
'''
This block type is kind of special in that it is a hybrid between a block and a primitive (it can be fuzzed). The
user does not need to be wary of this fact.
'''
def __init__ (self, block_name, request, offset=0, length=4, endian="<", format="binary", inclusive=False, signed=False, math=None, fuzzable=False, name=None):
'''
Create a sizer block bound to the block with the specified name. You *can not* create a sizer for any
currently open blocks.
@type block_name: String
@param block_name: Name of block to apply sizer to
@type request: s_request
@param request: Request this block belongs to
@type length: Integer
@param length: (Optional, def=4) Length of sizer
@type offset: Integer
@param offset: (Optional, def=0) Offset for calculated size value
@type endian: Character
@param endian: (Optional, def=LITTLE_ENDIAN) Endianess of the bit field (LITTLE_ENDIAN: <, BIG_ENDIAN: >)
@type format: String
@param format: (Optional, def=binary) Output format, "binary" or "ascii"
@type inclusive: Boolean
@param inclusive: (Optional, def=False) Should the sizer count its own length?
@type signed: Boolean
@param signed: (Optional, def=False) Make size signed vs. unsigned (applicable only with format="ascii")
@type math: Function
@param math: (Optional, def=None) Apply the mathematical operations defined in this function to the size
@type fuzzable: Boolean
@param fuzzable: (Optional, def=False) Enable/disable fuzzing of this sizer
@type name: String
@param name: Name of this sizer field
'''
self.block_name = block_name
self.request = request
self.offset = offset
self.length = length
self.endian = endian
self.format = format
self.inclusive = inclusive
self.signed = signed
self.math = math
self.fuzzable = fuzzable
self.name = name
self.original_value = "N/A" # for get_primitive
self.s_type = "size" # for ease of object identification
self.bit_field = primitives.bit_field(0, self.length*8, endian=self.endian, format=self.format, signed=self.signed)
self.rendered = ""
self.fuzz_complete = self.bit_field.fuzz_complete
self.fuzz_library = self.bit_field.fuzz_library
self.mutant_index = self.bit_field.mutant_index
self.value = self.bit_field.value
if self.math == None:
self.math = lambda (x): x
def exhaust (self):
'''
Exhaust the possible mutations for this primitive.
@rtype: Integer
@return: The number of mutations to reach exhaustion
'''
num = self.num_mutations() - self.mutant_index
self.fuzz_complete = True
self.mutant_index = self.num_mutations()
self.bit_field.mutant_index = self.num_mutations()
self.value = self.original_value
return num
def mutate (self):
'''
Wrap the mutation routine of the internal bit_field primitive.
@rtype: Boolean
@return: True on success, False otherwise.
'''
if self.mutant_index == self.num_mutations():
self.fuzz_complete = True
self.mutant_index += 1
return self.bit_field.mutate()
def num_mutations (self):
'''
Wrap the num_mutations routine of the internal bit_field primitive.
@rtype: Integer
@return: Number of mutated forms this primitive can take.
'''
return self.bit_field.num_mutations()
def render (self):
'''
Render the sizer.
'''
self.rendered = ""
# if the sizer is fuzzable and we have not yet exhausted the the possible bit field values, use the fuzz value.
if self.fuzzable and self.bit_field.mutant_index and not self.bit_field.fuzz_complete:
self.rendered = self.bit_field.render()
# if the target block for this sizer is already closed, render the size.
elif self.block_name in self.request.closed_blocks:
if self.inclusive: self_size = self.length
else: self_size = 0
block = self.request.closed_blocks[self.block_name]
self.bit_field.value = self.math(len(block.rendered) + self_size + self.offset)
self.rendered = self.bit_field.render()
# otherwise, add this sizer block to the requests callback list.
else:
if not self.request.callbacks.has_key(self.block_name):
self.request.callbacks[self.block_name] = []
self.request.callbacks[self.block_name].append(self)
def reset (self):
'''
Wrap the reset routine of the internal bit_field primitive.
'''
self.bit_field.reset()
| 30,797
|
Python
|
.py
| 624
| 38.307692
| 163
| 0.57825
|
OpenRCE/sulley
| 1,416
| 338
| 56
|
GPL-2.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
16,009
|
primitives.py
|
OpenRCE_sulley/sulley/primitives.py
|
import random
import struct
########################################################################################################################
class base_primitive (object):
'''
The primitive base class implements common functionality shared across most primitives.
'''
def __init__ (self):
self.fuzz_complete = False # this flag is raised when the mutations are exhausted.
self.fuzz_library = [] # library of static fuzz heuristics to cycle through.
self.fuzzable = True # flag controlling whether or not the given primitive is to be fuzzed.
self.mutant_index = 0 # current mutation index into the fuzz library.
self.original_value = None # original value of primitive.
self.rendered = "" # rendered value of primitive.
self.value = None # current value of primitive.
def exhaust (self):
'''
Exhaust the possible mutations for this primitive.
@rtype: Integer
@return: The number of mutations to reach exhaustion
'''
num = self.num_mutations() - self.mutant_index
self.fuzz_complete = True
self.mutant_index = self.num_mutations()
self.value = self.original_value
return num
def mutate (self):
'''
Mutate the primitive by stepping through the fuzz library, return False on completion.
@rtype: Boolean
@return: True on success, False otherwise.
'''
# if we've ran out of mutations, raise the completion flag.
if self.mutant_index == self.num_mutations():
self.fuzz_complete = True
# if fuzzing was disabled or complete, and mutate() is called, ensure the original value is restored.
if not self.fuzzable or self.fuzz_complete:
self.value = self.original_value
return False
# update the current value from the fuzz library.
self.value = self.fuzz_library[self.mutant_index]
# increment the mutation count.
self.mutant_index += 1
return True
def num_mutations (self):
'''
Calculate and return the total number of mutations for this individual primitive.
@rtype: Integer
@return: Number of mutated forms this primitive can take
'''
return len(self.fuzz_library)
def render (self):
'''
Nothing fancy on render, simply return the value.
'''
self.rendered = self.value
return self.rendered
def reset (self):
'''
Reset this primitive to the starting mutation state.
'''
self.fuzz_complete = False
self.mutant_index = 0
self.value = self.original_value
########################################################################################################################
class delim (base_primitive):
def __init__ (self, value, fuzzable=True, name=None):
'''
Represent a delimiter such as :,\r,\n, ,=,>,< etc... Mutations include repetition, substitution and exclusion.
@type value: Character
@param value: Original value
@type fuzzable: Boolean
@param fuzzable: (Optional, def=True) Enable/disable fuzzing of this primitive
@type name: String
@param name: (Optional, def=None) Specifying a name gives you direct access to a primitive
'''
self.value = self.original_value = value
self.fuzzable = fuzzable
self.name = name
self.s_type = "delim" # for ease of object identification
self.rendered = "" # rendered value
self.fuzz_complete = False # flag if this primitive has been completely fuzzed
self.fuzz_library = [] # library of fuzz heuristics
self.mutant_index = 0 # current mutation number
#
# build the library of fuzz heuristics.
#
# if the default delim is not blank, repeat it a bunch of times.
if self.value:
self.fuzz_library.append(self.value * 2)
self.fuzz_library.append(self.value * 5)
self.fuzz_library.append(self.value * 10)
self.fuzz_library.append(self.value * 25)
self.fuzz_library.append(self.value * 100)
self.fuzz_library.append(self.value * 500)
self.fuzz_library.append(self.value * 1000)
# try ommitting the delimiter.
self.fuzz_library.append("")
# if the delimiter is a space, try throwing out some tabs.
if self.value == " ":
self.fuzz_library.append("\t")
self.fuzz_library.append("\t" * 2)
self.fuzz_library.append("\t" * 100)
# toss in some other common delimiters:
self.fuzz_library.append(" ")
self.fuzz_library.append("\t")
self.fuzz_library.append("\t " * 100)
self.fuzz_library.append("\t\r\n" * 100)
self.fuzz_library.append("!")
self.fuzz_library.append("@")
self.fuzz_library.append("#")
self.fuzz_library.append("$")
self.fuzz_library.append("%")
self.fuzz_library.append("^")
self.fuzz_library.append("&")
self.fuzz_library.append("*")
self.fuzz_library.append("(")
self.fuzz_library.append(")")
self.fuzz_library.append("-")
self.fuzz_library.append("_")
self.fuzz_library.append("+")
self.fuzz_library.append("=")
self.fuzz_library.append(":")
self.fuzz_library.append(": " * 100)
self.fuzz_library.append(":7" * 100)
self.fuzz_library.append(";")
self.fuzz_library.append("'")
self.fuzz_library.append("\"")
self.fuzz_library.append("/")
self.fuzz_library.append("\\")
self.fuzz_library.append("?")
self.fuzz_library.append("<")
self.fuzz_library.append(">")
self.fuzz_library.append(".")
self.fuzz_library.append(",")
self.fuzz_library.append("\r")
self.fuzz_library.append("\n")
self.fuzz_library.append("\r\n" * 64)
self.fuzz_library.append("\r\n" * 128)
self.fuzz_library.append("\r\n" * 512)
########################################################################################################################
class group (base_primitive):
def __init__ (self, name, values):
'''
This primitive represents a list of static values, stepping through each one on mutation. You can tie a block
to a group primitive to specify that the block should cycle through all possible mutations for *each* value
within the group. The group primitive is useful for example for representing a list of valid opcodes.
@type name: String
@param name: Name of group
@type values: List or raw data
@param values: List of possible raw values this group can take.
'''
self.name = name
self.values = values
self.fuzzable = True
self.s_type = "group"
self.value = self.values[0]
self.original_value = self.values[0]
self.rendered = ""
self.fuzz_complete = False
self.mutant_index = 0
# sanity check that values list only contains strings (or raw data)
if self.values != []:
for val in self.values:
assert type(val) is str, "Value list may only contain strings or raw data"
def mutate (self):
'''
Move to the next item in the values list.
@rtype: False
@return: False
'''
if self.mutant_index == self.num_mutations():
self.fuzz_complete = True
# if fuzzing was disabled or complete, and mutate() is called, ensure the original value is restored.
if not self.fuzzable or self.fuzz_complete:
self.value = self.values[0]
return False
# step through the value list.
self.value = self.values[self.mutant_index]
# increment the mutation count.
self.mutant_index += 1
return True
def num_mutations (self):
'''
Number of values in this primitive.
@rtype: Integer
@return: Number of values in this primitive.
'''
return len(self.values)
########################################################################################################################
class random_data (base_primitive):
def __init__ (self, value, min_length, max_length, max_mutations=25, fuzzable=True, step=None, name=None):
'''
Generate a random chunk of data while maintaining a copy of the original. A random length range can be specified.
For a static length, set min/max length to be the same.
@type value: Raw
@param value: Original value
@type min_length: Integer
@param min_length: Minimum length of random block
@type max_length: Integer
@param max_length: Maximum length of random block
@type max_mutations: Integer
@param max_mutations: (Optional, def=25) Number of mutations to make before reverting to default
@type fuzzable: Boolean
@param fuzzable: (Optional, def=True) Enable/disable fuzzing of this primitive
@type step: Integer
@param step: (Optional, def=None) If not null, step count between min and max reps, otherwise random
@type name: String
@param name: (Optional, def=None) Specifying a name gives you direct access to a primitive
'''
self.value = self.original_value = str(value)
self.min_length = min_length
self.max_length = max_length
self.max_mutations = max_mutations
self.fuzzable = fuzzable
self.step = step
self.name = name
self.s_type = "random_data" # for ease of object identification
self.rendered = "" # rendered value
self.fuzz_complete = False # flag if this primitive has been completely fuzzed
self.mutant_index = 0 # current mutation number
if self.step:
self.max_mutations = (self.max_length - self.min_length) / self.step + 1
def mutate (self):
'''
Mutate the primitive value returning False on completion.
@rtype: Boolean
@return: True on success, False otherwise.
'''
# if we've ran out of mutations, raise the completion flag.
if self.mutant_index == self.num_mutations():
self.fuzz_complete = True
# if fuzzing was disabled or complete, and mutate() is called, ensure the original value is restored.
if not self.fuzzable or self.fuzz_complete:
self.value = self.original_value
return False
# select a random length for this string.
if not self.step:
length = random.randint(self.min_length, self.max_length)
# select a length function of the mutant index and the step.
else:
length = self.min_length + self.mutant_index * self.step
# reset the value and generate a random string of the determined length.
self.value = ""
for i in xrange(length):
self.value += chr(random.randint(0, 255))
# increment the mutation count.
self.mutant_index += 1
return True
def num_mutations (self):
'''
Calculate and return the total number of mutations for this individual primitive.
@rtype: Integer
@return: Number of mutated forms this primitive can take
'''
return self.max_mutations
########################################################################################################################
class static (base_primitive):
def __init__ (self, value, name=None):
'''
Primitive that contains static content.
@type value: Raw
@param value: Raw static data
@type name: String
@param name: (Optional, def=None) Specifying a name gives you direct access to a primitive
'''
self.value = self.original_value = value
self.name = name
self.fuzzable = False # every primitive needs this attribute.
self.mutant_index = 0
self.s_type = "static" # for ease of object identification
self.rendered = ""
self.fuzz_complete = True
def mutate (self):
'''
Do nothing.
@rtype: False
@return: False
'''
return False
def num_mutations (self):
'''
Return 0.
@rtype: 0
@return: 0
'''
return 0
########################################################################################################################
class string (base_primitive):
# store fuzz_library as a class variable to avoid copying the ~70MB structure across each instantiated primitive.
fuzz_library = []
def __init__ (self, value, size=-1, padding="\x00", encoding="ascii", fuzzable=True, max_len=0, name=None):
'''
Primitive that cycles through a library of "bad" strings. The class variable 'fuzz_library' contains a list of
smart fuzz values global across all instances. The 'this_library' variable contains fuzz values specific to
the instantiated primitive. This allows us to avoid copying the near ~70MB fuzz_library data structure across
each instantiated primitive.
@type value: String
@param value: Default string value
@type size: Integer
@param size: (Optional, def=-1) Static size of this field, leave -1 for dynamic.
@type padding: Character
@param padding: (Optional, def="\\x00") Value to use as padding to fill static field size.
@type encoding: String
@param encoding: (Optonal, def="ascii") String encoding, ex: utf_16_le for Microsoft Unicode.
@type fuzzable: Boolean
@param fuzzable: (Optional, def=True) Enable/disable fuzzing of this primitive
@type max_len: Integer
@param max_len: (Optional, def=0) Maximum string length
@type name: String
@param name: (Optional, def=None) Specifying a name gives you direct access to a primitive
'''
self.value = self.original_value = value
self.size = size
self.padding = padding
self.encoding = encoding
self.fuzzable = fuzzable
self.name = name
self.s_type = "string" # for ease of object identification
self.rendered = "" # rendered value
self.fuzz_complete = False # flag if this primitive has been completely fuzzed
self.mutant_index = 0 # current mutation number
# add this specific primitives repitition values to the unique fuzz library.
self.this_library = \
[
self.value * 2,
self.value * 10,
self.value * 100,
# UTF-8
self.value * 2 + "\xfe",
self.value * 10 + "\xfe",
self.value * 100 + "\xfe",
]
# if the fuzz library has not yet been initialized, do so with all the global values.
if not self.fuzz_library:
string.fuzz_library = \
[
# omission.
"",
# strings ripped from spike (and some others I added)
"/.:/" + "A"*5000 + "\x00\x00",
"/.../" + "A"*5000 + "\x00\x00",
"/.../.../.../.../.../.../.../.../.../.../",
"/../../../../../../../../../../../../etc/passwd",
"/../../../../../../../../../../../../boot.ini",
"..:..:..:..:..:..:..:..:..:..:..:..:..:",
"\\\\*",
"\\\\?\\",
"/\\" * 5000,
"/." * 5000,
"!@#$%%^#$%#$@#$%$$@#$%^^**(()",
"%01%02%03%04%0a%0d%0aADSF",
"%01%02%03@%04%0a%0d%0aADSF",
"/%00/",
"%00/",
"%00",
"%u0000",
"%\xfe\xf0%\x00\xff",
"%\xfe\xf0%\x01\xff" * 20,
# format strings.
"%n" * 100,
"%n" * 500,
"\"%n\"" * 500,
"%s" * 100,
"%s" * 500,
"\"%s\"" * 500,
# command injection.
"|touch /tmp/SULLEY",
";touch /tmp/SULLEY;",
"|notepad",
";notepad;",
"\nnotepad\n",
# SQL injection.
"1;SELECT%20*",
"'sqlattempt1",
"(sqlattempt2)",
"OR%201=1",
# some binary strings.
"\xde\xad\xbe\xef",
"\xde\xad\xbe\xef" * 10,
"\xde\xad\xbe\xef" * 100,
"\xde\xad\xbe\xef" * 1000,
"\xde\xad\xbe\xef" * 10000,
"\x00" * 1000,
# miscellaneous.
"\r\n" * 100,
"<>" * 500, # sendmail crackaddr (http://lsd-pl.net/other/sendmail.txt)
]
# add some long strings.
self.add_long_strings("A")
self.add_long_strings("B")
self.add_long_strings("1")
self.add_long_strings("2")
self.add_long_strings("3")
self.add_long_strings("<")
self.add_long_strings(">")
self.add_long_strings("'")
self.add_long_strings("\"")
self.add_long_strings("/")
self.add_long_strings("\\")
self.add_long_strings("?")
self.add_long_strings("=")
self.add_long_strings("a=")
self.add_long_strings("&")
self.add_long_strings(".")
self.add_long_strings(",")
self.add_long_strings("(")
self.add_long_strings(")")
self.add_long_strings("]")
self.add_long_strings("[")
self.add_long_strings("%")
self.add_long_strings("*")
self.add_long_strings("-")
self.add_long_strings("+")
self.add_long_strings("{")
self.add_long_strings("}")
self.add_long_strings("\x14")
self.add_long_strings("\xFE") # expands to 4 characters under utf16
self.add_long_strings("\xFF") # expands to 4 characters under utf16
# add some long strings with null bytes thrown in the middle of it.
for length in [128, 256, 1024, 2048, 4096, 32767, 0xFFFF]:
s = "B" * length
s = s[:len(s)/2] + "\x00" + s[len(s)/2:]
string.fuzz_library.append(s)
# if the optional file '.fuzz_strings' is found, parse each line as a new entry for the fuzz library.
try:
fh = open(".fuzz_strings", "r")
for fuzz_string in fh.readlines():
fuzz_string = fuzz_string.rstrip("\r\n")
if fuzz_string != "":
string.fuzz_library.append(fuzz_string)
fh.close()
except:
pass
# delete strings which length is greater than max_len.
if max_len > 0:
if any(len(s) > max_len for s in self.this_library):
self.this_library = list(set([s[:max_len] for s in self.this_library]))
if any(len(s) > max_len for s in self.fuzz_library):
self.fuzz_library = list(set([s[:max_len] for s in self.fuzz_library]))
def add_long_strings (self, sequence):
'''
Given a sequence, generate a number of selectively chosen strings lengths of the given sequence and add to the
string heuristic library.
@type sequence: String
@param sequence: Sequence to repeat for creation of fuzz strings.
'''
for length in [128, 255, 256, 257, 511, 512, 513, 1023, 1024, 2048, 2049, 4095, 4096, 4097, 5000, 10000, 20000,
32762, 32763, 32764, 32765, 32766, 32767, 32768, 32769, 0xFFFF-2, 0xFFFF-1, 0xFFFF, 0xFFFF+1,
0xFFFF+2, 99999, 100000, 500000, 1000000]:
long_string = sequence * length
string.fuzz_library.append(long_string)
def mutate (self):
'''
Mutate the primitive by stepping through the fuzz library extended with the "this" library, return False on
completion.
@rtype: Boolean
@return: True on success, False otherwise.
'''
# loop through the fuzz library until a suitable match is found.
while 1:
# if we've ran out of mutations, raise the completion flag.
if self.mutant_index == self.num_mutations():
self.fuzz_complete = True
# if fuzzing was disabled or complete, and mutate() is called, ensure the original value is restored.
if not self.fuzzable or self.fuzz_complete:
self.value = self.original_value
return False
# update the current value from the fuzz library.
self.value = (self.fuzz_library + self.this_library)[self.mutant_index]
# increment the mutation count.
self.mutant_index += 1
# if the size parameter is disabled, break out of the loop right now.
if self.size == -1:
break
# ignore library items greather then user-supplied length.
# TODO: might want to make this smarter.
if len(self.value) > self.size:
continue
# pad undersized library items.
if len(self.value) < self.size:
self.value = self.value + self.padding * (self.size - len(self.value))
break
return True
def num_mutations (self):
'''
Calculate and return the total number of mutations for this individual primitive.
@rtype: Integer
@return: Number of mutated forms this primitive can take
'''
return len(self.fuzz_library) + len(self.this_library)
def render (self):
'''
Render the primitive, encode the string according to the specified encoding.
'''
# try to encode the string properly and fall back to the default value on failure.
try:
self.rendered = str(self.value).encode(self.encoding)
except:
self.rendered = self.value
return self.rendered
########################################################################################################################
class bit_field (base_primitive):
def __init__ (self, value, width, max_num=None, endian="<", format="binary", signed=False, full_range=False, fuzzable=True, name=None):
'''
The bit field primitive represents a number of variable length and is used to define all other integer types.
@type value: Integer
@param value: Default integer value
@type width: Integer
@param width: Width of bit fields
@type endian: Character
@param endian: (Optional, def=LITTLE_ENDIAN) Endianess of the bit field (LITTLE_ENDIAN: <, BIG_ENDIAN: >)
@type format: String
@param format: (Optional, def=binary) Output format, "binary" or "ascii"
@type signed: Boolean
@param signed: (Optional, def=False) Make size signed vs. unsigned (applicable only with format="ascii")
@type full_range: Boolean
@param full_range: (Optional, def=False) If enabled the field mutates through *all* possible values.
@type fuzzable: Boolean
@param fuzzable: (Optional, def=True) Enable/disable fuzzing of this primitive
@type name: String
@param name: (Optional, def=None) Specifying a name gives you direct access to a primitive
'''
assert(type(width) is int or type(value) is long)
if type(value) in [int, long, list, tuple]:
self.value = self.original_value = value
else:
raise ValueError("The supplied value must be either an Int, Long, List or Tuple.")
self.width = width
self.max_num = max_num
self.endian = endian
self.format = format
self.signed = signed
self.full_range = full_range
self.fuzzable = fuzzable
self.name = name
self.rendered = "" # rendered value
self.fuzz_complete = False # flag if this primitive has been completely fuzzed
self.fuzz_library = [] # library of fuzz heuristics
self.mutant_index = 0 # current mutation number
self.cyclic_index = 0 # when cycling through non-mutating values
if self.max_num == None:
self.max_num = self.to_decimal("1" + "0" * width)
assert(type(self.max_num) is int or type(self.max_num) is long)
# build the fuzz library.
if self.full_range:
# add all possible values.
for i in xrange(0, self.max_num):
self.fuzz_library.append(i)
else:
if type(value) in [list, tuple]:
# Use the supplied values as the fuzz library.
for val in value:
self.fuzz_library.append(val)
else:
# try only "smart" values.
self.add_integer_boundaries(0)
self.add_integer_boundaries(self.max_num / 2)
self.add_integer_boundaries(self.max_num / 3)
self.add_integer_boundaries(self.max_num / 4)
self.add_integer_boundaries(self.max_num / 8)
self.add_integer_boundaries(self.max_num / 16)
self.add_integer_boundaries(self.max_num / 32)
self.add_integer_boundaries(self.max_num)
# if the optional file '.fuzz_ints' is found, parse each line as a new entry for the fuzz library.
try:
fh = open(".fuzz_ints", "r")
for fuzz_int in fh.readlines():
# convert the line into an integer, continue on failure.
try:
fuzz_int = long(fuzz_int, 16)
except:
continue
if fuzz_int < self.max_num:
self.fuzz_library.append(fuzz_int)
fh.close()
except:
pass
def add_integer_boundaries (self, integer):
'''
Add the supplied integer and border cases to the integer fuzz heuristics library.
@type integer: Int
@param integer: Integer to append to fuzz heuristics
'''
for i in xrange(-10, 10):
case = integer + i
# ensure the border case falls within the valid range for this field.
if 0 <= case < self.max_num:
if case not in self.fuzz_library:
self.fuzz_library.append(case)
def render (self):
'''
Render the primitive.
'''
#
# binary formatting.
#
if self.format == "binary":
bit_stream = ""
rendered = ""
# pad the bit stream to the next byte boundary.
if self.width % 8 == 0:
bit_stream += self.to_binary()
else:
bit_stream = "0" * (8 - (self.width % 8))
bit_stream += self.to_binary()
# convert the bit stream from a string of bits into raw bytes.
for i in xrange(len(bit_stream) / 8):
chunk = bit_stream[8*i:8*i+8]
rendered += struct.pack("B", self.to_decimal(chunk))
# if necessary, convert the endianess of the raw bytes.
if self.endian == "<":
rendered = list(rendered)
rendered.reverse()
rendered = "".join(rendered)
self.rendered = rendered
#
# ascii formatting.
#
else:
# if the sign flag is raised and we are dealing with a signed integer (first bit is 1).
if self.signed and self.to_binary()[0] == "1":
max_num = self.to_decimal("1" + "0" * (self.width - 1))
# mask off the sign bit.
val = self.value & self.to_decimal("1" * (self.width - 1))
# account for the fact that the negative scale works backwards.
val = max_num - val - 1
# toss in the negative sign.
self.rendered = "%d" % ~val
# unsigned integer or positive signed integer.
else:
self.rendered = "%d" % self.value
return self.rendered
def to_binary (self, number=None, bit_count=None):
'''
Convert a number to a binary string.
@type number: Integer
@param number: (Optional, def=self.value) Number to convert
@type bit_count: Integer
@param bit_count: (Optional, def=self.width) Width of bit string
@rtype: String
@return: Bit string
'''
if number == None:
if type(self.value) in [list, tuple]:
# We have been given a list to cycle through that is not being mutated...
if self.cyclic_index == len(self.value):
# Reset the index.
self.cyclic_index = 0
number = self.value[self.cyclic_index]
self.cyclic_index += 1
else:
number = self.value
if bit_count == None:
bit_count = self.width
return "".join(map(lambda x:str((number >> x) & 1), range(bit_count -1, -1, -1)))
def to_decimal (self, binary):
'''
Convert a binary string to a decimal number.
@type binary: String
@param binary: Binary string
@rtype: Integer
@return: Converted bit string
'''
return int(binary, 2)
########################################################################################################################
class byte (bit_field):
def __init__ (self, value, endian="<", format="binary", signed=False, full_range=False, fuzzable=True, name=None):
self.s_type = "byte"
if type(value) not in [int, long, list, tuple]:
value = struct.unpack(endian + "B", value)[0]
bit_field.__init__(self, value, 8, None, endian, format, signed, full_range, fuzzable, name)
########################################################################################################################
class word (bit_field):
def __init__ (self, value, endian="<", format="binary", signed=False, full_range=False, fuzzable=True, name=None):
self.s_type = "word"
if type(value) not in [int, long, list, tuple]:
value = struct.unpack(endian + "H", value)[0]
bit_field.__init__(self, value, 16, None, endian, format, signed, full_range, fuzzable, name)
########################################################################################################################
class dword (bit_field):
def __init__ (self, value, endian="<", format="binary", signed=False, full_range=False, fuzzable=True, name=None):
self.s_type = "dword"
if type(value) not in [int, long, list, tuple]:
value = struct.unpack(endian + "L", value)[0]
bit_field.__init__(self, value, 32, None, endian, format, signed, full_range, fuzzable, name)
########################################################################################################################
class qword (bit_field):
def __init__ (self, value, endian="<", format="binary", signed=False, full_range=False, fuzzable=True, name=None):
self.s_type = "qword"
if type(value) not in [int, long, list, tuple]:
value = struct.unpack(endian + "Q", value)[0]
bit_field.__init__(self, value, 64, None, endian, format, signed, full_range, fuzzable, name)
| 32,873
|
Python
|
.py
| 693
| 36.480519
| 139
| 0.536495
|
OpenRCE/sulley
| 1,416
| 338
| 56
|
GPL-2.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
16,010
|
dcerpc.py
|
OpenRCE_sulley/sulley/utils/dcerpc.py
|
import math
import struct
import misc
########################################################################################################################
def bind (uuid, version):
'''
Generate the data necessary to bind to the specified interface.
'''
major, minor = version.split(".")
major = struct.pack("<H", int(major))
minor = struct.pack("<H", int(minor))
bind = "\x05\x00" # version 5.0
bind += "\x0b" # packet type = bind (11)
bind += "\x03" # packet flags = last/first flag set
bind += "\x10\x00\x00\x00" # data representation
bind += "\x48\x00" # frag length: 72
bind += "\x00\x00" # auth length
bind += "\x00\x00\x00\x00" # call id
bind += "\xb8\x10" # max xmit frag (4280)
bind += "\xb8\x10" # max recv frag (4280)
bind += "\x00\x00\x00\x00" # assoc group
bind += "\x01" # number of ctx items (1)
bind += "\x00\x00\x00" # padding
bind += "\x00\x00" # context id (0)
bind += "\x01" # number of trans items (1)
bind += "\x00" # padding
bind += misc.uuid_str_to_bin(uuid) # abstract syntax
bind += major # interface version
bind += minor # interface version minor
# transfer syntax 8a885d04-1ceb-11c9-9fe8-08002b104860 v2.0
bind += "\x04\x5d\x88\x8a\xeb\x1c\xc9\x11\x9f\xe8\x08\x00\x2b\x10\x48\x60"
bind += "\x02\x00\x00\x00"
return bind
########################################################################################################################
def bind_ack (data):
'''
Ensure the data is a bind ack and that the
'''
# packet type == bind ack (12)?
if data[2] != "\x0c":
return False
# ack result == acceptance?
if data[36:38] != "\x00\x00":
return False
return True
########################################################################################################################
def request (opnum, data):
'''
Return a list of packets broken into 5k fragmented chunks necessary to make the RPC request.
'''
frag_size = 1000 # max frag size = 5840?
frags = []
num_frags = int(math.ceil(float(len(data)) / float(frag_size)))
for i in xrange(num_frags):
chunk = data[i * frag_size:(i+1) * frag_size]
frag_length = struct.pack("<H", len(chunk) + 24)
alloc_hint = struct.pack("<L", len(chunk))
flags = 0
if i == 0: flags |= 0x1 # first frag
if i == num_frags - 1: flags |= 0x2 # last frag
request = "\x05\x00" # version 5.0
request += "\x00" # packet type = request (0)
request += struct.pack("B", flags) # packet flags
request += "\x10\x00\x00\x00" # data representation
request += frag_length # frag length
request += "\x00\x00" # auth length
request += "\x00\x00\x00\x00" # call id
request += alloc_hint # alloc hint
request += "\x00\x00" # context id (0)
request += struct.pack("<H", opnum) # opnum
request += chunk
frags.append(request)
# you don't have to send chunks out individually. so make life easier for the user and send them all at once.
return "".join(frags)
| 3,706
|
Python
|
.py
| 74
| 44.22973
| 120
| 0.449488
|
OpenRCE/sulley
| 1,416
| 338
| 56
|
GPL-2.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
16,011
|
scada.py
|
OpenRCE_sulley/sulley/utils/scada.py
|
import math
import struct
########################################################################################################################
def dnp3 (data, control_code="\x44", src="\x00\x00", dst="\x00\x00"):
num_packets = int(math.ceil(float(len(data)) / 250.0))
packets = []
for i in xrange(num_packets):
slice = data[i*250 : (i+1)*250]
p = "\x05\x64"
p += chr(len(slice))
p += control_code
p += dst
p += src
chksum = struct.pack("<H", crc16(p))
p += chksum
num_chunks = int(math.ceil(float(len(slice) / 16.0)))
# insert the fragmentation flags / sequence number.
# first frag: 0x40, last frag: 0x80
frag_number = i
if i == 0:
frag_number |= 0x40
if i == num_packets - 1:
frag_number |= 0x80
p += chr(frag_number)
for x in xrange(num_chunks):
chunk = slice[i*16 : (i+1)*16]
chksum = struct.pack("<H", crc16(chunk))
p += chksum + chunk
packets.append(p)
return packets
| 1,118
|
Python
|
.py
| 30
| 28.7
| 120
| 0.461323
|
OpenRCE/sulley
| 1,416
| 338
| 56
|
GPL-2.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
16,012
|
misc.py
|
OpenRCE_sulley/sulley/utils/misc.py
|
import re
import struct
########################################################################################################################
def crc16 (string, value=0):
'''
CRC-16 poly: p(x) = x**16 + x**15 + x**2 + 1
'''
crc16_table = []
for byte in range(256):
crc = 0
for bit in range(8):
if (byte ^ crc) & 1: crc = (crc >> 1) ^ 0xa001 # polly
else: crc >>= 1
byte >>= 1
crc16_table.append(crc)
for ch in string:
value = crc16_table[ord(ch) ^ (value & 0xff)] ^ (value >> 8)
return value
########################################################################################################################
def uuid_bin_to_str (uuid):
'''
Convert a binary UUID to human readable string.
'''
(block1, block2, block3) = struct.unpack("<LHH", uuid[:8])
(block4, block5, block6) = struct.unpack(">HHL", uuid[8:16])
return "%08x-%04x-%04x-%04x-%04x%08x" % (block1, block2, block3, block4, block5, block6)
########################################################################################################################
def uuid_str_to_bin (uuid):
'''
Ripped from Core Impacket. Converts a UUID string to binary form.
'''
matches = re.match('([\dA-Fa-f]{8})-([\dA-Fa-f]{4})-([\dA-Fa-f]{4})-([\dA-Fa-f]{4})-([\dA-Fa-f]{4})([\dA-Fa-f]{8})', uuid)
(uuid1, uuid2, uuid3, uuid4, uuid5, uuid6) = map(lambda x: long(x, 16), matches.groups())
uuid = struct.pack('<LHH', uuid1, uuid2, uuid3)
uuid += struct.pack('>HHL', uuid4, uuid5, uuid6)
return uuid
| 1,648
|
Python
|
.py
| 36
| 39.861111
| 126
| 0.426868
|
OpenRCE/sulley
| 1,416
| 338
| 56
|
GPL-2.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
16,013
|
crc16.py
|
OpenRCE_sulley/sulley/utils/crc16.py
|
# -*- coding: UTF-8 -*-
"""
Translation from a C code posted to a forum on the Internet.
@translator Thomas Schmid
@url https://raw.githubusercontent.com/mitshell/libmich/master/libmich/utils/CRC16.py
"""
from array import array
def reflect(crc, bitnum):
# reflects the lower 'bitnum' bits of 'crc'
j = 1
crcout = 0
for b in range(bitnum):
i = 1 << (bitnum-1-b)
if crc & i:
crcout |= j
j <<= 1
return crcout
def crcbitbybit(p):
# bit by bit algorithm with augmented zero bytes.
crc = 0
for i in range(len(p)):
c = p[i]
c = reflect(ord(c), 8)
j = 0x80
for b in range(16):
bit = crc & 0x8000
crc <<= 1
crc &= 0xFFFF
if c & j:
crc |= 1
if bit:
crc ^= 0x1021
j >>= 1
if j == 0:
break
for i in range(16):
bit = crc & 0x8000
crc <<= 1
if bit:
crc ^= 0x1021
crc = reflect(crc, 16)
return crc
class CRC16(object):
"""
Class interface, like the Python library's cryptographic
hash functions (which CRC's are definitely not.)
"""
def __init__(self, string=''):
self.val = 0
if string:
self.update(string)
def update(self, string):
self.val = crcbitbybit(string)
def checksum(self):
return chr(self.val >> 8) + chr(self.val & 0xff)
def intchecksum(self):
return self.val
def hexchecksum(self):
return '%04x' % self.val
def copy(self):
clone = CRC16()
clone.val = self.val
return clone
| 1,702
|
Python
|
.py
| 63
| 19.222222
| 86
| 0.536133
|
OpenRCE/sulley
| 1,416
| 338
| 56
|
GPL-2.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
16,014
|
cluster.py
|
OpenRCE_sulley/sulley/pgraph/cluster.py
|
#
# pGRAPH
# Copyright (C) 2006 Pedram Amini <pedram.amini@gmail.com>
#
# 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
'''
@author: Pedram Amini
@license: GNU General Public License 2.0 or later
@contact: pedram.amini@gmail.com
@organization: www.openrce.org
'''
import node
class cluster (object):
'''
'''
id = None
nodes = []
####################################################################################################################
def __init__ (self, id=None):
'''
Class constructor.
'''
self.id = id
self.nodes = []
####################################################################################################################
def add_node (self, node):
'''
Add a node to the cluster.
@type node: pGRAPH Node
@param node: Node to add to cluster
'''
self.nodes.append(node)
return self
####################################################################################################################
def del_node (self, node_id):
'''
Remove a node from the cluster.
@type node: pGRAPH Node
@param node: Node to remove from cluster
'''
for node in self.nodes:
if node.id == node_id:
self.nodes.remove(node)
break
return self
####################################################################################################################
def find_node (self, attribute, value):
'''
Find and return the node with the specified attribute / value pair.
@type attribute: String
@param attribute: Attribute name we are looking for
@type value: Mixed
@param value: Value of attribute we are looking for
@rtype: Mixed
@return: Node, if attribute / value pair is matched. None otherwise.
'''
for node in self.nodes:
if hasattr(node, attribute):
if getattr(node, attribute) == value:
return node
return None
####################################################################################################################
def render (self):
pass
| 2,963
|
Python
|
.py
| 73
| 33.863014
| 120
| 0.495989
|
OpenRCE/sulley
| 1,416
| 338
| 56
|
GPL-2.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
16,015
|
edge.py
|
OpenRCE_sulley/sulley/pgraph/edge.py
|
#
# pGRAPH
# Copyright (C) 2006 Pedram Amini <pedram.amini@gmail.com>
#
# 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
'''
@author: Pedram Amini
@license: GNU General Public License 2.0 or later
@contact: pedram.amini@gmail.com
@organization: www.openrce.org
'''
class edge (object):
'''
'''
id = None
src = None
dst = None
# general graph attributes.
color = 0x000000
label = ""
# gml relevant attributes.
gml_arrow = "none"
gml_stipple = 1
gml_line_width = 1.0
####################################################################################################################
def __init__ (self, src, dst):
'''
Class constructor.
@type src: Mixed
@param src: Edge source
@type dst: Mixed
@param dst: Edge destination
'''
# the unique id for any edge (provided that duplicates are not allowed) is the combination of the source and
# the destination stored as a long long.
self.id = (src << 32) + dst
self.src = src
self.dst = dst
# general graph attributes.
self.color = 0x000000
self.label = ""
# gml relevant attributes.
self.gml_arrow = "none"
self.gml_stipple = 1
self.gml_line_width = 1.0
####################################################################################################################
def render_edge_gml (self, graph):
'''
Render an edge description suitable for use in a GML file using the set internal attributes.
@type graph: pgraph.graph
@param graph: Top level graph object containing the current edge
@rtype: String
@return: GML edge description
'''
src = graph.find_node("id", self.src)
dst = graph.find_node("id", self.dst)
# ensure nodes exist at the source and destination of this edge.
if not src or not dst:
return ""
edge = ' edge [\n'
edge += ' source %d\n' % src.number
edge += ' target %d\n' % dst.number
edge += ' generalization 0\n'
edge += ' graphics [\n'
edge += ' type "line"\n'
edge += ' arrow "%s"\n' % self.gml_arrow
edge += ' stipple %d\n' % self.gml_stipple
edge += ' lineWidth %f\n' % self.gml_line_width
edge += ' fill "#%06x"\n' % self.color
edge += ' ]\n'
edge += ' ]\n'
return edge
####################################################################################################################
def render_edge_graphviz (self, graph):
'''
Render an edge suitable for use in a Pydot graph using the set internal attributes.
@type graph: pgraph.graph
@param graph: Top level graph object containing the current edge
@rtype: pydot.Edge()
@return: Pydot object representing edge
'''
import pydot
# no need to validate if nodes exist for src/dst. graphviz takes care of that for us transparently.
dot_edge = pydot.Edge(self.src, self.dst)
if self.label:
dot_edge.label = self.label
dot_edge.color = "#%06x" % self.color
return dot_edge
####################################################################################################################
def render_edge_udraw (self, graph):
'''
Render an edge description suitable for use in a GML file using the set internal attributes.
@type graph: pgraph.graph
@param graph: Top level graph object containing the current edge
@rtype: String
@return: GML edge description
'''
src = graph.find_node("id", self.src)
dst = graph.find_node("id", self.dst)
# ensure nodes exist at the source and destination of this edge.
if not src or not dst:
return ""
# translate newlines for uDraw.
self.label = self.label.replace("\n", "\\n")
udraw = 'l("%08x->%08x",' % (self.src, self.dst)
udraw += 'e("",' # open edge
udraw += '[' # open attributes
udraw += 'a("EDGECOLOR","#%06x"),' % self.color
udraw += 'a("OBJECT","%s")' % self.label
udraw += '],' # close attributes
udraw += 'r("%08x")' % self.dst
udraw += ')' # close edge
udraw += ')' # close element
return udraw
####################################################################################################################
def render_edge_udraw_update (self):
'''
Render an edge update description suitable for use in a GML file using the set internal attributes.
@rtype: String
@return: GML edge update description
'''
# translate newlines for uDraw.
self.label = self.label.replace("\n", "\\n")
udraw = 'new_edge("%08x->%08x","",' % (self.src, self.dst)
udraw += '['
udraw += 'a("EDGECOLOR","#%06x"),' % self.color
udraw += 'a("OBJECT","%s")' % self.label
udraw += '],'
udraw += '"%08x","%08x"' % (self.src, self.dst)
udraw += ')'
return udraw
| 6,271
|
Python
|
.py
| 140
| 37.235714
| 120
| 0.502381
|
OpenRCE/sulley
| 1,416
| 338
| 56
|
GPL-2.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
16,016
|
graph.py
|
OpenRCE_sulley/sulley/pgraph/graph.py
|
#
# pGRAPH
# Copyright (C) 2006 Pedram Amini <pedram.amini@gmail.com>
#
# 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
'''
@author: Pedram Amini
@license: GNU General Public License 2.0 or later
@contact: pedram.amini@gmail.com
@organization: www.openrce.org
'''
import node
import edge
import cluster
import copy
class graph (object):
'''
@todo: Add support for clusters
@todo: Potentially swap node list with a node dictionary for increased performance
'''
id = None
clusters = []
edges = {}
nodes = {}
####################################################################################################################
def __init__ (self, id=None):
'''
'''
self.id = id
self.clusters = []
self.edges = {}
self.nodes = {}
####################################################################################################################
def add_cluster (self, cluster):
'''
Add a pgraph cluster to the graph.
@type cluster: pGRAPH Cluster
@param cluster: Cluster to add to graph
'''
self.clusters.append(cluster)
return self
####################################################################################################################
def add_edge (self, edge, prevent_dups=True):
'''
Add a pgraph edge to the graph. Ensures a node exists for both the source and destination of the edge.
@type edge: pGRAPH Edge
@param edge: Edge to add to graph
@type prevent_dups: Boolean
@param prevent_dups: (Optional, Def=True) Flag controlling whether or not the addition of duplicate edges is ok
'''
if prevent_dups:
if self.edges.has_key(edge.id):
return self
# ensure the source and destination nodes exist.
if self.find_node("id", edge.src) and self.find_node("id", edge.dst):
self.edges[edge.id] = edge
return self
####################################################################################################################
def add_graph (self, other_graph):
'''
Alias of graph_cat(). Concatenate the other graph into the current one.
@todo: Add support for clusters
@see: graph_cat()
@type other_graph: pgraph.graph
@param other_graph: Graph to concatenate into this one.
'''
return self.graph_cat(other_graph)
####################################################################################################################
def add_node (self, node):
'''
Add a pgraph node to the graph. Ensures a node with the same id does not already exist in the graph.
@type node: pGRAPH Node
@param node: Node to add to graph
'''
node.number = len(self.nodes)
if not self.nodes.has_key(node.id):
self.nodes[node.id] = node
return self
####################################################################################################################
def del_cluster (self, id):
'''
Remove a cluster from the graph.
@type id: Mixed
@param id: Identifier of cluster to remove from graph
'''
for cluster in self.clusters:
if cluster.id == id:
self.clusters.remove(cluster)
break
return self
####################################################################################################################
def del_edge (self, id=None, src=None, dst=None):
'''
Remove an edge from the graph. There are two ways to call this routine, with an edge id::
graph.del_edge(id)
or by specifying the edge source and destination::
graph.del_edge(src=source, dst=destination)
@type id: Mixed
@param id: (Optional) Identifier of edge to remove from graph
@type src: Mixed
@param src: (Optional) Source of edge to remove from graph
@type dst: Mixed
@param dst: (Optional) Destination of edge to remove from graph
'''
if not id:
id = (src << 32) + dst
if self.edges.has_key(id):
del self.edges[id]
return self
####################################################################################################################
def del_graph (self, other_graph):
'''
Alias of graph_sub(). Remove the elements shared between the current graph and other graph from the current
graph.
@todo: Add support for clusters
@see: graph_sub()
@type other_graph: pgraph.graph
@param other_graph: Graph to diff/remove against
'''
return self.graph_sub(other_graph)
####################################################################################################################
def del_node (self, id):
'''
Remove a node from the graph.
@type node_id: Mixed
@param node_id: Identifier of node to remove from graph
'''
if self.nodes.has_key(id):
del self.nodes[id]
return self
####################################################################################################################
def edges_from (self, id):
'''
Enumerate the edges from the specified node.
@type id: Mixed
@param id: Identifier of node to enumerate edges from
@rtype: List
@return: List of edges from the specified node
'''
return [edge for edge in self.edges.values() if edge.src == id]
####################################################################################################################
def edges_to (self, id):
'''
Enumerate the edges to the specified node.
@type id: Mixed
@param id: Identifier of node to enumerate edges to
@rtype: List
@return: List of edges to the specified node
'''
return [edge for edge in self.edges.values() if edge.dst == id]
####################################################################################################################
def find_cluster (self, attribute, value):
'''
Find and return the cluster with the specified attribute / value pair.
@type attribute: String
@param attribute: Attribute name we are looking for
@type value: Mixed
@param value: Value of attribute we are looking for
@rtype: Mixed
@return: Cluster, if attribute / value pair is matched. None otherwise.
'''
for cluster in self.clusters:
if hasattr(cluster, attribute):
if getattr(cluster, attribute) == value:
return cluster
return None
####################################################################################################################
def find_cluster_by_node (self, attribute, value):
'''
Find and return the cluster that contains the node with the specified attribute / value pair.
@type attribute: String
@param attribute: Attribute name we are looking for
@type value: Mixed
@param value: Value of attribute we are looking for
@rtype: Mixed
@return: Cluster, if node with attribute / value pair is matched. None otherwise.
'''
for cluster in self.clusters:
for node in cluster:
if hasattr(node, attribute):
if getattr(node, attribute) == value:
return cluster
return None
####################################################################################################################
def find_edge (self, attribute, value):
'''
Find and return the edge with the specified attribute / value pair.
@type attribute: String
@param attribute: Attribute name we are looking for
@type value: Mixed
@param value: Value of attribute we are looking for
@rtype: Mixed
@return: Edge, if attribute / value pair is matched. None otherwise.
'''
# if the attribute to search for is the id, simply return the edge from the internal hash.
if attribute == "id" and self.edges.has_key(value):
return self.edges[value]
# step through all the edges looking for the given attribute/value pair.
else:
for edge in self.edges.values():
if hasattr(edge, attribute):
if getattr(edge, attribute) == value:
return edge
return None
####################################################################################################################
def find_node (self, attribute, value):
'''
Find and return the node with the specified attribute / value pair.
@type attribute: String
@param attribute: Attribute name we are looking for
@type value: Mixed
@param value: Value of attribute we are looking for
@rtype: Mixed
@return: Node, if attribute / value pair is matched. None otherwise.
'''
# if the attribute to search for is the id, simply return the node from the internal hash.
if attribute == "id" and self.nodes.has_key(value):
return self.nodes[value]
# step through all the nodes looking for the given attribute/value pair.
else:
for node in self.nodes.values():
if hasattr(node, attribute):
if getattr(node, attribute) == value:
return node
return None
####################################################################################################################
def graph_cat (self, other_graph):
'''
Concatenate the other graph into the current one.
@todo: Add support for clusters
@type other_graph: pgraph.graph
@param other_graph: Graph to concatenate into this one.
'''
for other_node in other_graph.nodes.values():
self.add_node(other_node)
for other_edge in other_graph.edges.values():
self.add_edge(other_edge)
return self
####################################################################################################################
def graph_down (self, from_node_id, max_depth=-1):
'''
Create a new graph, looking down, from the specified node id to the specified depth.
@type from_node_id: pgraph.node
@param from_node_id: Node to use as start of down graph
@type max_depth: Integer
@param max_depth: (Optional, Def=-1) Number of levels to include in down graph (-1 for infinite)
@rtype: pgraph.graph
@return: Down graph around specified node.
'''
down_graph = graph()
from_node = self.find_node("id", from_node_id)
if not from_node:
print "unable to resolve node %08x" % from_node_id
raise Exception
levels_to_process = []
current_depth = 1
levels_to_process.append([from_node])
for level in levels_to_process:
next_level = []
if current_depth > max_depth and max_depth != -1:
break
for node in level:
down_graph.add_node(copy.copy(node))
for edge in self.edges_from(node.id):
to_add = self.find_node("id", edge.dst)
if not down_graph.find_node("id", edge.dst):
next_level.append(to_add)
down_graph.add_node(copy.copy(to_add))
down_graph.add_edge(copy.copy(edge))
if next_level:
levels_to_process.append(next_level)
current_depth += 1
return down_graph
####################################################################################################################
def graph_intersect (self, other_graph):
'''
Remove all elements from the current graph that do not exist in the other graph.
@todo: Add support for clusters
@type other_graph: pgraph.graph
@param other_graph: Graph to intersect with
'''
for node in self.nodes.values():
if not other_graph.find_node("id", node.id):
self.del_node(node.id)
for edge in self.edges.values():
if not other_graph.find_edge("id", edge.id):
self.del_edge(edge.id)
return self
####################################################################################################################
def graph_proximity (self, center_node_id, max_depth_up=2, max_depth_down=2):
'''
Create a proximity graph centered around the specified node.
@type center_node_id: pgraph.node
@param center_node_id: Node to use as center of proximity graph
@type max_depth_up: Integer
@param max_depth_up: (Optional, Def=2) Number of upward levels to include in proximity graph
@type max_depth_down: Integer
@param max_depth_down: (Optional, Def=2) Number of downward levels to include in proximity graph
@rtype: pgraph.graph
@return: Proximity graph around specified node.
'''
prox_graph = self.graph_down(center_node_id, max_depth_down)
prox_graph.add_graph(self.graph_up(center_node_id, max_depth_up))
return prox_graph
####################################################################################################################
def graph_sub (self, other_graph):
'''
Remove the elements shared between the current graph and other graph from the current
graph.
@todo: Add support for clusters
@type other_graph: pgraph.graph
@param other_graph: Graph to diff/remove against
'''
for other_node in other_graph.nodes.values():
self.del_node(other_node.id)
for other_edge in other_graph.edges.values():
self.del_edge(None, other_edge.src, other_edge.dst)
return self
####################################################################################################################
def graph_up (self, from_node_id, max_depth=-1):
'''
Create a new graph, looking up, from the specified node id to the specified depth.
@type from_node_id: pgraph.node
@param from_node_id: Node to use as start of up graph
@type max_depth: Integer
@param max_depth: (Optional, Def=-1) Number of levels to include in up graph (-1 for infinite)
@rtype: pgraph.graph
@return: Up graph to the specified node.
'''
up_graph = graph()
from_node = self.find_node("id", from_node_id)
levels_to_process = []
current_depth = 1
levels_to_process.append([from_node])
for level in levels_to_process:
next_level = []
if current_depth > max_depth and max_depth != -1:
break
for node in level:
up_graph.add_node(copy.copy(node))
for edge in self.edges_to(node.id):
to_add = self.find_node("id", edge.src)
if not up_graph.find_node("id", edge.src):
next_level.append(to_add)
up_graph.add_node(copy.copy(to_add))
up_graph.add_edge(copy.copy(edge))
if next_level:
levels_to_process.append(next_level)
current_depth += 1
return up_graph
####################################################################################################################
def render_graph_gml (self):
'''
Render the GML graph description.
@rtype: String
@return: GML graph description.
'''
gml = 'Creator "pGRAPH - Pedram Amini <pedram.amini@gmail.com>"\n'
gml += 'directed 1\n'
# open the graph tag.
gml += 'graph [\n'
# add the nodes to the GML definition.
for node in self.nodes.values():
gml += node.render_node_gml(self)
# add the edges to the GML definition.
for edge in self.edges.values():
gml += edge.render_edge_gml(self)
# close the graph tag.
gml += ']\n'
"""
TODO: Complete cluster rendering
# if clusters exist.
if len(self.clusters):
# open the rootcluster tag.
gml += 'rootcluster [\n'
# add the clusters to the GML definition.
for cluster in self.clusters:
gml += cluster.render()
# add the clusterless nodes to the GML definition.
for node in self.nodes:
if not self.find_cluster_by_node("id", node.id):
gml += ' vertex "%d"\n' % node.id
# close the rootcluster tag.
gml += ']\n'
"""
return gml
####################################################################################################################
def render_graph_graphviz (self):
'''
Render the graphviz graph structure.
@rtype: pydot.Dot
@return: Pydot object representing entire graph
'''
import pydot
dot_graph = pydot.Dot()
for node in self.nodes.values():
dot_graph.add_node(node.render_node_graphviz(self))
for edge in self.edges.values():
dot_graph.add_edge(edge.render_edge_graphviz(self))
return dot_graph
####################################################################################################################
def render_graph_udraw (self):
'''
Render the uDraw graph description.
@rtype: String
@return: uDraw graph description.
'''
udraw = '['
# render each of the nodes in the graph.
# the individual nodes will handle their own edge rendering.
for node in self.nodes.values():
udraw += node.render_node_udraw(self)
udraw += ','
# trim the extraneous comment and close the graph.
udraw = udraw[0:-1] + ']'
return udraw
####################################################################################################################
def render_graph_udraw_update (self):
'''
Render the uDraw graph update description.
@rtype: String
@return: uDraw graph description.
'''
udraw = '['
for node in self.nodes.values():
udraw += node.render_node_udraw_update()
udraw += ','
for edge in self.edges.values():
udraw += edge.render_edge_udraw_update()
udraw += ','
# trim the extraneous comment and close the graph.
udraw = udraw[0:-1] + ']'
return udraw
####################################################################################################################
def update_node_id (self, current_id, new_id):
'''
Simply updating the id attribute of a node will sever the edges to / from the given node. This routine will
correctly update the edges as well.
@type current_id: Long
@param current_id: Current ID of node whose ID we want to update
@type new_id: Long
@param new_id: New ID to update to.
'''
if not self.nodes.has_key(current_id):
return
# update the node.
node = self.nodes[current_id]
del self.nodes[current_id]
node.id = new_id
self.nodes[node.id] = node
# update the edges.
for edge in [edge for edge in self.edges.values() if current_id in (edge.src, edge.dst)]:
del self.edges[edge.id]
if edge.src == current_id:
edge.src = new_id
if edge.dst == current_id:
edge.dst = new_id
edge.id = (edge.src << 32) + edge.dst
self.edges[edge.id] = edge
####################################################################################################################
def sorted_nodes (self):
'''
Return a list of the nodes within the graph, sorted by id.
@rtype: List
@return: List of nodes, sorted by id.
'''
node_keys = self.nodes.keys()
node_keys.sort()
return [self.nodes[key] for key in node_keys]
| 21,762
|
Python
|
.py
| 478
| 35.725941
| 120
| 0.497036
|
OpenRCE/sulley
| 1,416
| 338
| 56
|
GPL-2.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
16,017
|
__init__.py
|
OpenRCE_sulley/sulley/pgraph/__init__.py
|
#
# pGRAPH
# Copyright (C) 2006 Pedram Amini <pedram.amini@gmail.com>
#
# 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
'''
@author: Pedram Amini
@license: GNU General Public License 2.0 or later
@contact: pedram.amini@gmail.com
@organization: www.openrce.org
'''
from cluster import *
from edge import *
from graph import *
from node import *
| 1,012
|
Python
|
.py
| 24
| 41.125
| 119
| 0.764944
|
OpenRCE/sulley
| 1,416
| 338
| 56
|
GPL-2.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
16,018
|
node.py
|
OpenRCE_sulley/sulley/pgraph/node.py
|
#
# pGRAPH
# Copyright (C) 2006 Pedram Amini <pedram.amini@gmail.com>
#
# 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
'''
@author: Pedram Amini
@license: GNU General Public License 2.0 or later
@contact: pedram.amini@gmail.com
@organization: www.openrce.org
'''
class node (object):
'''
'''
id = 0
number = 0
# general graph attributes
color = 0xEEF7FF
border_color = 0xEEEEEE
label = ""
shape = "box"
# gml relevant attributes.
gml_width = 0.0
gml_height = 0.0
gml_pattern = "1"
gml_stipple = 1
gml_line_width = 1.0
gml_type = "rectangle"
gml_width_shape = 1.0
# udraw relevant attributes.
udraw_image = None
udraw_info = ""
####################################################################################################################
def __init__ (self, id=None):
'''
'''
self.id = id
self.number = 0
# general graph attributes
self.color = 0xEEF7FF
self.border_color = 0xEEEEEE
self.label = ""
self.shape = "box"
# gml relevant attributes.
self.gml_width = 0.0
self.gml_height = 0.0
self.gml_pattern = "1"
self.gml_stipple = 1
self.gml_line_width = 1.0
self.gml_type = "rectangle"
self.gml_width_shape = 1.0
####################################################################################################################
def render_node_gml (self, graph):
'''
Render a node description suitable for use in a GML file using the set internal attributes.
@type graph: pgraph.graph
@param graph: Top level graph object containing the current node
@rtype: String
@return: GML node description.
'''
# GDE does not like lines longer then approx 250 bytes. within their their own GML files you won't find lines
# longer then approx 210 bytes. wo we are forced to break long lines into chunks.
chunked_label = ""
cursor = 0
while cursor < len(self.label):
amount = 200
# if the end of the current chunk contains a backslash or double-quote, back off some.
if cursor + amount < len(self.label):
while self.label[cursor+amount] == '\\' or self.label[cursor+amount] == '"':
amount -= 1
chunked_label += self.label[cursor:cursor+amount] + "\\\n"
cursor += amount
# if node width and height were not explicitly specified, make a best effort guess to create something nice.
if not self.gml_width:
self.gml_width = len(self.label) * 10
if not self.gml_height:
self.gml_height = len(self.label.split()) * 20
# construct the node definition.
node = ' node [\n'
node += ' id %d\n' % self.number
node += ' template "oreas:std:rect"\n'
node += ' label "'
node += '<!--%08x-->\\\n' % self.id
node += chunked_label + '"\n'
node += ' graphics [\n'
node += ' w %f\n' % self.gml_width
node += ' h %f\n' % self.gml_height
node += ' fill "#%06x"\n' % self.color
node += ' line "#%06x"\n' % self.border_color
node += ' pattern "%s"\n' % self.gml_pattern
node += ' stipple %d\n' % self.gml_stipple
node += ' lineWidth %f\n' % self.gml_line_width
node += ' type "%s"\n' % self.gml_type
node += ' width %f\n' % self.gml_width_shape
node += ' ]\n'
node += ' ]\n'
return node
####################################################################################################################
def render_node_graphviz (self, graph):
'''
Render a node suitable for use in a Pydot graph using the set internal attributes.
@type graph: pgraph.graph
@param graph: Top level graph object containing the current node
@rtype: pydot.Node
@return: Pydot object representing node
'''
import pydot
dot_node = pydot.Node(self.id)
dot_node.label = '<<font face="lucida console">%s</font>>' % self.label.rstrip("\r\n")
dot_node.label = dot_node.label.replace("\\n", '<br/>')
dot_node.shape = self.shape
dot_node.color = "#%06x" % self.color
dot_node.fillcolor = "#%06x" % self.color
return dot_node
####################################################################################################################
def render_node_udraw (self, graph):
'''
Render a node description suitable for use in a uDraw file using the set internal attributes.
@type graph: pgraph.graph
@param graph: Top level graph object containing the current node
@rtype: String
@return: uDraw node description.
'''
# translate newlines for uDraw.
self.label = self.label.replace("\n", "\\n")
# if an image was specified for this node, update the shape and include the image tag.
if self.udraw_image:
self.shape = "image"
udraw_image = 'a("IMAGE","%s"),' % self.udraw_image
else:
udraw_image = ""
udraw = 'l("%08x",' % self.id
udraw += 'n("",' # open node
udraw += '[' # open attributes
udraw += udraw_image
udraw += 'a("_GO","%s"),' % self.shape
udraw += 'a("COLOR","#%06x"),' % self.color
udraw += 'a("OBJECT","%s"),' % self.label
udraw += 'a("FONTFAMILY","courier"),'
udraw += 'a("INFO","%s"),' % self.udraw_info
udraw += 'a("BORDER","none")'
udraw += '],' # close attributes
udraw += '[' # open edges
edges = graph.edges_from(self.id)
for edge in edges:
udraw += edge.render_edge_udraw(graph)
udraw += ','
if edges:
udraw = udraw[0:-1]
udraw += ']))'
return udraw
####################################################################################################################
def render_node_udraw_update (self):
'''
Render a node update description suitable for use in a uDraw file using the set internal attributes.
@rtype: String
@return: uDraw node update description.
'''
# translate newlines for uDraw.
self.label = self.label.replace("\n", "\\n")
# if an image was specified for this node, update the shape and include the image tag.
if self.udraw_image:
self.shape = "image"
udraw_image = 'a("IMAGE","%s"),' % self.udraw_image
else:
udraw_image = ""
udraw = 'new_node("%08x","",' % self.id
udraw += '['
udraw += udraw_image
udraw += 'a("_GO","%s"),' % self.shape
udraw += 'a("COLOR","#%06x"),' % self.color
udraw += 'a("OBJECT","%s"),' % self.label
udraw += 'a("FONTFAMILY","courier"),'
udraw += 'a("INFO","%s"),' % self.udraw_info
udraw += 'a("BORDER","none")'
udraw += ']'
udraw += ')'
return udraw
| 8,623
|
Python
|
.py
| 187
| 37.946524
| 120
| 0.483906
|
OpenRCE/sulley
| 1,416
| 338
| 56
|
GPL-2.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
16,019
|
xdr.py
|
OpenRCE_sulley/sulley/legos/xdr.py
|
########################################################################################################################
### XDR TYPES (http://www.freesoft.org/CIE/RFC/1832/index.htm)
########################################################################################################################
import struct
from sulley import blocks, primitives, sex
########################################################################################################################
def xdr_pad (string):
return "\x00" * ((4 - (len(string) & 3)) & 3)
########################################################################################################################
class string (blocks.block):
'''
Note: this is not for fuzzing the XDR protocol but rather just representing an XDR string for fuzzing the actual
client.
'''
def __init__ (self, name, request, value, options={}):
blocks.block.__init__(self, name, request, None, None, None, None)
self.value = value
self.options = options
if not self.value:
raise sex.SullyRuntimeError("MISSING LEGO.xdr_string DEFAULT VALUE")
self.push(primitives.string(self.value))
def render (self):
'''
We overload and extend the render routine in order to properly pad and prefix the string.
[dword length][array][pad]
'''
# let the parent do the initial render.
blocks.block.render(self)
# encode the empty string correctly:
if self.rendered == "":
self.rendered = "\x00\x00\x00\x00"
else:
self.rendered = struct.pack(">L", len(self.rendered)) + self.rendered + xdr_pad(self.rendered)
return self.rendered
| 1,752
|
Python
|
.py
| 34
| 44.676471
| 120
| 0.455666
|
OpenRCE/sulley
| 1,416
| 338
| 56
|
GPL-2.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
16,020
|
dcerpc.py
|
OpenRCE_sulley/sulley/legos/dcerpc.py
|
########################################################################################################################
### MSRPC NDR TYPES
########################################################################################################################
import struct
from sulley import blocks, primitives, sex
########################################################################################################################
def ndr_pad (string):
return "\x00" * ((4 - (len(string) & 3)) & 3)
########################################################################################################################
class ndr_conformant_array (blocks.block):
'''
Note: this is not for fuzzing the RPC protocol but rather just representing an NDR string for fuzzing the actual
client.
'''
def __init__ (self, name, request, value, options={}):
blocks.block.__init__(self, name, request, None, None, None, None)
self.value = value
self.options = options
if not self.value:
raise sex.SullyRuntimeError("MISSING LEGO.ndr_conformant_array DEFAULT VALUE")
self.push(primitives.string(self.value))
def render (self):
'''
We overload and extend the render routine in order to properly pad and prefix the string.
[dword length][array][pad]
'''
# let the parent do the initial render.
blocks.block.render(self)
# encode the empty string correctly:
if self.rendered == "":
self.rendered = "\x00\x00\x00\x00"
else:
self.rendered = struct.pack("<L", len(self.rendered)) + self.rendered + ndr_pad(self.rendered)
return self.rendered
########################################################################################################################
class ndr_string (blocks.block):
'''
Note: this is not for fuzzing the RPC protocol but rather just representing an NDR string for fuzzing the actual
client.
'''
def __init__ (self, name, request, value, options={}):
blocks.block.__init__(self, name, request, None, None, None, None)
self.value = value
self.options = options
if not self.value:
raise sex.SullyRuntimeError("MISSING LEGO.tag DEFAULT VALUE")
self.push(primitives.string(self.value))
def render (self):
'''
We overload and extend the render routine in order to properly pad and prefix the string.
[dword length][dword offset][dword passed size][string][pad]
'''
# let the parent do the initial render.
blocks.block.render(self)
# encode the empty string correctly:
if self.rendered == "":
self.rendered = "\x00\x00\x00\x00"
else:
# ensure null termination.
self.rendered += "\x00"
# format accordingly.
length = len(self.rendered)
self.rendered = struct.pack("<L", length) \
+ struct.pack("<L", 0) \
+ struct.pack("<L", length) \
+ self.rendered \
+ ndr_pad(self.rendered)
return self.rendered
########################################################################################################################
class ndr_wstring (blocks.block):
'''
Note: this is not for fuzzing the RPC protocol but rather just representing an NDR string for fuzzing the actual
client.
'''
def __init__ (self, name, request, value, options={}):
blocks.block.__init__(self, name, request, None, None, None, None)
self.value = value
self.options = options
if not self.value:
raise sex.SullyRuntimeError("MISSING LEGO.tag DEFAULT VALUE")
self.push(primitives.string(self.value))
def render (self):
'''
We overload and extend the render routine in order to properly pad and prefix the string.
[dword length][dword offset][dword passed size][string][pad]
'''
# let the parent do the initial render.
blocks.block.render(self)
# encode the empty string correctly:
if self.rendered == "":
self.rendered = "\x00\x00\x00\x00"
else:
# unicode encode and null terminate.
self.rendered = self.rendered.encode("utf-16le") + "\x00"
# format accordingly.
length = len(self.rendered)
self.rendered = struct.pack("<L", length) \
+ struct.pack("<L", 0) \
+ struct.pack("<L", length) \
+ self.rendered \
+ ndr_pad(self.rendered)
return self.rendered
| 4,877
|
Python
|
.py
| 102
| 38.107843
| 120
| 0.492925
|
OpenRCE/sulley
| 1,416
| 338
| 56
|
GPL-2.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
16,021
|
__init__.py
|
OpenRCE_sulley/sulley/legos/__init__.py
|
import ber
import dcerpc
import misc
import xdr
# all defined legos must be added to this bin.
BIN = {}
BIN["ber_string"] = ber.string
BIN["ber_integer"] = ber.integer
BIN["dns_hostname"] = misc.dns_hostname
BIN["ndr_conformant_array"] = dcerpc.ndr_conformant_array
BIN["ndr_wstring"] = dcerpc.ndr_wstring
BIN["ndr_string"] = dcerpc.ndr_string
BIN["tag"] = misc.tag
BIN["xdr_string"] = xdr.string
| 471
|
Python
|
.py
| 14
| 32.571429
| 57
| 0.627193
|
OpenRCE/sulley
| 1,416
| 338
| 56
|
GPL-2.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
16,022
|
ber.py
|
OpenRCE_sulley/sulley/legos/ber.py
|
########################################################################################################################
### ASN.1 / BER TYPES (http://luca.ntop.org/Teaching/Appunti/asn1.html)
########################################################################################################################
import struct
from sulley import blocks, primitives, sex
########################################################################################################################
class string (blocks.block):
'''
[0x04][0x84][dword length][string]
Where:
0x04 = string
0x84 = length is 4 bytes
'''
def __init__ (self, name, request, value, options={}):
blocks.block.__init__(self, name, request, None, None, None, None)
self.value = value
self.options = options
self.prefix = options.get("prefix", "\x04")
if not self.value:
raise sex.SullyRuntimeError("MISSING LEGO.ber_string DEFAULT VALUE")
str_block = blocks.block(name + "_STR", request)
str_block.push(primitives.string(self.value))
self.push(blocks.size(name + "_STR", request, endian=">", fuzzable=True))
self.push(str_block)
def render (self):
# let the parent do the initial render.
blocks.block.render(self)
self.rendered = self.prefix + "\x84" + self.rendered
return self.rendered
########################################################################################################################
class integer (blocks.block):
'''
[0x02][0x04][dword]
Where:
0x02 = integer
0x04 = integer length is 4 bytes
'''
def __init__ (self, name, request, value, options={}):
blocks.block.__init__(self, name, request, None, None, None, None)
self.value = value
self.options = options
if not self.value:
raise sex.SullyRuntimeError("MISSING LEGO.ber_integer DEFAULT VALUE")
self.push(primitives.dword(self.value, endian=">"))
def render (self):
# let the parent do the initial render.
blocks.block.render(self)
self.rendered = "\x02\x04" + self.rendered
return self.rendered
| 2,252
|
Python
|
.py
| 49
| 38.755102
| 120
| 0.484167
|
OpenRCE/sulley
| 1,416
| 338
| 56
|
GPL-2.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
16,023
|
misc.py
|
OpenRCE_sulley/sulley/legos/misc.py
|
import struct
from sulley import blocks, primitives, sex
########################################################################################################################
class dns_hostname (blocks.block):
def __init__ (self, name, request, value, options={}):
blocks.block.__init__(self, name, request, None, None, None, None)
self.value = value
self.options = options
if not self.value:
raise sex.SullyRuntimeError("MISSING LEGO.tag DEFAULT VALUE")
self.push(primitives.string(self.value))
def render (self):
'''
We overload and extend the render routine in order to properly insert substring lengths.
'''
# let the parent do the initial render.
blocks.block.render(self)
new_str = ""
# replace dots (.) with the substring length.
for part in self.rendered.split("."):
new_str += str(len(part)) + part
# be sure to null terminate too.
self.rendered = new_str + "\x00"
return self.rendered
########################################################################################################################
class tag (blocks.block):
def __init__ (self, name, request, value, options={}):
blocks.block.__init__(self, name, request, None, None, None, None)
self.value = value
self.options = options
if not self.value:
raise sex.SullyRuntimeError("MISSING LEGO.tag DEFAULT VALUE")
# <example>
# [delim][string][delim]
self.push(primitives.delim("<"))
self.push(primitives.string(self.value))
self.push(primitives.delim(">"))
| 1,703
|
Python
|
.py
| 37
| 37.864865
| 120
| 0.52638
|
OpenRCE/sulley
| 1,416
| 338
| 56
|
GPL-2.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
16,024
|
hp.py
|
OpenRCE_sulley/requests/hp.py
|
from sulley import *
from struct import *
########################################################################################################################
def unicode_ftw(val):
"""
Simple unicode slicer
"""
val_list = []
for char in val:
val_list.append("\x00")
val_list.append(pack('B', ord(char)))
ret = ""
for char in val_list:
ret += char
return ret
########################################################################################################################
s_initialize("omni")
"""
Hewlett Packard OpenView Data Protector OmniInet.exe
"""
if s_block_start("packet_1"):
s_size("packet_2", endian=">", length=4)
s_block_end()
if s_block_start("packet_2"):
# unicode byte order marker
s_static("\xfe\xff")
# unicode magic
if s_block_start("unicode_magic", encoder=unicode_ftw):
s_int(267, format="ascii")
s_block_end()
s_static("\x00\x00")
# random 2 bytes
s_string("AA", size=2)
# unicode value to pass calls to wtoi()
if s_block_start("unicode_100_1", encoder=unicode_ftw):
s_int(100, format="ascii")
s_block_end()
s_static("\x00\x00")
# random 2 bytes
s_string("BB", size=2)
# unicode value to pass calls to wtoi()
if s_block_start("unicode_100_2", encoder=unicode_ftw):
s_int(100, format="ascii")
s_block_end()
s_static("\x00\x00")
# random 2 bytes
s_string("CC", size=2)
# unicode value to pass calls to wtoi()
if s_block_start("unicode_100_3", encoder=unicode_ftw):
s_int(100, format="ascii")
s_block_end()
s_static("\x00\x00")
# random buffer
s_string("D"*32, size=32)
# barhost cookie
s_dword(0x7cde7bab, endian="<", fuzzable=False)
# random buffer
s_string("FOO")
s_block_end()
| 1,848
|
Python
|
.py
| 59
| 26.288136
| 120
| 0.532541
|
OpenRCE/sulley
| 1,416
| 338
| 56
|
GPL-2.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
16,025
|
ldap.py
|
OpenRCE_sulley/requests/ldap.py
|
from sulley import *
"""
Application number Application
0 BindRequest
1 BindResponse
2 UnbindRequest
3 SearchRequest
4 SearchResponse
5 ModifyRequest
6 ModifyResponse
7 AddRequest
8 AddResponse
9 DelRequest
10 DelResponse
11 ModifyRDNRequest
12 ModifyRDNResponse
13 CompareRequest
14 CompareResponse
15 AbandonRequest
"""
########################################################################################################################
s_initialize("anonymous bind")
# all ldap messages start with this.
s_static("\x30")
# length of entire envelope.
s_static("\x84")
s_sizer("envelope", endian=">")
if s_block_start("envelope"):
s_static("\x02\x01\x01") # message id (always one)
s_static("\x60") # bind request (0)
s_static("\x84")
s_sizer("bind request", endian=">")
if s_block_start("bind request"):
s_static("\x02\x01\x03") # version
s_lego("ber_string", "anonymous")
s_lego("ber_string", "foobar", options={"prefix":"\x80"}) # 0x80 is "simple" authentication
s_block_end()
s_block_end()
########################################################################################################################
s_initialize("search request")
# all ldap messages start with this.
s_static("\x30")
# length of entire envelope.
s_static("\x84")
s_sizer("envelope", endian=">", fuzzable=True)
if s_block_start("envelope"):
s_static("\x02\x01\x02") # message id (always one)
s_static("\x63") # search request (3)
s_static("\x84")
s_sizer("searchRequest", endian=">", fuzzable=True)
if s_block_start("searchRequest"):
s_static("\x04\x00") # static empty string ... why?
s_static("\x0a\x01\x00") # scope: baseOjbect (0)
s_static("\x0a\x01\x00") # deref: never (0)
s_lego("ber_integer", 1000) # size limit
s_lego("ber_integer", 30) # time limit
s_static("\x01\x01\x00") # typesonly: false
s_lego("ber_string", "objectClass", options={"prefix":"\x87"})
s_static("\x30")
s_static("\x84")
s_sizer("attributes", endian=">")
if s_block_start("attributes"):
s_lego("ber_string", "1.1")
s_block_end("attributes")
s_block_end("searchRequest")
s_block_end("envelope")
| 2,324
|
Python
|
.py
| 66
| 31.227273
| 120
| 0.572066
|
OpenRCE/sulley
| 1,416
| 338
| 56
|
GPL-2.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
16,026
|
ndmp.py
|
OpenRCE_sulley/requests/ndmp.py
|
from sulley import *
import struct
import time
ndmp_messages = \
[
# Connect Interface
0x900, # NDMP_CONNECT_OPEN
0x901, # NDMP_CONECT_CLIENT_AUTH
0x902, # NDMP_CONNECT_CLOSE
0x903, # NDMP_CONECT_SERVER_AUTH
# Config Interface
0x100, # NDMP_CONFIG_GET_HOST_INFO
0x102, # NDMP_CONFIG_GET_CONNECTION_TYPE
0x103, # NDMP_CONFIG_GET_AUTH_ATTR
0x104, # NDMP_CONFIG_GET_BUTYPE_INFO
0x105, # NDMP_CONFIG_GET_FS_INFO
0x106, # NDMP_CONFIG_GET_TAPE_INFO
0x107, # NDMP_CONFIG_GET_SCSI_INFO
0x108, # NDMP_CONFIG_GET_SERVER_INFO
# SCSI Interface
0x200, # NDMP_SCSI_OPEN
0x201, # NDMP_SCSI_CLOSE
0x202, # NDMP_SCSI_GET_STATE
0x203, # NDMP_SCSI_SET_TARGET
0x204, # NDMP_SCSI_RESET_DEVICE
0x205, # NDMP_SCSI_RESET_BUS
0x206, # NDMP_SCSI_EXECUTE_CDB
# Tape Interface
0x300, # NDMP_TAPE_OPEN
0x301, # NDMP_TAPE_CLOSE
0x302, # NDMP_TAPE_GET_STATE
0x303, # NDMP_TAPE_MTIO
0x304, # NDMP_TAPE_WRITE
0x305, # NDMP_TAPE_READ
0x307, # NDMP_TAPE_EXECUTE_CDB
# Data Interface
0x400, # NDMP_DATA_GET_STATE
0x401, # NDMP_DATA_START_BACKUP
0x402, # NDMP_DATA_START_RECOVER
0x403, # NDMP_DATA_ABORT
0x404, # NDMP_DATA_GET_ENV
0x407, # NDMP_DATA_STOP
0x409, # NDMP_DATA_LISTEN
0x40a, # NDMP_DATA_CONNECT
# Notify Interface
0x501, # NDMP_NOTIFY_DATA_HALTED
0x502, # NDMP_NOTIFY_CONNECTED
0x503, # NDMP_NOTIFY_MOVER_HALTED
0x504, # NDMP_NOTIFY_MOVER_PAUSED
0x505, # NDMP_NOTIFY_DATA_READ
# Log Interface
0x602, # NDMP_LOG_FILES
0x603, # NDMP_LOG_MESSAGE
# File History Interface
0x703, # NDMP_FH_ADD_FILE
0x704, # NDMP_FH_ADD_DIR
0x705, # NDMP_FH_ADD_NODE
# Mover Interface
0xa00, # NDMP_MOVER_GET_STATE
0xa01, # NDMP_MOVER_LISTEN
0xa02, # NDMP_MOVER_CONTINUE
0xa03, # NDMP_MOVER_ABORT
0xa04, # NDMP_MOVER_STOP
0xa05, # NDMP_MOVER_SET_WINDOW
0xa06, # NDMP_MOVER_READ
0xa07, # NDMP_MOVER_CLOSE
0xa08, # NDMP_MOVER_SET_RECORD_SIZE
0xa09, # NDMP_MOVER_CONNECT
# Reserved for the vendor specific usage (from 0xf000 to 0xffff)
0xf000, # NDMP_VENDORS_BASE
# Reserved for Prototyping (from 0xff00 to 0xffff)
0xff00, # NDMP_RESERVED_BASE
]
########################################################################################################################
s_initialize("Veritas NDMP_CONECT_CLIENT_AUTH")
# the first bit is the last frag flag, we'll always set it and truncate our size to 3 bytes.
# 3 bytes of size gives us a max 16mb ndmp message, plenty of space.
s_static("\x80")
s_size("request", length=3, endian=">")
if s_block_start("request"):
if s_block_start("ndmp header"):
s_static(struct.pack(">L", 1), name="sequence")
s_static(struct.pack(">L", time.time()), name="timestamp")
s_static(struct.pack(">L", 0), name="message type") # request (0)
s_static(struct.pack(">L", 0x901), name="NDMP_CONECT_CLIENT_AUTH")
s_static(struct.pack(">L", 1), name="reply sequence")
s_static(struct.pack(">L", 0), name="error")
s_block_end("ndmp header")
s_group("auth types", values=[struct.pack(">L", 190), struct.pack(">L", 5), struct.pack(">L", 4)])
if s_block_start("body", group="auth types"):
# do random data.
s_random(0, min_length=1000, max_length=50000, num_mutations=500)
# random valid XDR string.
#s_lego("xdr_string", "pedram")
s_block_end("body")
s_block_end("request")
########################################################################################################################
s_initialize("Veritas Proprietary Message Types")
# the first bit is the last frag flag, we'll always set it and truncate our size to 3 bytes.
# 3 bytes of size gives us a max 16mb ndmp message, plenty of space.
s_static("\x80")
s_size("request", length=3, endian=">")
if s_block_start("request"):
if s_block_start("ndmp header"):
s_static(struct.pack(">L", 1), name="sequence")
s_static(struct.pack(">L", time.time()), name="timestamp")
s_static(struct.pack(">L", 0), name="message type") # request (0)
s_group("prop ops", values = \
[
struct.pack(">L", 0xf315), # file list?
struct.pack(">L", 0xf316),
struct.pack(">L", 0xf317),
struct.pack(">L", 0xf200), #
struct.pack(">L", 0xf201),
struct.pack(">L", 0xf202),
struct.pack(">L", 0xf31b),
struct.pack(">L", 0xf270), # send strings like NDMP_PROP_PEER_PROTOCOL_VERSION
struct.pack(">L", 0xf271),
struct.pack(">L", 0xf33b),
struct.pack(">L", 0xf33c),
])
s_static(struct.pack(">L", 1), name="reply sequence")
s_static(struct.pack(">L", 0), name="error")
s_block_end("ndmp header")
if s_block_start("body", group="prop ops"):
s_random("\x00\x00\x00\x00", min_length=1000, max_length=50000, num_mutations=100)
s_block_end("body")
s_block_end("request")
| 5,379
|
Python
|
.py
| 128
| 35.140625
| 120
| 0.572522
|
OpenRCE/sulley
| 1,416
| 338
| 56
|
GPL-2.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
16,027
|
http_post.py
|
OpenRCE_sulley/requests/http_post.py
|
from sulley import *
########################################################################################################################
# All POST mimetypes that I could think of/find
########################################################################################################################
# List of all blocks defined here (for easy copy/paste)
"""
sess.connect(s_get("HTTP VERBS POST"))
sess.connect(s_get("HTTP VERBS POST ALL"))
sess.connect(s_get("HTTP VERBS POST REQ"))
"""
########################################################################################################################
# Fuzz POST requests with most MIMETypes known
########################################################################################################################
s_initialize("HTTP VERBS POST ALL")
s_static("POST / HTTP/1.1\r\n")
s_static("Content-Type: ")
s_group("mimetypes",values=["audio/basic","audio/x-mpeg","drawing/x-dwf","graphics/x-inventor","image/x-portable-bitmap",
"message/external-body","message/http","message/news","message/partial","message/rfc822",
"multipart/alternative","multipart/appledouble","multipart/digest","multipart/form-data",
"multipart/header-set","multipart/mixed","multipart/parallel","multipart/related","multipart/report",
"multipart/voice-message","multipart/x-mixed-replace","text/css","text/enriched","text/html",
"text/javascript","text/plain","text/richtext","text/sgml","text/tab-separated-values","text/vbscript",
"video/x-msvideo","video/x-sgi-movie","workbook/formulaone","x-conference/x-cooltalk","x-form/x-openscape",
"x-music/x-midi","x-script/x-wfxclient","x-world/x-3dmf"])
if s_block_start("mime", group="mimetypes"):
s_static("\r\n")
s_static("Content-Length: ")
s_size("post blob", format="ascii", signed=True, fuzzable=True)
s_static("\r\n\r\n")
s_block_end()
if s_block_start("post blob"):
s_string("A"*100 + "=" + "B"*100)
s_block_end()
s_static("\r\n\r\n")
########################################################################################################################
# Basic fuzz of post payloads
########################################################################################################################
s_initialize("HTTP VERBS POST")
s_static("POST / HTTP/1.1\r\n")
s_static("Content-Type: ")
s_string("application/x-www-form-urlencoded")
s_static("\r\n")
s_static("Content-Length: ")
s_size("post blob", format="ascii", signed=True, fuzzable=True)
s_static("\r\n")
if s_block_start("post blob"):
s_string("A"*100 + "=" + "B"*100)
s_block_end()
s_static("\r\n\r\n")
########################################################################################################################
# Fuzz POST request MIMETypes
########################################################################################################################
s_initialize("HTTP VERBS POST REQ")
s_static("POST / HTTP/1.1\r\n")
s_static("Content-Type: ")
s_string("application")
s_delim("/")
s_string("x")
s_delim("-")
s_string("www")
s_delim("-")
s_string("form")
s_delim("-")
s_string("urlencoded")
s_static("\r\n")
s_static("Content-Length: ")
s_size("post blob", format="ascii", signed=True, fuzzable=True)
s_static("\r\n")
if s_block_start("post blob"):
s_string("A"*100 + "=" + "B"*100)
s_block_end()
s_static("\r\n\r\n")
| 3,483
|
Python
|
.py
| 72
| 45.097222
| 126
| 0.475352
|
OpenRCE/sulley
| 1,416
| 338
| 56
|
GPL-2.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
16,028
|
jabber.py
|
OpenRCE_sulley/requests/jabber.py
|
from sulley import *
########################################################################################################################
s_initialize("chat init")
"""
<?xml version="1.0" encoding="UTF-8" ?>
<stream:stream to="192.168.200.17" xmlns="jabber:client" xmlns:stream="http://etherx.jabber.org/streams">
"""
# i'll fuzz these bitches later.
# TODO: still need to figure out how to incorporate dynamic IPs
s_static('<?xml version="1.0" encoding="UTF-8" ?>')
s_static('<stream:stream to="152.67.137.126" xmlns="jabber:client" xmlns:stream="http://etherx.jabber.org/streams">')
########################################################################################################################
s_initialize("chat message")
s_static('<message to="TSR@GIZMO" type="chat">\n')
s_static('<body></body>\n')
s_static('<html xmlns="http://www.w3.org/1999/xhtml"><body></body></html><x xmlns="jabber:x:event">\n')
s_static('<composing/>\n')
s_static('<id></id>\n')
s_static('</x>\n')
s_static('</message>\n')
# s_static('<message to="TSR@GIZMO" type="chat">\n')
s_delim("<")
s_string("message")
s_delim(" ")
s_string("to")
s_delim("=")
s_delim('"')
s_string("TSR@GIZMO")
s_delim('"')
s_static(' type="chat"')
s_delim(">")
s_delim("\n")
# s_static('<body>hello from python!</body>\n')
s_static("<body>")
s_string("hello from python!")
s_static("</body>\n")
# s_static('<html xmlns="http://www.w3.org/1999/xhtml"><body><font face="Helvetica" ABSZ="12" color="#000000">hello from python</font></body></html><x xmlns="jabber:x:event">\n')
s_static('<html xmlns="http://www.w3.org/1999/xhtml"><body>')
s_static("<")
s_string("font")
s_static(' face="')
s_string("Helvetica")
s_string('" ABSZ="')
s_word(12, format="ascii", signed=True)
s_static('" color="')
s_string("#000000")
s_static('">')
s_string("hello from python")
s_static('</font></body></html><x xmlns="jabber:x:event">\n')
s_static('<composing/>\n')
s_static('</x>\n')
s_static('</message>\n')
| 1,969
|
Python
|
.py
| 52
| 36.673077
| 178
| 0.579444
|
OpenRCE/sulley
| 1,416
| 338
| 56
|
GPL-2.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
16,029
|
http_get.py
|
OpenRCE_sulley/requests/http_get.py
|
from sulley import *
########################################################################################################################
# All HTTP requests that I could think of/find
########################################################################################################################
# List of all blocks defined here (for easy copy/paste)
"""
sess.connect(s_get("HTTP VERBS"))
sess.connect(s_get("HTTP METHOD"))
sess.connect(s_get("HTTP REQ"))
"""
########################################################################################################################
# Fuzz all the publicly avalible methods known for HTTP Servers
########################################################################################################################
s_initialize("HTTP VERBS")
s_group("verbs", values=["GET", "HEAD", "POST", "OPTIONS", "TRACE", "PUT", "DELETE", "PROPFIND","CONNECT","PROPPATCH",
"MKCOL","COPY","MOVE","LOCK","UNLOCK","VERSION-CONTROL","REPORT","CHECKOUT","CHECKIN","UNCHECKOUT",
"MKWORKSPACE","UPDATE","LABEL","MERGE","BASELINE-CONTROL","MKACTIVITY","ORDERPATCH","ACL","PATCH","SEARCH","CAT"])
if s_block_start("body", group="verbs"):
s_delim(" ")
s_delim("/")
s_string("index.html")
s_delim(" ")
s_string("HTTP")
s_delim("/")
s_int(1,format="ascii")
s_delim(".")
s_int(1,format="ascii")
s_static("\r\n\r\n")
s_block_end()
########################################################################################################################
# Fuzz the HTTP Method itself
########################################################################################################################
s_initialize("HTTP METHOD")
s_string("FUZZ")
s_static(" /index.html HTTP/1.1")
s_static("\r\n\r\n")
########################################################################################################################
# Fuzz this standard multi-header HTTP request
# GET / HTTP/1.1
# Host: www.google.com
# Connection: keep-alive
# User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.83 Safari/537.1
# Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
# Accept-Encoding: gzip,deflate,sdch
# Accept-Language: en-US,en;q=0.8
# Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
########################################################################################################################
s_initialize("HTTP REQ")
s_static("GET / HTTP/1.1\r\n")
# Host: www.google.com
s_static("Host")
s_delim(":")
s_delim(" ")
s_string("www.google.com")
s_static("\r\n")
# Connection: keep-alive
s_static("Connection")
s_delim(":")
s_delim(" ")
s_string("Keep-Alive")
# User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.83 Safari/537.1
s_static("User-Agent")
s_delim(":")
s_delim(" ")
s_string("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.83 Safari/537.1")
s_static("\r\n")
# Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
s_static("Accept")
s_delim(":")
s_delim(" ")
s_string("text")
s_delim("/")
s_string("html")
s_delim(",")
s_string("application")
s_delim("/")
s_string("xhtml")
s_delim("+")
s_string("xml")
s_delim(",")
s_string("application")
s_delim("/")
s_string("xml")
s_delim(";")
s_string("q")
s_delim("=")
s_int(0,format="ascii")
s_delim(".")
s_int(9,format="ascii")
s_delim(",")
s_string("*")
s_delim("/")
s_string("*")
s_delim(";")
s_string("q")
s_delim("=")
s_int(0,format="ascii")
s_delim(".")
s_int(8,format="ascii")
s_static("\r\n")
# Accept-Encoding: gzip,deflate,sdch
s_static("Accept-Encoding")
s_delim(":")
s_delim(" ")
s_string("gzip")
s_delim(",")
s_string("deflate")
s_delim(",")
s_string("sdch")
s_static("\r\n")
# Accept-Language: en-US,en;q=0.8
s_static("Accept-Language")
s_delim(":")
s_delim(" ")
s_string("en-US")
s_delim(",")
s_string("en")
s_delim(";")
s_string("q")
s_delim("=")
s_string("0.8")
s_static("\r\n")
# Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
s_static("Accept-Charset")
s_delim(":")
s_delim(" ")
s_string("ISO")
s_delim("-")
s_int(8859,format="ascii")
s_delim("-")
s_int(1,format="ascii")
s_delim(",")
s_string("utf-8")
s_delim(";")
s_string("q")
s_delim("=")
s_int(0,format="ascii")
s_delim(".")
s_int(7,format="ascii")
s_delim(",")
s_string("*")
s_delim(";")
s_string("q")
s_delim("=")
s_int(0,format="ascii")
s_delim(".")
s_int(3,format="ascii")
s_static("\r\n\r\n")
| 4,547
|
Python
|
.py
| 148
| 29.094595
| 139
| 0.508644
|
OpenRCE/sulley
| 1,416
| 338
| 56
|
GPL-2.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
16,030
|
xbox.py
|
OpenRCE_sulley/requests/xbox.py
|
"""
mediaconnect port 2869
"""
from sulley import *
########################################################################################################################
s_initialize("mediaconnect: get album list")
# POST /upnphost/udhisapi.dll?control=uuid:848a20cc-91bc-4a02-8180-187baa537527+urn:microsoft-com:serviceId:MSContentDirectory HTTP/1.1
s_group("verbs", values=["GET", "POST"])
s_delim(" ")
s_delim("/")
s_string("upnphost/udhisapi.dll")
s_delim("?")
s_string("control")
s_delim("=")
s_string("uuid")
s_delim(":")
s_string("848a20cc-91bc-4a02-8180-187baa537527")
s_delim("+")
s_static("urn")
s_delim(":")
s_string("microsoft-com:serviceId:MSContentDirectory")
s_static(" HTTP/1.1\r\n")
# User-Agent: Xbox/2.0.4552.0 UPnP/1.0 Xbox/2.0.4552.0
# we take this opportunity to fuzz headers in general.
s_string("User-Agent")
s_delim(":")
s_delim(" ")
s_string("Xbox")
s_delim("/")
s_string("2.0.4552.0 UPnP/1.0 Xbox/2.0.4552.0")
s_static("\r\n")
# Connection: Keep-alive
s_static("Connection: ")
s_string("Keep-alive")
s_static("\r\n")
# Host:10.10.20.111
s_static("Host: 10.10.20.111")
s_static("\r\n")
# SOAPACTION: "urn:schemas-microsoft-com:service:MSContentDirectory:1#Search"
s_static("SOAPACTION: ")
s_delim("\"")
s_static("urn")
s_delim(":")
s_string("schemas-microsoft-com")
s_static(":")
s_string("service")
s_static(":")
s_string("MSContentDirectory")
s_static(":")
s_string("1")
s_delim("#")
s_string("Search")
s_delim("\"")
s_static("\r\n")
# CONTENT-TYPE: text/xml; charset="utf-8"
s_static("CONTENT-TYPE: text/xml; charset=\"utf-8\"")
s_static("\r\n")
# Content-Length: 547
s_static("Content-Length: ")
s_sizer("content", format="ascii", signed=True, fuzzable=True)
s_static("\r\n\r\n")
if s_block_start("content"):
# <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
s_delim("<")
s_string("s")
s_delim(":")
s_string("Envelope")
s_static(" xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" ")
s_static("s:")
s_string("encodingStyle")
s_delim("=")
s_string("\"http://schemas.xmlsoap.org/soap/encoding/\"")
s_delim(">")
s_static("<s:Body>")
s_static("<u:Search xmlns:u=\"urn:schemas-microsoft-com:service:MSContentDirectory:1\">")
# <ContainerID>7</ContainerID>
s_static("<ContainerID>")
s_dword(7, format="ascii", signed=True)
s_static("</ContainerID>")
# <SearchCriteria>(upnp:class = "object.container.album.musicAlbum")</SearchCriteria>
s_static("<SearchCriteria>(upnp:class = "")
s_string("object.container.album.musicAlbum")
s_static("")</SearchCriteria>")
# <Filter>dc:title,upnp:artist</Filter>
s_static("<Filter>")
s_delim("dc")
s_delim(":")
s_string("title")
s_delim(",")
s_string("upnp")
s_delim(":")
s_string("artist")
s_static("</Filter>")
# <StartingIndex>0</StartingIndex>
s_static("<StartingIndex>")
s_dword(0, format="ascii", signed=True)
s_static("</StartingIndex>")
# <RequestedCount>1000</RequestedCount>
s_static("<RequestedCount>")
s_dword(1000, format="ascii", signed=True)
s_static("</RequestedCount>")
s_static("<SortCriteria>+dc:title</SortCriteria>")
s_static("</u:Search>")
s_static("</s:Body>")
# </s:Envelope>
s_delim("<")
s_delim("/")
s_delim("s")
s_delim(":")
s_string("Envelope")
s_delim(">")
s_block_end()
| 3,477
|
Python
|
.py
| 112
| 28.133929
| 135
| 0.638482
|
OpenRCE/sulley
| 1,416
| 338
| 56
|
GPL-2.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
16,031
|
__init__.py
|
OpenRCE_sulley/requests/__init__.py
|
import os
__all__ = []
for filename in os.listdir(os.path.dirname(__file__)):
if not filename.startswith("__") and filename.endswith(".py"):
filename = filename.replace(".py", "")
__all__.append(filename)
# uncommenting the next line causes all requests to load into the namespace once 'requests' is imported.
# this is not the desired behaviour, instead the user should import individual packages of requests. ie:
# from requests import http, trend
#__import__("requests."+filename)
| 542
|
Python
|
.py
| 10
| 47.6
| 112
| 0.668561
|
OpenRCE/sulley
| 1,416
| 338
| 56
|
GPL-2.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
16,032
|
stun.py
|
OpenRCE_sulley/requests/stun.py
|
"""
STUN: Simple Traversal of UDP through NAT
Gizmo binds this service on UDP port 5004 / 5005
http://www.vovida.org/
"""
from sulley import *
########################################################################################################################
s_initialize("binding request")
# message type 0x0001: binding request.
s_static("\x00\x01")
# message length.
s_sizer("attributes", length=2, endian=">", name="message length", fuzzable=True)
# message transaction id.
s_static("\x00\x11\x22\x33\x44\x55\x66\x77\x88\x99\xaa\xbb\xcc\xdd\xee\xff")
if s_block_start("attributes"):
# attribute type
# 0x0001: mapped address
# 0x0003: change request
# 0x0004: source address
# 0x0005: changed address
# 0x8020: xor mapped address
# 0x8022: server
s_word(0x0003, endian=">")
s_sizer("attribute", length=2, endian=">", name="attribute length", fuzzable=True)
if s_block_start("attribute"):
# default valid null block
s_string("\x00\x00\x00\x00")
s_block_end()
s_block_end()
# toss out some large strings when the lengths are anything but valid.
if s_block_start("fuzz block 1", dep="attribute length", dep_value=4, dep_compare="!="):
s_static("A"*5000)
s_block_end()
# toss out some large strings when the lengths are anything but valid.
if s_block_start("fuzz block 2", dep="message length", dep_value=8, dep_compare="!="):
s_static("B"*5000)
s_block_end()
########################################################################################################################
s_initialize("binding response")
# message type 0x0101: binding response
| 1,652
|
Python
|
.py
| 40
| 38.275
| 120
| 0.595372
|
OpenRCE/sulley
| 1,416
| 338
| 56
|
GPL-2.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
16,033
|
http_header.py
|
OpenRCE_sulley/requests/http_header.py
|
from sulley import *
########################################################################################################################
# List of all HTTP Headers I could find
########################################################################################################################
# List of all blocks defined here (for easy copy/paste)
"""
sess.connect(s_get("HTTP HEADER ACCEPT"))
sess.connect(s_get("HTTP HEADER ACCEPTCHARSET"))
sess.connect(s_get("HTTP HEADER ACCEPTDATETIME"))
sess.connect(s_get("HTTP HEADER ACCEPTENCODING"))
sess.connect(s_get("HTTP HEADER ACCEPTLANGUAGE"))
sess.connect(s_get("HTTP HEADER AUTHORIZATION"))
sess.connect(s_get("HTTP HEADER CACHECONTROL"))
sess.connect(s_get("HTTP HEADER CLOSE"))
sess.connect(s_get("HTTP HEADER CONTENTLENGTH"))
sess.connect(s_get("HTTP HEADER CONTENTMD5"))
sess.connect(s_get("HTTP HEADER COOKIE"))
sess.connect(s_get("HTTP HEADER DATE"))
sess.connect(s_get("HTTP HEADER DNT"))
sess.connect(s_get("HTTP HEADER EXPECT"))
sess.connect(s_get("HTTP HEADER FROM"))
sess.connect(s_get("HTTP HEADER HOST"))
sess.connect(s_get("HTTP HEADER IFMATCH"))
sess.connect(s_get("HTTP HEADER IFMODIFIEDSINCE"))
sess.connect(s_get("HTTP HEADER IFNONEMATCH"))
sess.connect(s_get("HTTP HEADER IFRANGE"))
sess.connect(s_get("HTTP HEADER IFUNMODIFIEDSINCE"))
sess.connect(s_get("HTTP HEADER KEEPALIVE"))
sess.connect(s_get("HTTP HEADER MAXFORWARDS"))
sess.connect(s_get("HTTP HEADER PRAGMA"))
sess.connect(s_get("HTTP HEADER PROXYAUTHORIZATION"))
sess.connect(s_get("HTTP HEADER RANGE"))
sess.connect(s_get("HTTP HEADER REFERER"))
sess.connect(s_get("HTTP HEADER TE"))
sess.connect(s_get("HTTP HEADER UPGRADE"))
sess.connect(s_get("HTTP HEADER USERAGENT"))
sess.connect(s_get("HTTP HEADER VIA"))
sess.connect(s_get("HTTP HEADER WARNING"))
sess.connect(s_get("HTTP HEADER XATTDEVICEID"))
sess.connect(s_get("HTTP HEADER XDONOTTRACK"))
sess.connect(s_get("HTTP HEADER XFORWARDEDFOR"))
sess.connect(s_get("HTTP HEADER XREQUESTEDWITH"))
sess.connect(s_get("HTTP HEADER XWAPPROFILE"))
"""
########################################################################################################################
# Fuzz Accept header
# Accept: text/*;q=0.3, text/html;q=0.7, text/html;level=1, text/html;level=2;q=0.4, */*;q=0.5
########################################################################################################################
s_initialize("HTTP HEADER ACCEPT")
s_static("GET / HTTP/1.1\r\n")
s_static("Accept")
s_delim(":")
s_delim(" ")
s_string("text")
s_delim("/")
s_string("*")
s_delim(";")
s_string("q")
s_delim("=")
s_int(0,format="ascii")
s_delim(".")
s_int(3,format="ascii")
s_delim(",")
s_delim(" ")
s_string("text")
s_delim("/")
s_string("html")
s_delim(";")
s_string("q")
s_delim("=")
s_int(0,format="ascii")
s_delim(".")
s_int(7,format="ascii")
s_delim(",")
s_delim(" ")
s_string("text")
s_delim("/")
s_string("html")
s_delim(";")
s_string("level")
s_delim("=")
s_string("1")
s_delim(",")
s_delim(" ")
s_string("text")
s_delim("/")
s_string("html")
s_delim(";")
s_string("level")
s_delim("=")
s_int(2,format="ascii")
s_delim(";")
s_string("q")
s_delim("=")
s_int(0,format="ascii")
s_delim(".")
s_int(4,format="ascii")
s_delim(",")
s_delim(" ")
s_string("*")
s_delim("/")
s_string("*")
s_delim(";")
s_string("q")
s_delim("=")
s_int(0,format="ascii")
s_delim(".")
s_int(5,format="ascii")
s_static("\r\n\r\n")
########################################################################################################################
# Fuzz Accept-Charset header
# Accept-Charset: utf-8, unicode-1-1;q=0.8
########################################################################################################################
s_initialize("HTTP HEADER ACCEPTCHARSET")
s_static("GET / HTTP/1.1\r\n")
s_static("Accept-Charset")
s_delim(":")
s_delim(" ")
s_string("utf")
s_delim("-")
s_int(8,format="ascii")
s_delim(",")
s_delim(" ")
s_string("unicode")
s_delim("-")
s_int(1,format="ascii")
s_delim("-")
s_int(1,format="ascii")
s_delim(";")
s_string("q")
s_delim("=")
s_int(0,format="ascii")
s_delim(".")
s_int(8,format="ascii")
s_static("\r\n\r\n")
########################################################################################################################
# Fuzz Accept-Datetime header
# Accept-Datetime: Thu, 31 May 2007 20:35:00 GMT
########################################################################################################################
s_initialize("HTTP HEADER ACCEPTDATETIME")
s_static("GET / HTTP/1.1\r\n")
s_static("Accept-Datetime")
s_delim(":")
s_delim(" ")
s_string("Thu")
s_delim(",")
s_delim(" ")
s_string("31")
s_delim(" ")
s_string("May")
s_delim(" ")
s_string("2007")
s_delim(" ")
s_string("20")
s_delim(":")
s_string("35")
s_delim(":")
s_string("00")
s_delim(" ")
s_string("GMT")
s_static("\r\n\r\n")
########################################################################################################################
# Fuzz Accept-Encoding header
# Accept-Encoding: gzip, deflate
########################################################################################################################
s_initialize("HTTP HEADER ACCEPTENCODING")
s_static("GET / HTTP/1.1\r\n")
s_static("Accept-Encoding")
s_delim(":")
s_delim(" ")
s_string("gzip")
s_delim(", ")
s_string("deflate")
s_static("\r\n\r\n")
########################################################################################################################
# Fuzz Accept-Language header
# Accept-Language: en-us, en;q=0.5
########################################################################################################################
s_initialize("HTTP HEADER ACCEPTLANGUAGE")
s_static("GET / HTTP/1.1\r\n")
s_static("Accept-Language")
s_delim(":")
s_delim(" ")
s_string("en-us")
s_delim(",")
s_string("en")
s_delim(";")
s_string("q")
s_delim("=")
s_string("0.5")
s_static("\r\n\r\n")
########################################################################################################################
# Fuzz Authorization header
# Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
########################################################################################################################
s_initialize("HTTP HEADER AUTHORIZATION")
s_static("GET / HTTP/1.1\r\n")
s_static("Authorization")
s_delim(":")
s_delim(" ")
s_string("Basic")
s_delim(" ")
s_string("QWxhZGRpbjpvcGVuIHNlc2FtZQ==")
s_static("\r\n\r\n")
########################################################################################################################
# Fuzz Cache-Control header
# Cache-Control: no-cache
########################################################################################################################
s_initialize("HTTP HEADER CACHECONTROL")
s_static("GET / HTTP/1.1\r\n")
s_static("Cache-Control")
s_delim(":")
s_delim(" ")
s_string("no")
s_delim("-")
s_string("cache")
s_static("\r\n\r\n")
########################################################################################################################
# Fuzz Connection header
# Connection: close
########################################################################################################################
s_initialize("HTTP HEADER CLOSE")
s_static("GET / HTTP/1.1\r\n")
s_static("Connection")
s_delim(":")
s_delim(" ")
s_string("close")
s_static("\r\n\r\n")
########################################################################################################################
# Fuzz Content Length header
# Content-Length: 348
########################################################################################################################
s_initialize("HTTP HEADER CONTENTLENGTH")
s_static("GET / HTTP/1.1\r\n")
s_static("Content-Length")
s_delim(":")
s_delim(" ")
s_string("348")
s_static("\r\n\r\n")
########################################################################################################################
# Fuzz Content MD5 header
# Content-MD5: Q2hlY2sgSW50ZWdyaXR5IQ==
########################################################################################################################
s_initialize("HTTP HEADER CONTENTMD5")
s_static("GET / HTTP/1.1\r\n")
s_static("Content-MD5")
s_delim(":")
s_delim(" ")
s_string("Q2hlY2sgSW50ZWdyaXR5IQ==")
s_static("\r\n\r\n")
########################################################################################################################
# Fuzz COOKIE header
# Cookie: PHPSESSIONID=hLKQPySBvyTRq5K5RJmcTHQVtQycmwZG3Qvr0tSy2w9mQGmbJbJn;
########################################################################################################################
s_initialize("HTTP HEADER COOKIE")
s_static("GET / HTTP/1.1\r\n")
if s_block_start("cookie"):
s_static("Cookie")
s_delim(":")
s_delim(" ")
s_string("PHPSESSIONID")
s_delim("=")
s_string("hLKQPySBvyTRq5K5RJmcTHQVtQycmwZG3Qvr0tSy2w9mQGmbJbJn")
s_static(";")
s_static("\r\n")
s_block_end()
s_repeat("cookie", max_reps=5000, step=500)
s_static("\r\n\r\n")
########################################################################################################################
# Fuzz Date header
# Date: Tue, 15 Nov 2012 08:12:31 EST
########################################################################################################################
s_initialize("HTTP HEADER DATE")
s_static("GET / HTTP/1.1\r\n")
s_static("Date")
s_delim(":")
s_delim(" ")
s_string("Tue")
s_delim(",")
s_delim(" ")
s_string("15")
s_delim(" ")
s_string("Nov")
s_delim(" ")
s_string("2012")
s_delim(" ")
s_string("08")
s_delim(":")
s_string("12")
s_delim(":")
s_string("31")
s_delim(" ")
s_string("EST")
s_static("\r\n\r\n")
########################################################################################################################
# Fuzz DNT header -> May be same as X-Do-Not-Track?
# DNT: 1
########################################################################################################################
s_initialize("HTTP HEADER DNT")
s_static("GET / HTTP/1.1\r\n")
s_static("DNT")
s_delim(":")
s_delim(" ")
s_string("1")
s_static("\r\n\r\n")
########################################################################################################################
# Fuzz Expect header
# Expect: 100-continue
########################################################################################################################
s_initialize("HTTP HEADER EXPECT")
s_static("GET / HTTP/1.1\r\n")
s_static("Expect")
s_delim(":")
s_delim(" ")
s_string("100")
s_delim("-")
s_string("continue")
s_static("\r\n\r\n")
########################################################################################################################
# Fuzz From header
# From: derp@derp.com
########################################################################################################################
s_initialize("HTTP HEADER FROM")
s_static("GET / HTTP/1.1\r\n")
s_static("From")
s_delim(":")
s_delim(" ")
s_string("derp")
s_delim("@")
s_string("derp")
s_delim(".")
s_string("com")
s_static("\r\n\r\n")
########################################################################################################################
# Fuzz Host header
# Host: 127.0.0.1
########################################################################################################################
s_initialize("HTTP HEADER HOST")
s_static("GET / HTTP/1.1\r\n")
s_static("Host")
s_delim(":")
s_delim(" ")
s_string("127.0.0.1")
s_static("\r\n")
s_string("Connection")
s_delim(":")
s_delim(" ")
s_string("Keep-Alive")
s_static("\r\n\r\n")
########################################################################################################################
# Fuzz If-Match header
# If-Match: "737060cd8c284d8af7ad3082f209582d"
########################################################################################################################
s_initialize("HTTP HEADER IFMATCH")
s_static("GET / HTTP/1.1\r\n")
s_static("If-Match")
s_delim(":")
s_delim(" ")
s_static("\"")
s_string("737060cd8c284d8af7ad3082f209582d")
s_static("\"")
s_static("\r\n\r\n")
########################################################################################################################
# Fuzz If-Modified-Since header
# If-Modified-Since: Sat, 29 Oct 2012 19:43:31 ESTc
########################################################################################################################
s_initialize("HTTP HEADER IFMODIFIEDSINCE")
s_static("GET / HTTP/1.1\r\n")
s_static("If-Modified-Since")
s_delim(":")
s_delim(" ")
s_string("Sat")
s_delim(",")
s_delim(" ")
s_string("29")
s_delim(" ")
s_string("Oct")
s_delim(" ")
s_string("2012")
s_delim(" ")
s_string("08")
s_delim(":")
s_string("12")
s_delim(":")
s_string("31")
s_delim(" ")
s_string("EST")
s_static("\r\n\r\n")
########################################################################################################################
# Fuzz If-None-Match header
# If-None-Match: "737060cd8c284d8af7ad3082f209582d"
########################################################################################################################
s_initialize("HTTP HEADER IFNONEMATCH")
s_static("GET / HTTP/1.1\r\n")
s_static("If-None-Match")
s_delim(":")
s_delim(" ")
s_static("\"")
s_string("737060cd8c284d8af7ad3082f209582d")
s_static("\"")
s_static("\r\n\r\n")
########################################################################################################################
# Fuzz If-Range header
# If-Range: "737060cd8c284d8af7ad3082f209582d"
########################################################################################################################
s_initialize("HTTP HEADER IFRANGE")
s_static("GET / HTTP/1.1\r\n")
s_static("If-Range")
s_delim(":")
s_delim(" ")
s_static("\"")
s_string("737060cd8c284d8af7ad3082f209582d")
s_static("\"")
s_static("\r\n\r\n")
########################################################################################################################
# Fuzz If-Unmodified-Since header
# If-Unmodified-Since: Sat, 29 Oct 2012 19:43:31 EST
########################################################################################################################
s_initialize("HTTP HEADER IFUNMODIFIEDSINCE")
s_static("GET / HTTP/1.1\r\n")
s_static("If-Unmodified-Since")
s_delim(":")
s_delim(" ")
s_string("Sat")
s_delim(",")
s_delim(" ")
s_string("29")
s_delim(" ")
s_string("Oct")
s_delim(" ")
s_string("2012")
s_delim(" ")
s_string("08")
s_delim(":")
s_string("12")
s_delim(":")
s_string("31")
s_delim(" ")
s_string("EST")
s_static("\r\n\r\n")
########################################################################################################################
# Fuzz KeepAlive header
# Keep-Alive: 300
########################################################################################################################
s_initialize("HTTP HEADER KEEPALIVE")
s_static("GET / HTTP/1.1\r\n")
s_static("Keep-Alive")
s_delim(":")
s_delim(" ")
s_string("300")
s_static("\r\n\r\n")
########################################################################################################################
# Fuzz Max-Fowards header
# Max-Forwards: 80
########################################################################################################################
s_initialize("HTTP HEADER MAXFORWARDS")
s_static("GET / HTTP/1.1\r\n")
s_static("Max-Forwards")
s_delim(":")
s_delim(" ")
s_string("80")
s_static("\r\n\r\n")
########################################################################################################################
# Fuzz Pragma header
# Pragma: no-cache
########################################################################################################################
s_initialize("HTTP HEADER PRAGMA")
s_static("GET / HTTP/1.1\r\n")
s_static("Pragma")
s_delim(":")
s_delim(" ")
s_string("no-cache")
s_static("\r\n\r\n")
########################################################################################################################
# Fuzz Proxy-Authorization header
# Proxy-Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
########################################################################################################################
s_initialize("HTTP HEADER PROXYAUTHORIZATION")
s_static("GET / HTTP/1.1\r\n")
s_static("Proxy-Authorization")
s_delim(":")
s_delim(" ")
s_string("Basic")
s_delim(" ")
s_string("QWxhZGRpbjpvcGVuIHNlc2FtZQ==")
s_static("\r\n\r\n")
########################################################################################################################
# Fuzz Range header
# Range: bytes=500-999
########################################################################################################################
s_initialize("HTTP HEADER RANGE")
s_static("GET / HTTP/1.1\r\n")
s_static("Range")
s_delim(":")
s_delim(" ")
s_string("bytes")
s_delim("=")
s_string("500")
s_delim("-")
s_string("999")
s_static("\r\n\r\n")
########################################################################################################################
# Fuzz Referer header
# Referer: http://www.google.com
########################################################################################################################
s_initialize("HTTP HEADER REFERER")
s_static("GET / HTTP/1.1\r\n")
s_static("Referer")
s_delim(":")
s_delim(" ")
s_string("http://www.google.com")
s_static("\r\n\r\n")
########################################################################################################################
# Fuzz TE header
# TE: trailers, deflate
########################################################################################################################
s_initialize("HTTP HEADER TE")
s_static("GET / HTTP/1.1\r\n")
s_static("TE")
s_delim(":")
s_delim(" ")
s_string("trailers")
s_delim(",")
s_delim(" ")
s_string("deflate")
s_static("\r\n\r\n")
########################################################################################################################
# Fuzz Upgrade header
# Upgrade: HTTP/2.0, SHTTP/1.3, IRC/6.9, RTA/x11
########################################################################################################################
s_initialize("HTTP HEADER UPGRADE")
s_static("GET / HTTP/1.1\r\n")
s_static("Upgrade")
s_delim(":")
s_delim(" ")
s_string("HTTP")
s_delim("/")
s_string("2")
s_delim(".")
s_string("0")
s_delim(",")
s_delim(" ")
s_string("SHTTP")
s_delim("/")
s_string("1")
s_delim(".")
s_string("3")
s_delim(",")
s_delim(" ")
s_string("IRC")
s_delim("/")
s_string("6")
s_delim(".")
s_string("9")
s_delim(",")
s_delim(" ")
s_string("RTA")
s_delim("/")
s_string("x11")
s_static("\r\n\r\n")
########################################################################################################################
# Fuzz User Agent header
# User-Agent: Mozilla/5.0 (Windows; U)
########################################################################################################################
s_initialize("HTTP HEADER USERAGENT")
s_static("GET / HTTP/1.1\r\n")
s_static("User-Agent")
s_delim(":")
s_delim(" ")
s_string("Mozilla/5.0 (Windows; U)")
s_static("\r\n\r\n")
########################################################################################################################
# Fuzz Via header
# Via: 1.0 derp, 1.1 derp.com (Apache/1.1)
########################################################################################################################
s_initialize("HTTP HEADER VIA")
s_static("GET / HTTP/1.1\r\n")
s_static("Via")
s_delim(":")
s_delim(" ")
s_string("1")
s_delim(".")
s_string("0")
s_delim(" ")
s_string("derp")
s_delim(",")
s_delim(" ")
s_string("1")
s_delim(".")
s_string("1")
s_delim(" ")
s_string("derp.com")
s_delim(" ")
s_delim("(")
s_string("Apache")
s_delim("/")
s_string("1")
s_delim(".")
s_string("1")
s_delim(")")
s_static("\r\n\r\n")
########################################################################################################################
# Fuzz Warning header
# Warning: 4141 Sulley Rocks!
########################################################################################################################
s_initialize("HTTP HEADER WARNING")
s_static("GET / HTTP/1.1\r\n")
s_static("Warning")
s_delim(":")
s_delim(" ")
s_string("4141")
s_delim(" ")
s_string("Sulley Rocks!")
s_static("\r\n\r\n")
########################################################################################################################
# Fuzz X-att-deviceid header
# x-att-deviceid: DerpPhone/Rev2309
########################################################################################################################
s_initialize("HTTP HEADER XATTDEVICEID")
s_static("GET / HTTP/1.1\r\n")
s_static("x-att-deviceid")
s_delim(":")
s_delim(" ")
s_string("DerpPhone")
s_delim("/")
s_string("Rev2309")
s_static("\r\n\r\n")
########################################################################################################################
# Fuzz X-Do-Not-Track header
# X-Do-Not-Track: 1
########################################################################################################################
s_initialize("HTTP HEADER XDONOTTRACK")
s_static("GET / HTTP/1.1\r\n")
s_static("X-Do-Not-Track")
s_delim(":")
s_delim(" ")
s_string("1")
s_static("\r\n\r\n")
########################################################################################################################
# Fuzz X-Forwarded-For header
# X-Forwarded-For: client1, proxy1, proxy2
########################################################################################################################
s_initialize("HTTP HEADER XFORWARDEDFOR")
s_static("GET / HTTP/1.1\r\n")
s_static("X-Forwarded-For")
s_delim(":")
s_delim(" ")
s_string("client1")
s_delim(",")
s_delim(" ")
s_string("proxy2")
s_static("\r\n\r\n")
########################################################################################################################
# Fuzz X-Requested-With header
# X-Requested-With: XMLHttpRequest
########################################################################################################################
s_initialize("HTTP HEADER XREQUESTEDWITH")
s_static("GET / HTTP/1.1\r\n")
s_static("X-Requested-With")
s_delim(":")
s_delim(" ")
s_string("XMLHttpRequest")
s_static("\r\n\r\n")
########################################################################################################################
# Fuzz X-WAP-Profile header
# x-wap-profile: http://wap.samsungmobile.com/uaprof/SGH-I777.xml
########################################################################################################################
s_initialize("HTTP HEADER XWAPPROFILE")
s_static("GET / HTTP/1.1\r\n")
s_static("x-wap-profile")
s_delim(":")
s_delim(" ")
s_string("http")
s_delim(":")
s_delim("/")
s_delim("/")
s_string("wap.samsungmobile.com/uaprof/SGH-I777")
s_static(".xml")
s_static("\r\n\r\n")
| 22,992
|
Python
|
.py
| 679
| 32.749632
| 120
| 0.402146
|
OpenRCE/sulley
| 1,416
| 338
| 56
|
GPL-2.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
16,034
|
mcafee.py
|
OpenRCE_sulley/requests/mcafee.py
|
from sulley import *
from struct import *
# stupid one byte XOR
def mcafee_epo_xor (buf, poly=0xAA):
l = len(buf)
new_buf = ""
for char in buf:
new_buf += chr(ord(char) ^ poly)
return new_buf
########################################################################################################################
s_initialize("mcafee_epo_framework_tcp")
"""
McAfee FrameworkService.exe TCP port 8081
"""
s_static("POST", name="post_verb")
s_delim(" ")
s_group("paths", ["/spipe/pkg", "/spipe/file", "default.htm"])
s_delim("?")
s_string("URL")
s_delim("=")
s_string("TESTFILE")
s_delim("\r\n")
s_static("Content-Length:")
s_delim(" ")
s_size("payload", format="ascii")
s_delim("\r\n\r\n")
if s_block_start("payload"):
s_string("TESTCONTENTS")
s_delim("\r\n")
s_block_end()
########################################################################################################################
s_initialize("mcafee_epo_framework_udp")
"""
McAfee FrameworkService.exe UDP port 8082
"""
s_static('Type=\"AgentWakeup\"', name="agent_wakeup")
s_static('\"DataSize=\"')
s_size("data", format="ascii") # must be over 234
if s_block_start("data", encoder=mcafee_epo_xor):
s_static("\x50\x4f", name="signature")
s_group(values=[pack('<L', 0x40000001), pack('<L', 0x30000001), pack('<L', 0x20000001)], name="opcode")
s_size("data", length=4) #TODO: needs to be size of data - 1 !!!
s_string("size", size=210)
s_static("EPO\x00")
s_dword(1, name="other_opcode")
s_block_end()
########################################################################################################################
s_initialize("network_agent_udp")
"""
McAfee Network Agent UDP/TCP port 6646
"""
s_size("kit_and_kaboodle", endian='>', fuzzable=True)
if s_block_start("kit_and_kaboodle"):
# TODO: command? might want to fuzz this later.
s_static("\x00\x00\x00\x02")
# dunno what this is.
s_static("\x00\x00\x00\x00")
# here comes the first tag.
s_static("\x00\x00\x00\x01")
s_size("first_tag", endian='>', fuzzable=True)
if s_block_start("first_tag"):
s_string("McNAUniqueId", encoding="utf-16-le")
s_block_end()
# here comes the second tag.
s_static("\x0b\x00\x00\x00")
s_size("second_tag", fuzzable=True)
if s_block_start("second_tag"):
s_string("babee6e9-1cba-45be-9c81-05a3fb486ed7")
s_block_end()
s_block_end()
| 2,460
|
Python
|
.py
| 70
| 31.671429
| 120
| 0.551124
|
OpenRCE/sulley
| 1,416
| 338
| 56
|
GPL-2.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
16,035
|
trend.py
|
OpenRCE_sulley/requests/trend.py
|
from sulley import *
import struct
# crap ass trend xor "encryption" routine for control manager (20901)
def trend_xor_encode (str):
'''
Simple bidirectional XOR "encryption" routine used by this service.
'''
key = 0xA8534344
ret = ""
# pad to 4 byte boundary.
pad = 4 - (len(str) % 4)
if pad == 4:
pad = 0
str += "\x00" * pad
while str:
dword = struct.unpack("<L", str[:4])[0]
str = str[4:]
dword ^= key
ret += struct.pack("<L", dword)
key = dword
return ret
# crap ass trend xor "encryption" routine for control manager (20901)
def trend_xor_decode (str):
key = 0xA8534344
ret = ""
while str:
dword = struct.unpack("<L", str[:4])[0]
str = str[4:]
tmp = dword
tmp ^= key
ret += struct.pack("<L", tmp)
key = dword
return ret
# dce rpc request encoder used for trend server protect 5168 RPC service.
# opnum is always zero.
def rpc_request_encoder (data):
return utils.dcerpc.request(0, data)
########################################################################################################################
s_initialize("20901")
"""
Trend Micro Control Manager (DcsProcessor.exe)
http://bakemono/mediawiki/index.php/Trend_Micro:Control_Manager
This fuzz found nothing! need to uncover more protocol details. See also: pedram's pwned notebook page 3, 4.
"""
# dword 1, error: 0x10000001, do something:0x10000002, 0x10000003 (>0x10000002)
s_group("magic", values=["\x02\x00\x00\x10", "\x03\x00\x00\x10"])
# dword 2, size of body
s_size("body")
# dword 3, crc32(block) (copy from eax at 0041EE8B)
# TODO: CRC is non standard, nop out jmp at 0041EE99 and use bogus value:
#s_checksum("body", algorithm="crc32")
s_static("\xff\xff\xff\xff")
# the body of the trend request contains a variable number of (2-byte) TLVs
if s_block_start("body", encoder=trend_xor_encode):
s_word(0x0000, full_range=True) # completely fuzz the type
s_size("string1", length=2) # valid length
if s_block_start("string1"): # fuzz string
s_string("A"*1000)
s_block_end()
s_random("\x00\x00", 2, 2) # random type
s_size("string2", length=2) # valid length
if s_block_start("string2"): # fuzz string
s_string("B"*10)
s_block_end()
# try a table overflow.
if s_block_start("repeat me"):
s_random("\x00\x00", 2, 2) # random type
s_size("string3", length=2) # valid length
if s_block_start("string3"): # fuzz string
s_string("C"*10)
s_block_end()
s_block_end()
# repeat string3 a bunch of times.
s_repeat("repeat me", min_reps=100, max_reps=1000, step=50)
s_block_end("body")
########################################################################################################################
"""
Trend Micro Server Protect (SpNTsvc.exe)
This fuzz uncovered a bunch of DoS and code exec bugs. The obvious code exec bugs were documented and released to
the vendor. See also: pedram's pwned notebook page 1, 2.
// opcode: 0x00, address: 0x65741030
// uuid: 25288888-bd5b-11d1-9d53-0080c83a5c2c
// version: 1.0
error_status_t rpc_opnum_0 (
[in] handle_t arg_1, // not sent on wire
[in] long trend_req_num,
[in][size_is(arg_4)] byte overflow_str[],
[in] long arg_4,
[out][size_is(arg_6)] byte arg_5[], // not sent on wire
[in] long arg_6
);
"""
for op, submax in [(0x1, 22), (0x2, 19), (0x3, 85), (0x5, 25), (0xa, 49), (0x1f, 25)]:
s_initialize("5168: op-%x" % op)
if s_block_start("everything", encoder=rpc_request_encoder):
# [in] long trend_req_num,
s_group("subs", values=map(chr, range(1, submax)))
s_static("\x00") # subs is actually a little endian word
s_static(struct.pack("<H", op)) # opcode
# [in][size_is(arg_4)] byte overflow_str[],
s_size("the string")
if s_block_start("the string", group="subs"):
s_static("A" * 0x5000, name="arg3")
s_block_end()
# [in] long arg_4,
s_size("the string")
# [in] long arg_6
s_static(struct.pack("<L", 0x5000)) # output buffer size
s_block_end()
########################################################################################################################
s_initialize("5005")
"""
Trend Micro Server Protect (EarthAgent.exe)
Some custom protocol listening on TCP port 5005
"""
s_static("\x21\x43\x65\x87") # magic
# command
s_static("\x00\x00\x00\x00") # dunno
s_static("\x01\x00\x00\x00") # dunno, but observed static
# length
s_static("\xe8\x03\x00\x00") # dunno, but observed static
s_static("\x00\x00\x00\x00") # dunno, but observed static
| 4,922
|
Python
|
.py
| 122
| 35.114754
| 120
| 0.567227
|
OpenRCE/sulley
| 1,416
| 338
| 56
|
GPL-2.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
16,036
|
http.py
|
OpenRCE_sulley/requests/http.py
|
from sulley import *
########################################################################################################################
# Old http.py request primitives, http_* does all of these and many more (AFAIK)
########################################################################################################################
# List of all blocks defined here (for easy copy/paste)
"""
sess.connect(s_get("HTTP VERBS"))
sess.connect(s_get("HTTP VERBS BASIC"))
sess.connect(s_get("HTTP VERBS POST"))
sess.connect(s_get("HTTP HEADERS"))
sess.connect(s_get("HTTP COOKIE"))
"""
s_initialize("HTTP VERBS")
s_group("verbs", values=["GET", "HEAD", "POST", "OPTIONS", "TRACE", "PUT", "DELETE", "PROPFIND"])
if s_block_start("body", group="verbs"):
s_delim(" ")
s_delim("/")
s_string("index.html")
s_delim(" ")
s_string("HTTP")
s_delim("/")
s_string("1")
s_delim(".")
s_string("1")
s_static("\r\n\r\n")
s_block_end()
########################################################################################################################
s_initialize("HTTP VERBS BASIC")
s_group("verbs", values=["GET", "HEAD"])
if s_block_start("body", group="verbs"):
s_delim(" ")
s_delim("/")
s_string("index.html")
s_delim(" ")
s_string("HTTP")
s_delim("/")
s_string("1")
s_delim(".")
s_string("1")
s_static("\r\n\r\n")
s_block_end()
########################################################################################################################
s_initialize("HTTP VERBS POST")
s_static("POST / HTTP/1.1\r\n")
s_static("Content-Type: ")
s_string("application/x-www-form-urlencoded")
s_static("\r\n")
s_static("Content-Length: ")
s_size("post blob", format="ascii", signed=True, fuzzable=True)
s_static("\r\n\r\n")
if s_block_start("post blob"):
s_string("A"*100 + "=" + "B"*100)
s_block_end()
########################################################################################################################
s_initialize("HTTP HEADERS")
s_static("GET / HTTP/1.1\r\n")
# let's fuzz random headers with malformed delimiters.
s_string("Host")
s_delim(":")
s_delim(" ")
s_string("localhost")
s_delim("\r\n")
# let's fuzz the value portion of some popular headers.
s_static("User-Agent: ")
s_string("Mozilla/5.0 (Windows; U)")
s_static("\r\n")
s_static("Accept-Language: ")
s_string("en-us")
s_delim(",")
s_string("en;q=0.5")
s_static("\r\n")
s_static("Keep-Alive: ")
s_string("300")
s_static("\r\n")
s_static("Connection: ")
s_string("keep-alive")
s_static("\r\n")
s_static("Referer: ")
s_string("http://dvlabs.tippingpoint.com")
s_static("\r\n")
s_static("\r\n")
########################################################################################################################
s_initialize("HTTP COOKIE")
s_static("GET / HTTP/1.1\r\n")
if s_block_start("cookie"):
s_static("Cookie: ")
s_string("auth")
s_delim("=")
s_string("1234567890")
s_static("\r\n")
s_block_end()
s_repeat("cookie", max_reps=5000, step=500)
s_static("\r\n")
| 3,070
|
Python
|
.py
| 93
| 30.666667
| 120
| 0.483108
|
OpenRCE/sulley
| 1,416
| 338
| 56
|
GPL-2.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
16,037
|
rendezvous.py
|
OpenRCE_sulley/requests/rendezvous.py
|
from sulley import *
########################################################################################################################
s_initialize("trillian 1")
s_static("\x00\x00") # transaction ID
s_static("\x00\x00") # flags (standard query)
s_word(1, endian=">") # number of questions
s_word(0, endian=">", fuzzable=False) # answer RRs
s_word(0, endian=">", fuzzable=False) # authority RRs
s_word(0, endian=">", fuzzable=False) # additional RRs
# queries
s_lego("dns_hostname", "_presence._tcp.local")
s_word(0x000c, endian=">") # type = pointer
s_word(0x8001, endian=">") # class = flush
########################################################################################################################
s_initialize("trillian 2")
if s_block_start("pamini.local"):
if s_block_start("header"):
s_static("\x00\x00") # transaction ID
s_static("\x00\x00") # flags (standard query)
s_word(2, endian=">") # number of questions
s_word(0, endian=">", fuzzable=False) # answer RRs
s_word(2, endian=">", fuzzable=False) # authority RRs
s_word(0, endian=">", fuzzable=False) # additional RRs
s_block_end()
# queries
s_lego("dns_hostname", "pamini.local")
s_word(0x00ff, endian=">") # type = any
s_word(0x8001, endian=">") # class = flush
s_block_end()
s_lego("dns_hostname", "pedram@PAMINI._presence._tcp")
s_word(0x00ff, endian=">") # type = any
s_word(0x8001, endian=">") # class = flush
# authoritative nameservers
s_static("\xc0") # offset specifier
s_size("header", length=1) # offset to pamini.local
s_static("\x00\x01") # type = A (host address)
s_static("\x00\x01") # class = in
s_static("\x00\x00\x00\xf0") # ttl 4 minutes
s_static("\x00\x04") # data length
s_static(chr(152) + chr(67) + chr(137) + chr(53)) # ip address
s_static("\xc0") # offset specifier
s_size("pamini.local", length=1) # offset to pedram@PAMINI...
s_static("\x00\x21") # type = SRV (service location)
s_static("\x00\x01") # class = in
s_static("\x00\x00\x00\xf0") # ttl 4 minutes
s_static("\x00\x08") # data length
s_static("\x00\x00") # priority
s_static("\x00\x00") # weight
s_static("\x14\xb2") # port
s_static("\xc0") # offset specifier
s_size("header", length=1) # offset to pamini.local
########################################################################################################################
s_initialize("trillian 3")
if s_block_start("pamini.local"):
if s_block_start("header"):
s_static("\x00\x00") # transaction ID
s_static("\x00\x00") # flags (standard query)
s_word(2, endian=">") # number of questions
s_word(0, endian=">", fuzzable=False) # answer RRs
s_word(2, endian=">", fuzzable=False) # authority RRs
s_word(0, endian=">", fuzzable=False) # additional RRs
s_block_end()
# queries
s_lego("dns_hostname", "pamini.local")
s_word(0x00ff, endian=">") # type = any
s_word(0x0001, endian=">") # class = in
s_block_end()
s_lego("dns_hostname", "pedram@PAMINI._presence._tcp")
s_word(0x00ff, endian=">") # type = any
s_word(0x0001, endian=">") # class = in
# authoritative nameservers
s_static("\xc0") # offset specifier
s_size("header", length=1) # offset to pamini.local
s_static("\x00\x01") # type = A (host address)
s_static("\x00\x01") # class = in
s_static("\x00\x00\x00\xf0") # ttl 4 minutes
s_static("\x00\x04") # data length
s_static(chr(152) + chr(67) + chr(137) + chr(53)) # ip address
s_static("\xc0") # offset specifier
s_size("pamini.local", length=1) # offset to pedram@PAMINI...
s_static("\x00\x21") # type = SRV (service location)
s_static("\x00\x01") # class = in
s_static("\x00\x00\x00\xf0") # ttl 4 minutes
s_static("\x00\x08") # data length
s_static("\x00\x00") # priority
s_static("\x00\x00") # weight
s_static("\x14\xb2") # port
s_static("\xc0") # offset specifier
s_size("header", length=1) # offset to pamini.local
| 5,402
|
Python
|
.py
| 89
| 57.876404
| 120
| 0.427384
|
OpenRCE/sulley
| 1,416
| 338
| 56
|
GPL-2.0
|
9/5/2024, 5:12:06 PM (Europe/Amsterdam)
|
16,038
|
cupp.py
|
Mebus_cupp/cupp.py
|
#!/usr/bin/python3
#
# [Program]
#
# CUPP
# Common User Passwords Profiler
#
# [Author]
#
# Muris Kurgas aka j0rgan
# j0rgan [at] remote-exploit [dot] org
# http://www.remote-exploit.org
# http://www.azuzi.me
#
# [License]
#
# 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
# 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# See 'LICENSE' for more information.
import argparse
import configparser
import csv
import functools
import gzip
import os
import sys
import urllib.error
import urllib.parse
import urllib.request
import time
__author__ = "Mebus"
__license__ = "GPL"
__version__ = "3.3.0"
CONFIG = {}
def read_config(filename):
"""Read the given configuration file and update global variables to reflect
changes (CONFIG)."""
if os.path.isfile(filename):
# global CONFIG
# Reading configuration file
config = configparser.ConfigParser()
config.read(filename)
CONFIG["global"] = {
"years": config.get("years", "years").split(","),
"chars": config.get("specialchars", "chars").split(","),
"numfrom": config.getint("nums", "from"),
"numto": config.getint("nums", "to"),
"wcfrom": config.getint("nums", "wcfrom"),
"wcto": config.getint("nums", "wcto"),
"threshold": config.getint("nums", "threshold"),
"alectourl": config.get("alecto", "alectourl"),
"dicturl": config.get("downloader", "dicturl"),
}
# 1337 mode configs, well you can add more lines if you add it to the
# config file too.
leet = functools.partial(config.get, "leet")
leetc = {}
letters = {"a", "i", "e", "t", "o", "s", "g", "z"}
for letter in letters:
leetc[letter] = config.get("leet", letter)
CONFIG["LEET"] = leetc
return True
else:
print("Configuration file " + filename + " not found!")
sys.exit("Exiting.")
return False
def make_leet(x):
"""convert string to leet"""
for letter, leetletter in CONFIG["LEET"].items():
x = x.replace(letter, leetletter)
return x
# for concatenations...
def concats(seq, start, stop):
for mystr in seq:
for num in range(start, stop):
yield mystr + str(num)
# for sorting and making combinations...
def komb(seq, start, special=""):
for mystr in seq:
for mystr1 in start:
yield mystr + special + mystr1
# print list to file counting words
def print_to_file(filename, unique_list_finished):
f = open(filename, "w")
unique_list_finished.sort()
f.write(os.linesep.join(unique_list_finished))
f.close()
f = open(filename, "r")
lines = 0
for line in f:
lines += 1
f.close()
print(
"[+] Saving dictionary to \033[1;31m"
+ filename
+ "\033[1;m, counting \033[1;31m"
+ str(lines)
+ " words.\033[1;m"
)
inspect = input("> Hyperspeed Print? (Y/n) : ").lower()
if inspect == "y":
try:
with open(filename, "r+") as wlist:
data = wlist.readlines()
for line in data:
print("\033[1;32m[" + filename + "] \033[1;33m" + line)
time.sleep(0000.1)
os.system("clear")
except Exception as e:
print("[ERROR]: " + str(e))
else:
pass
print(
"[+] Now load your pistolero with \033[1;31m"
+ filename
+ "\033[1;m and shoot! Good luck!"
)
def print_cow():
print(" ___________ ")
print(" \033[07m cupp.py! \033[27m # \033[07mC\033[27mommon")
print(" \ # \033[07mU\033[27mser")
print(" \ \033[1;31m,__,\033[1;m # \033[07mP\033[27masswords")
print(
" \ \033[1;31m(\033[1;moo\033[1;31m)____\033[1;m # \033[07mP\033[27mrofiler"
)
print(" \033[1;31m(__) )\ \033[1;m ")
print(
" \033[1;31m ||--|| \033[1;m\033[05m*\033[25m\033[1;m [ Muris Kurgas | j0rgan@remote-exploit.org ]"
)
print(28 * " " + "[ Mebus | https://github.com/Mebus/]\r\n")
def version():
"""Display version"""
print("\r\n \033[1;31m[ cupp.py ] " + __version__ + "\033[1;m\r\n")
print(" * Hacked up by j0rgan - j0rgan@remote-exploit.org")
print(" * http://www.remote-exploit.org\r\n")
print(" Take a look ./README.md file for more info about the program\r\n")
def improve_dictionary(file_to_open):
"""Implementation of the -w option. Improve a dictionary by
interactively questioning the user."""
kombinacija = {}
komb_unique = {}
if not os.path.isfile(file_to_open):
exit("Error: file " + file_to_open + " does not exist.")
chars = CONFIG["global"]["chars"]
years = CONFIG["global"]["years"]
numfrom = CONFIG["global"]["numfrom"]
numto = CONFIG["global"]["numto"]
fajl = open(file_to_open, "r")
listic = fajl.readlines()
listica = []
for x in listic:
listica += x.split()
print("\r\n *************************************************")
print(" * \033[1;31mWARNING!!!\033[1;m *")
print(" * Using large wordlists in some *")
print(" * options bellow is NOT recommended! *")
print(" *************************************************\r\n")
conts = input(
"> Do you want to concatenate all words from wordlist? Y/[N]: "
).lower()
if conts == "y" and len(listic) > CONFIG["global"]["threshold"]:
print(
"\r\n[-] Maximum number of words for concatenation is "
+ str(CONFIG["global"]["threshold"])
)
print("[-] Check configuration file for increasing this number.\r\n")
conts = input(
"> Do you want to concatenate all words from wordlist? Y/[N]: "
).lower()
cont = [""]
if conts == "y":
for cont1 in listica:
for cont2 in listica:
if listica.index(cont1) != listica.index(cont2):
cont.append(cont1 + cont2)
spechars = [""]
spechars1 = input(
"> Do you want to add special chars at the end of words? Y/[N]: "
).lower()
if spechars1 == "y":
for spec1 in chars:
spechars.append(spec1)
for spec2 in chars:
spechars.append(spec1 + spec2)
for spec3 in chars:
spechars.append(spec1 + spec2 + spec3)
randnum = input(
"> Do you want to add some random numbers at the end of words? Y/[N]:"
).lower()
leetmode = input("> Leet mode? (i.e. leet = 1337) Y/[N]: ").lower()
# init
for i in range(6):
kombinacija[i] = [""]
kombinacija[0] = list(komb(listica, years))
if conts == "y":
kombinacija[1] = list(komb(cont, years))
if spechars1 == "y":
kombinacija[2] = list(komb(listica, spechars))
if conts == "y":
kombinacija[3] = list(komb(cont, spechars))
if randnum == "y":
kombinacija[4] = list(concats(listica, numfrom, numto))
if conts == "y":
kombinacija[5] = list(concats(cont, numfrom, numto))
print("\r\n[+] Now making a dictionary...")
print("[+] Sorting list and removing duplicates...")
for i in range(6):
komb_unique[i] = list(dict.fromkeys(kombinacija[i]).keys())
komb_unique[6] = list(dict.fromkeys(listica).keys())
komb_unique[7] = list(dict.fromkeys(cont).keys())
# join the lists
uniqlist = []
for i in range(8):
uniqlist += komb_unique[i]
unique_lista = list(dict.fromkeys(uniqlist).keys())
unique_leet = []
if leetmode == "y":
for (
x
) in (
unique_lista
): # if you want to add more leet chars, you will need to add more lines in cupp.cfg too...
x = make_leet(x) # convert to leet
unique_leet.append(x)
unique_list = unique_lista + unique_leet
unique_list_finished = []
unique_list_finished = [
x
for x in unique_list
if len(x) > CONFIG["global"]["wcfrom"] and len(x) < CONFIG["global"]["wcto"]
]
print_to_file(file_to_open + ".cupp.txt", unique_list_finished)
fajl.close()
def interactive():
"""Implementation of the -i switch. Interactively question the user and
create a password dictionary file based on the answer."""
print("\r\n[+] Insert the information about the victim to make a dictionary")
print("[+] If you don't know all the info, just hit enter when asked! ;)\r\n")
# We need some information first!
profile = {}
name = input("> First Name: ").lower()
while len(name) == 0 or name == " " or name == " " or name == " ":
print("\r\n[-] You must enter a name at least!")
name = input("> Name: ").lower()
profile["name"] = str(name)
profile["surname"] = input("> Surname: ").lower()
profile["nick"] = input("> Nickname: ").lower()
birthdate = input("> Birthdate (DDMMYYYY): ")
while len(birthdate) != 0 and len(birthdate) != 8:
print("\r\n[-] You must enter 8 digits for birthday!")
birthdate = input("> Birthdate (DDMMYYYY): ")
profile["birthdate"] = str(birthdate)
print("\r\n")
profile["wife"] = input("> Partners) name: ").lower()
profile["wifen"] = input("> Partners) nickname: ").lower()
wifeb = input("> Partners) birthdate (DDMMYYYY): ")
while len(wifeb) != 0 and len(wifeb) != 8:
print("\r\n[-] You must enter 8 digits for birthday!")
wifeb = input("> Partners birthdate (DDMMYYYY): ")
profile["wifeb"] = str(wifeb)
print("\r\n")
profile["kid"] = input("> Child's name: ").lower()
profile["kidn"] = input("> Child's nickname: ").lower()
kidb = input("> Child's birthdate (DDMMYYYY): ")
while len(kidb) != 0 and len(kidb) != 8:
print("\r\n[-] You must enter 8 digits for birthday!")
kidb = input("> Child's birthdate (DDMMYYYY): ")
profile["kidb"] = str(kidb)
print("\r\n")
profile["pet"] = input("> Pet's name: ").lower()
profile["company"] = input("> Company name: ").lower()
print("\r\n")
profile["words"] = [""]
words1 = input(
"> Do you want to add some key words about the victim? Y/[N]: "
).lower()
words2 = ""
if words1 == "y":
words2 = input(
"> Please enter the words, separated by comma. [i.e. hacker,juice,black], spaces will be removed: "
).replace(" ", "")
profile["words"] = words2.split(",")
profile["spechars1"] = input(
"> Do you want to add special chars at the end of words? Y/[N]: "
).lower()
profile["randnum"] = input(
"> Do you want to add some random numbers at the end of words? Y/[N]:"
).lower()
profile["leetmode"] = input("> Leet mode? (i.e. leet = 1337) Y/[N]: ").lower()
generate_wordlist_from_profile(profile) # generate the wordlist
def generate_wordlist_from_profile(profile):
""" Generates a wordlist from a given profile """
chars = CONFIG["global"]["chars"]
years = CONFIG["global"]["years"]
numfrom = CONFIG["global"]["numfrom"]
numto = CONFIG["global"]["numto"]
profile["spechars"] = []
if profile["spechars1"] == "y":
for spec1 in chars:
profile["spechars"].append(spec1)
for spec2 in chars:
profile["spechars"].append(spec1 + spec2)
for spec3 in chars:
profile["spechars"].append(spec1 + spec2 + spec3)
print("\r\n[+] Now making a dictionary...")
# Now me must do some string modifications...
# Birthdays first
birthdate_yy = profile["birthdate"][-2:]
birthdate_yyy = profile["birthdate"][-3:]
birthdate_yyyy = profile["birthdate"][-4:]
birthdate_xd = profile["birthdate"][1:2]
birthdate_xm = profile["birthdate"][3:4]
birthdate_dd = profile["birthdate"][:2]
birthdate_mm = profile["birthdate"][2:4]
wifeb_yy = profile["wifeb"][-2:]
wifeb_yyy = profile["wifeb"][-3:]
wifeb_yyyy = profile["wifeb"][-4:]
wifeb_xd = profile["wifeb"][1:2]
wifeb_xm = profile["wifeb"][3:4]
wifeb_dd = profile["wifeb"][:2]
wifeb_mm = profile["wifeb"][2:4]
kidb_yy = profile["kidb"][-2:]
kidb_yyy = profile["kidb"][-3:]
kidb_yyyy = profile["kidb"][-4:]
kidb_xd = profile["kidb"][1:2]
kidb_xm = profile["kidb"][3:4]
kidb_dd = profile["kidb"][:2]
kidb_mm = profile["kidb"][2:4]
# Convert first letters to uppercase...
nameup = profile["name"].title()
surnameup = profile["surname"].title()
nickup = profile["nick"].title()
wifeup = profile["wife"].title()
wifenup = profile["wifen"].title()
kidup = profile["kid"].title()
kidnup = profile["kidn"].title()
petup = profile["pet"].title()
companyup = profile["company"].title()
wordsup = []
wordsup = list(map(str.title, profile["words"]))
word = profile["words"] + wordsup
# reverse a name
rev_name = profile["name"][::-1]
rev_nameup = nameup[::-1]
rev_nick = profile["nick"][::-1]
rev_nickup = nickup[::-1]
rev_wife = profile["wife"][::-1]
rev_wifeup = wifeup[::-1]
rev_kid = profile["kid"][::-1]
rev_kidup = kidup[::-1]
reverse = [
rev_name,
rev_nameup,
rev_nick,
rev_nickup,
rev_wife,
rev_wifeup,
rev_kid,
rev_kidup,
]
rev_n = [rev_name, rev_nameup, rev_nick, rev_nickup]
rev_w = [rev_wife, rev_wifeup]
rev_k = [rev_kid, rev_kidup]
# Let's do some serious work! This will be a mess of code, but... who cares? :)
# Birthdays combinations
bds = [
birthdate_yy,
birthdate_yyy,
birthdate_yyyy,
birthdate_xd,
birthdate_xm,
birthdate_dd,
birthdate_mm,
]
bdss = []
for bds1 in bds:
bdss.append(bds1)
for bds2 in bds:
if bds.index(bds1) != bds.index(bds2):
bdss.append(bds1 + bds2)
for bds3 in bds:
if (
bds.index(bds1) != bds.index(bds2)
and bds.index(bds2) != bds.index(bds3)
and bds.index(bds1) != bds.index(bds3)
):
bdss.append(bds1 + bds2 + bds3)
# For a woman...
wbds = [wifeb_yy, wifeb_yyy, wifeb_yyyy, wifeb_xd, wifeb_xm, wifeb_dd, wifeb_mm]
wbdss = []
for wbds1 in wbds:
wbdss.append(wbds1)
for wbds2 in wbds:
if wbds.index(wbds1) != wbds.index(wbds2):
wbdss.append(wbds1 + wbds2)
for wbds3 in wbds:
if (
wbds.index(wbds1) != wbds.index(wbds2)
and wbds.index(wbds2) != wbds.index(wbds3)
and wbds.index(wbds1) != wbds.index(wbds3)
):
wbdss.append(wbds1 + wbds2 + wbds3)
# and a child...
kbds = [kidb_yy, kidb_yyy, kidb_yyyy, kidb_xd, kidb_xm, kidb_dd, kidb_mm]
kbdss = []
for kbds1 in kbds:
kbdss.append(kbds1)
for kbds2 in kbds:
if kbds.index(kbds1) != kbds.index(kbds2):
kbdss.append(kbds1 + kbds2)
for kbds3 in kbds:
if (
kbds.index(kbds1) != kbds.index(kbds2)
and kbds.index(kbds2) != kbds.index(kbds3)
and kbds.index(kbds1) != kbds.index(kbds3)
):
kbdss.append(kbds1 + kbds2 + kbds3)
# string combinations....
kombinaac = [profile["pet"], petup, profile["company"], companyup]
kombina = [
profile["name"],
profile["surname"],
profile["nick"],
nameup,
surnameup,
nickup,
]
kombinaw = [
profile["wife"],
profile["wifen"],
wifeup,
wifenup,
profile["surname"],
surnameup,
]
kombinak = [
profile["kid"],
profile["kidn"],
kidup,
kidnup,
profile["surname"],
surnameup,
]
kombinaa = []
for kombina1 in kombina:
kombinaa.append(kombina1)
for kombina2 in kombina:
if kombina.index(kombina1) != kombina.index(kombina2) and kombina.index(
kombina1.title()
) != kombina.index(kombina2.title()):
kombinaa.append(kombina1 + kombina2)
kombinaaw = []
for kombina1 in kombinaw:
kombinaaw.append(kombina1)
for kombina2 in kombinaw:
if kombinaw.index(kombina1) != kombinaw.index(kombina2) and kombinaw.index(
kombina1.title()
) != kombinaw.index(kombina2.title()):
kombinaaw.append(kombina1 + kombina2)
kombinaak = []
for kombina1 in kombinak:
kombinaak.append(kombina1)
for kombina2 in kombinak:
if kombinak.index(kombina1) != kombinak.index(kombina2) and kombinak.index(
kombina1.title()
) != kombinak.index(kombina2.title()):
kombinaak.append(kombina1 + kombina2)
kombi = {}
kombi[1] = list(komb(kombinaa, bdss))
kombi[1] += list(komb(kombinaa, bdss, "_"))
kombi[2] = list(komb(kombinaaw, wbdss))
kombi[2] += list(komb(kombinaaw, wbdss, "_"))
kombi[3] = list(komb(kombinaak, kbdss))
kombi[3] += list(komb(kombinaak, kbdss, "_"))
kombi[4] = list(komb(kombinaa, years))
kombi[4] += list(komb(kombinaa, years, "_"))
kombi[5] = list(komb(kombinaac, years))
kombi[5] += list(komb(kombinaac, years, "_"))
kombi[6] = list(komb(kombinaaw, years))
kombi[6] += list(komb(kombinaaw, years, "_"))
kombi[7] = list(komb(kombinaak, years))
kombi[7] += list(komb(kombinaak, years, "_"))
kombi[8] = list(komb(word, bdss))
kombi[8] += list(komb(word, bdss, "_"))
kombi[9] = list(komb(word, wbdss))
kombi[9] += list(komb(word, wbdss, "_"))
kombi[10] = list(komb(word, kbdss))
kombi[10] += list(komb(word, kbdss, "_"))
kombi[11] = list(komb(word, years))
kombi[11] += list(komb(word, years, "_"))
kombi[12] = [""]
kombi[13] = [""]
kombi[14] = [""]
kombi[15] = [""]
kombi[16] = [""]
kombi[21] = [""]
if profile["randnum"] == "y":
kombi[12] = list(concats(word, numfrom, numto))
kombi[13] = list(concats(kombinaa, numfrom, numto))
kombi[14] = list(concats(kombinaac, numfrom, numto))
kombi[15] = list(concats(kombinaaw, numfrom, numto))
kombi[16] = list(concats(kombinaak, numfrom, numto))
kombi[21] = list(concats(reverse, numfrom, numto))
kombi[17] = list(komb(reverse, years))
kombi[17] += list(komb(reverse, years, "_"))
kombi[18] = list(komb(rev_w, wbdss))
kombi[18] += list(komb(rev_w, wbdss, "_"))
kombi[19] = list(komb(rev_k, kbdss))
kombi[19] += list(komb(rev_k, kbdss, "_"))
kombi[20] = list(komb(rev_n, bdss))
kombi[20] += list(komb(rev_n, bdss, "_"))
komb001 = [""]
komb002 = [""]
komb003 = [""]
komb004 = [""]
komb005 = [""]
komb006 = [""]
if len(profile["spechars"]) > 0:
komb001 = list(komb(kombinaa, profile["spechars"]))
komb002 = list(komb(kombinaac, profile["spechars"]))
komb003 = list(komb(kombinaaw, profile["spechars"]))
komb004 = list(komb(kombinaak, profile["spechars"]))
komb005 = list(komb(word, profile["spechars"]))
komb006 = list(komb(reverse, profile["spechars"]))
print("[+] Sorting list and removing duplicates...")
komb_unique = {}
for i in range(1, 22):
komb_unique[i] = list(dict.fromkeys(kombi[i]).keys())
komb_unique01 = list(dict.fromkeys(kombinaa).keys())
komb_unique02 = list(dict.fromkeys(kombinaac).keys())
komb_unique03 = list(dict.fromkeys(kombinaaw).keys())
komb_unique04 = list(dict.fromkeys(kombinaak).keys())
komb_unique05 = list(dict.fromkeys(word).keys())
komb_unique07 = list(dict.fromkeys(komb001).keys())
komb_unique08 = list(dict.fromkeys(komb002).keys())
komb_unique09 = list(dict.fromkeys(komb003).keys())
komb_unique010 = list(dict.fromkeys(komb004).keys())
komb_unique011 = list(dict.fromkeys(komb005).keys())
komb_unique012 = list(dict.fromkeys(komb006).keys())
uniqlist = (
bdss
+ wbdss
+ kbdss
+ reverse
+ komb_unique01
+ komb_unique02
+ komb_unique03
+ komb_unique04
+ komb_unique05
)
for i in range(1, 21):
uniqlist += komb_unique[i]
uniqlist += (
komb_unique07
+ komb_unique08
+ komb_unique09
+ komb_unique010
+ komb_unique011
+ komb_unique012
)
unique_lista = list(dict.fromkeys(uniqlist).keys())
unique_leet = []
if profile["leetmode"] == "y":
for (
x
) in (
unique_lista
): # if you want to add more leet chars, you will need to add more lines in cupp.cfg too...
x = make_leet(x) # convert to leet
unique_leet.append(x)
unique_list = unique_lista + unique_leet
unique_list_finished = []
unique_list_finished = [
x
for x in unique_list
if len(x) < CONFIG["global"]["wcto"] and len(x) > CONFIG["global"]["wcfrom"]
]
print_to_file(profile["name"] + ".txt", unique_list_finished)
def download_http(url, targetfile):
print("[+] Downloading " + targetfile + " from " + url + " ... ")
webFile = urllib.request.urlopen(url)
localFile = open(targetfile, "wb")
localFile.write(webFile.read())
webFile.close()
localFile.close()
def alectodb_download():
"""Download csv from alectodb and save into local file as a list of
usernames and passwords"""
url = CONFIG["global"]["alectourl"]
print("\r\n[+] Checking if alectodb is not present...")
targetfile = "alectodb.csv.gz"
if not os.path.isfile(targetfile):
download_http(url, targetfile)
f = gzip.open(targetfile, "rt")
data = csv.reader(f)
usernames = []
passwords = []
for row in data:
usernames.append(row[5])
passwords.append(row[6])
gus = list(set(usernames))
gpa = list(set(passwords))
gus.sort()
gpa.sort()
print(
"\r\n[+] Exporting to alectodb-usernames.txt and alectodb-passwords.txt\r\n[+] Done."
)
f = open("alectodb-usernames.txt", "w")
f.write(os.linesep.join(gus))
f.close()
f = open("alectodb-passwords.txt", "w")
f.write(os.linesep.join(gpa))
f.close()
def download_wordlist():
"""Implementation of -l switch. Download wordlists from http repository as
defined in the configuration file."""
print(" \r\n Choose the section you want to download:\r\n")
print(" 1 Moby 14 french 27 places")
print(" 2 afrikaans 15 german 28 polish")
print(" 3 american 16 hindi 29 random")
print(" 4 aussie 17 hungarian 30 religion")
print(" 5 chinese 18 italian 31 russian")
print(" 6 computer 19 japanese 32 science")
print(" 7 croatian 20 latin 33 spanish")
print(" 8 czech 21 literature 34 swahili")
print(" 9 danish 22 movieTV 35 swedish")
print(" 10 databases 23 music 36 turkish")
print(" 11 dictionaries 24 names 37 yiddish")
print(" 12 dutch 25 net 38 exit program")
print(" 13 finnish 26 norwegian \r\n")
print(
" \r\n Files will be downloaded from "
+ CONFIG["global"]["dicturl"]
+ " repository"
)
print(
" \r\n Tip: After downloading wordlist, you can improve it with -w option\r\n"
)
filedown = input("> Enter number: ")
filedown.isdigit()
while filedown.isdigit() == 0:
print("\r\n[-] Wrong choice. ")
filedown = input("> Enter number: ")
filedown = str(filedown)
while int(filedown) > 38 or int(filedown) < 0:
print("\r\n[-] Wrong choice. ")
filedown = input("> Enter number: ")
filedown = str(filedown)
download_wordlist_http(filedown)
return filedown
def download_wordlist_http(filedown):
""" do the HTTP download of a wordlist """
mkdir_if_not_exists("dictionaries")
# List of files to download:
arguments = {
1: (
"Moby",
(
"mhyph.tar.gz",
"mlang.tar.gz",
"moby.tar.gz",
"mpos.tar.gz",
"mpron.tar.gz",
"mthes.tar.gz",
"mwords.tar.gz",
),
),
2: ("afrikaans", ("afr_dbf.zip",)),
3: ("american", ("dic-0294.tar.gz",)),
4: ("aussie", ("oz.gz",)),
5: ("chinese", ("chinese.gz",)),
6: (
"computer",
(
"Domains.gz",
"Dosref.gz",
"Ftpsites.gz",
"Jargon.gz",
"common-passwords.txt.gz",
"etc-hosts.gz",
"foldoc.gz",
"language-list.gz",
"unix.gz",
),
),
7: ("croatian", ("croatian.gz",)),
8: ("czech", ("czech-wordlist-ascii-cstug-novak.gz",)),
9: ("danish", ("danish.words.gz", "dansk.zip")),
10: (
"databases",
("acronyms.gz", "att800.gz", "computer-companies.gz", "world_heritage.gz"),
),
11: (
"dictionaries",
(
"Antworth.gz",
"CRL.words.gz",
"Roget.words.gz",
"Unabr.dict.gz",
"Unix.dict.gz",
"englex-dict.gz",
"knuth_britsh.gz",
"knuth_words.gz",
"pocket-dic.gz",
"shakesp-glossary.gz",
"special.eng.gz",
"words-english.gz",
),
),
12: ("dutch", ("words.dutch.gz",)),
13: (
"finnish",
("finnish.gz", "firstnames.finnish.gz", "words.finnish.FAQ.gz"),
),
14: ("french", ("dico.gz",)),
15: ("german", ("deutsch.dic.gz", "germanl.gz", "words.german.gz")),
16: ("hindi", ("hindu-names.gz",)),
17: ("hungarian", ("hungarian.gz",)),
18: ("italian", ("words.italian.gz",)),
19: ("japanese", ("words.japanese.gz",)),
20: ("latin", ("wordlist.aug.gz",)),
21: (
"literature",
(
"LCarrol.gz",
"Paradise.Lost.gz",
"aeneid.gz",
"arthur.gz",
"cartoon.gz",
"cartoons-olivier.gz",
"charlemagne.gz",
"fable.gz",
"iliad.gz",
"myths-legends.gz",
"odyssey.gz",
"sf.gz",
"shakespeare.gz",
"tolkien.words.gz",
),
),
22: ("movieTV", ("Movies.gz", "Python.gz", "Trek.gz")),
23: (
"music",
(
"music-classical.gz",
"music-country.gz",
"music-jazz.gz",
"music-other.gz",
"music-rock.gz",
"music-shows.gz",
"rock-groups.gz",
),
),
24: (
"names",
(
"ASSurnames.gz",
"Congress.gz",
"Family-Names.gz",
"Given-Names.gz",
"actor-givenname.gz",
"actor-surname.gz",
"cis-givenname.gz",
"cis-surname.gz",
"crl-names.gz",
"famous.gz",
"fast-names.gz",
"female-names-kantr.gz",
"female-names.gz",
"givennames-ol.gz",
"male-names-kantr.gz",
"male-names.gz",
"movie-characters.gz",
"names.french.gz",
"names.hp.gz",
"other-names.gz",
"shakesp-names.gz",
"surnames-ol.gz",
"surnames.finnish.gz",
"usenet-names.gz",
),
),
25: (
"net",
(
"hosts-txt.gz",
"inet-machines.gz",
"usenet-loginids.gz",
"usenet-machines.gz",
"uunet-sites.gz",
),
),
26: ("norwegian", ("words.norwegian.gz",)),
27: (
"places",
(
"Colleges.gz",
"US-counties.gz",
"World.factbook.gz",
"Zipcodes.gz",
"places.gz",
),
),
28: ("polish", ("words.polish.gz",)),
29: (
"random",
(
"Ethnologue.gz",
"abbr.gz",
"chars.gz",
"dogs.gz",
"drugs.gz",
"junk.gz",
"numbers.gz",
"phrases.gz",
"sports.gz",
"statistics.gz",
),
),
30: ("religion", ("Koran.gz", "kjbible.gz", "norse.gz")),
31: ("russian", ("russian.lst.gz", "russian_words.koi8.gz")),
32: (
"science",
(
"Acr-diagnosis.gz",
"Algae.gz",
"Bacteria.gz",
"Fungi.gz",
"Microalgae.gz",
"Viruses.gz",
"asteroids.gz",
"biology.gz",
"tech.gz",
),
),
33: ("spanish", ("words.spanish.gz",)),
34: ("swahili", ("swahili.gz",)),
35: ("swedish", ("words.swedish.gz",)),
36: ("turkish", ("turkish.dict.gz",)),
37: ("yiddish", ("yiddish.gz",)),
}
# download the files
intfiledown = int(filedown)
if intfiledown in arguments:
dire = "dictionaries/" + arguments[intfiledown][0] + "/"
mkdir_if_not_exists(dire)
files_to_download = arguments[intfiledown][1]
for fi in files_to_download:
url = CONFIG["global"]["dicturl"] + arguments[intfiledown][0] + "/" + fi
tgt = dire + fi
download_http(url, tgt)
print("[+] files saved to " + dire)
else:
print("[-] leaving.")
# create the directory if it doesn't exist
def mkdir_if_not_exists(dire):
if not os.path.isdir(dire):
os.mkdir(dire)
# the main function
def main():
"""Command-line interface to the cupp utility"""
read_config(os.path.join(os.path.dirname(os.path.realpath(__file__)), "cupp.cfg"))
parser = get_parser()
args = parser.parse_args()
if not args.quiet:
print_cow()
if args.version:
version()
elif args.interactive:
interactive()
elif args.download_wordlist:
download_wordlist()
elif args.alecto:
alectodb_download()
elif args.improve:
improve_dictionary(args.improve)
else:
parser.print_help()
# Separate into a function for testing purposes
def get_parser():
"""Create and return a parser (argparse.ArgumentParser instance) for main()
to use"""
parser = argparse.ArgumentParser(description="Common User Passwords Profiler")
group = parser.add_mutually_exclusive_group(required=False)
group.add_argument(
"-i",
"--interactive",
action="store_true",
help="Interactive questions for user password profiling",
)
group.add_argument(
"-w",
dest="improve",
metavar="FILENAME",
help="Use this option to improve existing dictionary,"
" or WyD.pl output to make some pwnsauce",
)
group.add_argument(
"-l",
dest="download_wordlist",
action="store_true",
help="Download huge wordlists from repository",
)
group.add_argument(
"-a",
dest="alecto",
action="store_true",
help="Parse default usernames and passwords directly"
" from Alecto DB. Project Alecto uses purified"
" databases of Phenoelit and CIRT which were merged"
" and enhanced",
)
group.add_argument(
"-v", "--version", action="store_true", help="Show the version of this program."
)
parser.add_argument(
"-q", "--quiet", action="store_true", help="Quiet mode (don't print banner)"
)
return parser
if __name__ == "__main__":
main()
| 33,882
|
Python
|
.py
| 933
| 27.630225
| 124
| 0.53509
|
Mebus/cupp
| 4,406
| 1,154
| 58
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,039
|
test_cupp.py
|
Mebus_cupp/test_cupp.py
|
#!/usr/bin/env python3
#
# [Program]
#
# CUPP - Common User Passwords Profiler
#
# [Author]
#
# Mebus, https://github.com/Mebus/
#
# [License]
#
# 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
# 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# See 'LICENSE' for more information.
import os
import unittest
from unittest.mock import patch
from cupp import *
class TestCupp(unittest.TestCase):
def setUp(self):
read_config("cupp.cfg")
def test_config(self):
self.assertIn("2018", CONFIG["global"]["years"], "2018 is in years")
def test_generate_wordlist_from_profile(self):
profile = {
"name": "владимир",
"surname": "путин",
"nick": "putin",
"birthdate": "07101952",
"wife": "людмила",
"wifen": "ljudmila",
"wifeb": "06011958",
"kid": "екатерина",
"kidn": "katerina",
"kidb": "31081986",
"pet": "werny",
"company": "russian federation",
"words": ["Крим"],
"spechars1": "y",
"randnum": "y",
"leetmode": "y",
"spechars": [],
}
read_config("cupp.cfg")
generate_wordlist_from_profile(profile)
def test_parser(self):
""" downloads a file and checks if it exists """
download_wordlist_http("16")
filename = "dictionaries/hindi/hindu-names.gz"
self.assertTrue(os.path.isfile(filename), "file " + filename + "exists")
def test_print_cow(self):
""" test the cow """
print_cow()
def test_alectodb_download(self):
alectodb_download()
self.assertTrue(
os.path.isfile("alectodb-usernames.txt"),
"file alectodb-usernames.txt exists",
)
self.assertTrue(
os.path.isfile("alectodb-passwords.txt"),
"file alectodb-passwords.txt exists",
)
def test_improve_dictionary(self):
filename = "improveme.txt"
open(filename, "a").write("password123\n2018password\npassword\n")
__builtins__.input = lambda _: "Y" # Mock
improve_dictionary(filename)
def test_download_wordlist(self):
""" Download wordlists via menu """
__builtins__.input = lambda _: "31" # Mock
download_wordlist()
filename = "dictionaries/russian/russian.lst.gz"
self.assertTrue(os.path.isfile(filename), "file " + filename + "exists")
def test_interactive(self):
""" Tests the interactive menu """
expected_filename = "julian.txt"
string_to_test = "Julian30771"
# delete the file if it already exists
if os.path.isfile(expected_filename):
os.remove(expected_filename)
user_input = [
"Julian", # First Name
"Assange", # Surname
"Mendax", # Nickname
"03071971", # Birthdate
"", # Partner
"", # Partner nick
"", # Partner birthdate
"", # Child name
"", # Child nick
"", # Child birthdate
"", # Pet's name
"", # Company name
"N", # keywords
"Y", # Special chars
"N", # Random
"N", # Leet mode
]
test_ok = False
with patch("builtins.input", side_effect=user_input):
stacks = interactive()
if os.path.isfile(expected_filename):
if string_to_test in open(expected_filename).read():
test_ok = True
self.assertTrue(test_ok, "interactive generation works")
def test_main(self):
""" test run for the main function """
main()
if __name__ == "__main__":
unittest.main()
| 4,435
|
Python
|
.py
| 124
| 27.387097
| 80
| 0.583569
|
Mebus/cupp
| 4,406
| 1,154
| 58
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,040
|
setup.py
|
Guake_guake/setup.py
|
# -*- coding: utf-8 -*-
import setuptools
setuptools.setup(
use_scm_version={"write_to": "guake/_version.py", "local_scheme": "no-local-version"}
)
| 154
|
Python
|
.py
| 5
| 28.6
| 89
| 0.680272
|
Guake/guake
| 4,406
| 575
| 405
|
GPL-2.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,041
|
.pylintrc
|
Guake_guake/.pylintrc
|
[MASTER]
# A comma-separated list of package or module names from where C extensions may
# be loaded. Extensions are loading into the active Python interpreter and may
# run arbitrary code.
extension-pkg-whitelist=
# Add files or directories to the blacklist. They should be base names, not
# paths.
ignore=CVS
# Add files or directories matching the regex patterns to the blacklist. The
# regex matches against base names, not paths.
ignore-patterns=
# Python code to execute, usually for sys.path manipulation such as
# pygtk.require().
#init-hook=
# Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the
# number of processors available to use.
jobs=4
# Control the amount of potential inferred values when inferring a single
# object. This can help the performance when dealing with large functions or
# complex, nested conditions.
limit-inference-results=100
# List of plugins (as comma separated values of python modules names) to load,
# usually to register additional checkers.
load-plugins=
# Pickle collected data for later comparisons.
persistent=yes
# Specify a configuration file.
#rcfile=
# When enabled, pylint would attempt to guess common misconfiguration and emit
# user-friendly hints instead of false-positive error messages.
suggestion-mode=yes
# Allow loading of arbitrary C extensions. Extensions are imported into the
# active Python interpreter and may run arbitrary code.
unsafe-load-any-extension=no
[MESSAGES CONTROL]
# Only show warnings with the listed confidence levels. Leave empty to show
# all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED.
confidence=
# Disable the message, report, category or checker with the given id(s). You
# can either give multiple identifiers separated by comma (,) or put this
# option multiple times (only on the command line, not in the configuration
# file where it should appear only once). You can also use "--disable=all" to
# disable everything first and then reenable specific checks. For example, if
# you want to run only the similarities checker, you can use "--disable=all
# --enable=similarities". If you want to run only the classes checker, but have
# no Warning level messages displayed, use "--disable=all --enable=classes
# --disable=W".
disable=
arguments-differ,
attribute-defined-outside-init,
bad-continuation,
broad-except,
consider-using-ternary,
deprecated-method,
deprecated-module,
duplicate-code,
fixme,
import-error, # needed for travis build
inconsistent-return-statements,
invalid-name,
locally-enabled,
missing-docstring,
no-member,
no-method-argument,
no-name-in-module,
no-self-use,
no-value-for-parameter,
pointless-string-statement,
protected-access,
redefined-builtin,
too-few-public-methods,
too-many-arguments,
too-many-boolean-expressions,
too-many-instance-attributes,
too-many-lines,
too-many-locals,
too-many-nested-blocks,
too-many-public-methods,
too-many-statements,
undefined-variable,
ungrouped-imports,
unnecessary-pass,
unreachable,
unused-argument,
unused-import,
unused-variable,
wrong-import-order,
wrong-import-position,
consider-using-dict-items,
# Enable the message, report, category or checker with the given id(s). You can
# either give multiple identifier separated by comma (,) or put this option
# multiple time (only on the command line, not in the configuration file where
# it should appear only once). See also the "--disable" option for examples.
enable=c-extension-no-member
[REPORTS]
# Python expression which should return a note less than 10 (10 is the highest
# note). You have access to the variables errors warning, statement which
# respectively contain the number of errors / warnings messages and the total
# number of statements analyzed. This is used by the global evaluation report
# (RP0004).
evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)
# Template used to display messages. This is a python new-style format string
# used to format the message information. See doc for all details.
#msg-template=
# Set the output format. Available formats are text, parseable, colorized, json
# and msvs (visual studio). You can also give a reporter class, e.g.
# mypackage.mymodule.MyReporterClass.
output-format=text
# Tells whether to display a full report or only the messages.
reports=no
# Activate the evaluation score.
score=yes
[REFACTORING]
# Maximum number of nested blocks for function / method body
max-nested-blocks=5
# Complete name of functions that never returns. When checking for
# inconsistent-return-statements if a never returning function is called then
# it will be considered as an explicit return statement and no message will be
# printed.
never-returning-functions=sys.exit
[BASIC]
# Naming style matching correct argument names.
argument-naming-style=snake_case
# Regular expression matching correct argument names. Overrides argument-
# naming-style.
#argument-rgx=
# Naming style matching correct attribute names.
attr-naming-style=snake_case
# Regular expression matching correct attribute names. Overrides attr-naming-
# style.
#attr-rgx=
# Bad variable names which should always be refused, separated by a comma.
bad-names=foo,
bar,
baz,
toto,
tutu,
tata
# Naming style matching correct class attribute names.
class-attribute-naming-style=any
# Regular expression matching correct class attribute names. Overrides class-
# attribute-naming-style.
#class-attribute-rgx=
# Naming style matching correct class names.
class-naming-style=PascalCase
# Regular expression matching correct class names. Overrides class-naming-
# style.
#class-rgx=
# Naming style matching correct constant names.
const-naming-style=UPPER_CASE
# Regular expression matching correct constant names. Overrides const-naming-
# style.
#const-rgx=
# Minimum line length for functions/classes that require docstrings, shorter
# ones are exempt.
docstring-min-length=-1
# Naming style matching correct function names.
function-naming-style=snake_case
# Regular expression matching correct function names. Overrides function-
# naming-style.
#function-rgx=
# Good variable names which should always be accepted, separated by a comma.
good-names=i,
j,
k,
ex,
Run,
_
# Include a hint for the correct naming format with invalid-name.
include-naming-hint=no
# Naming style matching correct inline iteration names.
inlinevar-naming-style=any
# Regular expression matching correct inline iteration names. Overrides
# inlinevar-naming-style.
#inlinevar-rgx=
# Naming style matching correct method names.
method-naming-style=snake_case
# Regular expression matching correct method names. Overrides method-naming-
# style.
#method-rgx=
# Naming style matching correct module names.
module-naming-style=snake_case
# Regular expression matching correct module names. Overrides module-naming-
# style.
#module-rgx=
# Colon-delimited sets of names that determine each other's naming style when
# the name regexes allow several styles.
name-group=
# Regular expression which should only match function or class names that do
# not require a docstring.
no-docstring-rgx=^_
# List of decorators that produce properties, such as abc.abstractproperty. Add
# to this list to register other decorators that produce valid properties.
# These decorators are taken in consideration only for invalid-name.
property-classes=abc.abstractproperty
# Naming style matching correct variable names.
variable-naming-style=snake_case
# Regular expression matching correct variable names. Overrides variable-
# naming-style.
#variable-rgx=
[VARIABLES]
# List of additional names supposed to be defined in builtins. Remember that
# you should avoid to define new builtins when possible.
additional-builtins=
# Tells whether unused global variables should be treated as a violation.
allow-global-unused-variables=yes
# List of strings which can identify a callback function by name. A callback
# name must start or end with one of those strings.
callbacks=cb_,
_cb
# A regular expression matching the name of dummy variables (i.e. expected to
# not be used).
dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_
# Argument names that match this expression will be ignored. Default to name
# with leading underscore.
ignored-argument-names=_.*|^ignored_|^unused_
# Tells whether we should check for unused import in __init__ files.
init-import=no
# List of qualified module names which can have objects that can redefine
# builtins.
redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io
[FORMAT]
# Expected format of line ending, e.g. empty (any line ending), LF or CRLF.
expected-line-ending-format=
# Regexp for a line that is allowed to be longer than the limit.
ignore-long-lines=^\s*(# )?<?https?://\S+>?$
# Number of spaces of indent required inside a hanging or continued line.
indent-after-paren=4
# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1
# tab).
indent-string=' '
# Maximum number of characters on a single line.
max-line-length=100
# Maximum number of lines in a module.
max-module-lines=1000
# List of optional constructs for which whitespace checking is disabled. `dict-
# separator` is used to allow tabulation in dicts, etc.: {1 : 1,\n222: 2}.
# `trailing-comma` allows a space between comma and closing bracket: (a, ).
# `empty-line` allows space-only lines.
no-space-check=trailing-comma,
dict-separator
# Allow the body of a class to be on the same line as the declaration if body
# contains single statement.
single-line-class-stmt=no
# Allow the body of an if to be on the same line as the test if there is no
# else.
single-line-if-stmt=no
[TYPECHECK]
# List of decorators that produce context managers, such as
# contextlib.contextmanager. Add to this list to register other decorators that
# produce valid context managers.
contextmanager-decorators=contextlib.contextmanager
# List of members which are set dynamically and missed by pylint inference
# system, and so shouldn't trigger E1101 when accessed. Python regular
# expressions are accepted.
generated-members=
# Tells whether missing members accessed in mixin class should be ignored. A
# mixin class is detected if its name ends with "mixin" (case insensitive).
ignore-mixin-members=yes
# Tells whether to warn about missing members when the owner of the attribute
# is inferred to be None.
ignore-none=yes
# This flag controls whether pylint should warn about no-member and similar
# checks whenever an opaque object is returned when inferring. The inference
# can return multiple potential results while evaluating a Python object, but
# some branches might not be evaluated, which results in partial inference. In
# that case, it might be useful to still emit no-member and other checks for
# the rest of the inferred objects.
ignore-on-opaque-inference=yes
# List of class names for which member attributes should not be checked (useful
# for classes with dynamically set attributes). This supports the use of
# qualified names.
ignored-classes=optparse.Values,thread._local,_thread._local
# List of module names for which member attributes should not be checked
# (useful for modules/projects where namespaces are manipulated during runtime
# and thus existing member attributes cannot be deduced by static analysis. It
# supports qualified module names, as well as Unix pattern matching.
ignored-modules=
# Show a hint with possible names when a member name was not found. The aspect
# of finding the hint is based on edit distance.
missing-member-hint=yes
# The minimum edit distance a name should have in order to be considered a
# similar match for a missing member name.
missing-member-hint-distance=1
# The total number of similar names that should be taken in consideration when
# showing a hint for a missing member.
missing-member-max-choices=1
[LOGGING]
# Logging modules to check that the string format arguments are in logging
# function parameter format.
logging-modules=logging
[MISCELLANEOUS]
# List of note tags to take in consideration, separated by a comma.
notes=FIXME,
XXX,
TODO
[SIMILARITIES]
# Ignore comments when computing similarities.
ignore-comments=yes
# Ignore docstrings when computing similarities.
ignore-docstrings=yes
# Ignore imports when computing similarities.
ignore-imports=no
# Minimum lines number of a similarity.
min-similarity-lines=4
[SPELLING]
# Limits count of emitted suggestions for spelling mistakes.
max-spelling-suggestions=4
# Spelling dictionary name. Available dictionaries: none. To make it working
# install python-enchant package..
spelling-dict=
# List of comma separated words that should not be checked.
spelling-ignore-words=
# A path to a file that contains private dictionary; one word per line.
spelling-private-dict-file=
# Tells whether to store unknown words to indicated private dictionary in
# --spelling-private-dict-file option instead of raising a message.
spelling-store-unknown-words=no
[IMPORTS]
# Allow wildcard imports from modules that define __all__.
allow-wildcard-with-all=no
# Analyse import fallback blocks. This can be used to support both Python 2 and
# 3 compatible code, which means that the block might have code that exists
# only in one or another interpreter, leading to false positives when analysed.
analyse-fallback-blocks=no
# Deprecated modules which should not be used, separated by a comma.
deprecated-modules=optparse,tkinter.tix
# Create a graph of external dependencies in the given file (report RP0402 must
# not be disabled).
ext-import-graph=
# Create a graph of every (i.e. internal and external) dependencies in the
# given file (report RP0402 must not be disabled).
import-graph=
# Create a graph of internal dependencies in the given file (report RP0402 must
# not be disabled).
int-import-graph=
# Force import order to recognize a module as part of the standard
# compatibility libraries.
known-standard-library=
# Force import order to recognize a module as part of a third party library.
known-third-party=enchant
[DESIGN]
# Maximum number of arguments for function / method.
max-args=5
# Maximum number of attributes for a class (see R0902).
max-attributes=7
# Maximum number of boolean expressions in an if statement.
max-bool-expr=5
# Maximum number of branch for function / method body.
max-branches=12
# Maximum number of locals for function / method body.
max-locals=15
# Maximum number of parents for a class (see R0901).
max-parents=7
# Maximum number of public methods for a class (see R0904).
max-public-methods=20
# Maximum number of return / yield for function / method body.
max-returns=6
# Maximum number of statements in function / method body.
max-statements=50
# Minimum number of public methods for a class (see R0903).
min-public-methods=2
[CLASSES]
# List of method names used to declare (i.e. assign) instance attributes.
defining-attr-methods=__init__,
__new__,
setUp
# List of member names, which should be excluded from the protected access
# warning.
exclude-protected=_asdict,
_fields,
_replace,
_source,
_make
# List of valid names for the first argument in a class method.
valid-classmethod-first-arg=cls
# List of valid names for the first argument in a metaclass class method.
valid-metaclass-classmethod-first-arg=cls
[EXCEPTIONS]
# Exceptions that will emit a warning when being caught. Defaults to
# "Exception".
overgeneral-exceptions=Exception
| 15,868
|
Python
|
.py
| 382
| 39.180628
| 89
| 0.786096
|
Guake/guake
| 4,406
| 575
| 405
|
GPL-2.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,042
|
conf.py
|
Guake_guake/docs/source/conf.py
|
# -*- coding: utf-8 -*-
#
# Python Fix Imports documentation build configuration file, created by
# sphinx-quickstart on Fri Apr 1 14:41:17 2016.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
# sys.path.insert(0, os.path.abspath('.'))
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
"sphinx.ext.doctest",
"reno.sphinxext",
"sphinxcontrib.programoutput",
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ["_templates"]
# The suffix of source filenames.
source_suffix = ".rst"
# The encoding of source files.
# source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = "index"
# General information about the project.
project = "Guake"
copyright = "2018, Gaetan Semet"
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = "1.0"
# The full version, including alpha/beta/rc tags.
release = "1.0"
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
# language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
# today = ''
# Else, today_fmt is used as the format for a strftime call.
# today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = []
# The reST default role (used for this markup: `text`) to use for all
# documents.
# default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
# add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
# add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
# show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = "sphinx"
# A list of ignored prefixes for module index sorting.
# modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
# keep_warnings = False
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = "sphinx_rtd_theme"
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
# html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
# html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
# html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
# html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
# html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
# html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ["_static"]
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
# html_extra_path = []
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
# html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
# html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
# html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
# html_additional_pages = {}
# If false, no module index is generated.
# html_domain_indices = True
# If false, no index is generated.
# html_use_index = True
# If true, the index is split into individual pages for each letter.
# html_split_index = False
# If true, links to the reST sources are added to the pages.
# html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
# html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
# html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
# html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
# html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = "PythonFixImportsdoc"
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
# 'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
("index", "PythonFixImports.tex", "Python Fix Imports Documentation", "Gaetan Semet", "manual"),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
# latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
# latex_use_parts = False
# If true, show page references after internal links.
# latex_show_pagerefs = False
# If true, show URL addresses after external links.
# latex_show_urls = False
# Documents to append as an appendix to all manuals.
# latex_appendices = []
# If false, no module index is generated.
# latex_domain_indices = True
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [("index", "pythonfiximports", "Python Fix Imports Documentation", ["Gaetan Semet"], 1)]
# If true, show URL addresses after external links.
# man_show_urls = False
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(
"index",
"PythonFixImports",
"Python Fix Imports Documentation",
"Gaetan Semet",
"PythonFixImports",
"One line description of project.",
"Miscellaneous",
),
]
# Documents to append as an appendix to all manuals.
# texinfo_appendices = []
# If false, no module index is generated.
# texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
# texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
# texinfo_no_detailmenu = False
| 8,391
|
Python
|
.py
| 194
| 41.402062
| 100
| 0.720993
|
Guake/guake
| 4,406
| 575
| 405
|
GPL-2.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,043
|
test-exception.py
|
Guake_guake/scripts/test-exception.py
|
#!/usr/bin/env python3
print("Quick Open test: exception traceback")
def func4():
raise ValueError("This is an exception")
def func2():
func3() # noqa: F821
def func1():
func2()
if __name__ == "__main__":
func1()
| 239
|
Python
|
.py
| 10
| 20.4
| 45
| 0.640909
|
Guake/guake
| 4,406
| 575
| 405
|
GPL-2.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,044
|
all-sitedirs-in-prefix.py
|
Guake_guake/scripts/all-sitedirs-in-prefix.py
|
from __future__ import print_function
import os
import site
prefix = os.getenv("PREFIX")
for d in site.getsitepackages(None if not prefix else [prefix]):
print(d)
| 169
|
Python
|
.py
| 6
| 26.166667
| 64
| 0.763975
|
Guake/guake
| 4,406
| 575
| 405
|
GPL-2.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,045
|
guake_toggle.py
|
Guake_guake/guake/guake_toggle.py
|
def toggle_guake_by_dbus():
import dbus # pylint: disable=import-outside-toplevel
try:
bus = dbus.SessionBus()
remote_object = bus.get_object("org.guake3.RemoteControl", "/org/guake3/RemoteControl")
print("Sending 'toggle' message to Guake3")
remote_object.show_hide()
except dbus.DBusException:
pass
| 355
|
Python
|
.py
| 9
| 32.555556
| 95
| 0.672464
|
Guake/guake
| 4,406
| 575
| 405
|
GPL-2.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,046
|
boxes.py
|
Guake_guake/guake/boxes.py
|
import logging
import time
import gi
gi.require_version("Vte", "2.91") # vte-0.42
gi.require_version("Gtk", "3.0")
from gi.repository import GObject
from gi.repository import Gdk
from gi.repository import Gio
from gi.repository import Gtk
from gi.repository import Vte
from guake.callbacks import MenuHideCallback
from guake.callbacks import TerminalContextMenuCallbacks
from guake.dialogs import PromptResetColorsDialog
from guake.dialogs import RenameDialog
from guake.globals import PCRE2_MULTILINE
from guake.menus import mk_tab_context_menu
from guake.menus import mk_terminal_context_menu
from guake.utils import HidePrevention
from guake.utils import TabNameUtils
from guake.utils import get_server_time
from guake.utils import save_tabs_when_changed
log = logging.getLogger(__name__)
# TODO remove calls to guake
class TerminalHolder:
UP = 0
DOWN = 1
RIGHT = 2
LEFT = 3
def get_terminals(self):
raise NotImplementedError
def iter_terminals(self):
raise NotImplementedError
def replace_child(self, old, new):
raise NotImplementedError
def get_guake(self):
raise NotImplementedError
def get_window(self):
raise NotImplementedError
def get_settings(self):
raise NotImplementedError
def get_root_box(self):
raise NotImplementedError
def get_notebook(self):
raise NotImplementedError
def remove_dead_child(self, child):
raise NotImplementedError
class RootTerminalBox(Gtk.Overlay, TerminalHolder):
def __init__(self, guake, parent_notebook):
super().__init__()
self.guake = guake
self.notebook = parent_notebook
self.child = None
self.last_terminal_focused = None
self.searchstring = None
self.searchre = None
self._add_search_box()
def _add_search_box(self):
"""--------------------------------------|
| Revealer |
| |-----------------------------------|
| | Frame |
| | |---------------------------------|
| | | HBox |
| | | |---| |-------| |----| |------| |
| | | | x | | Entry | |Prev| | Next | |
| | | |---| |-------| |----| |------| |
--------------------------------------|
"""
self.search_revealer = Gtk.Revealer()
self.search_frame = Gtk.Frame(name="search-frame")
self.search_box = Gtk.HBox()
# Search
self.search_close_btn = Gtk.Button()
self.search_close_btn.set_can_focus(False)
close_icon = Gio.ThemedIcon(name="window-close-symbolic")
close_image = Gtk.Image.new_from_gicon(close_icon, Gtk.IconSize.BUTTON)
self.search_close_btn.set_image(close_image)
self.search_entry = Gtk.SearchEntry()
self.search_prev_btn = Gtk.Button()
self.search_prev_btn.set_can_focus(False)
prev_icon = Gio.ThemedIcon(name="go-up-symbolic")
prev_image = Gtk.Image.new_from_gicon(prev_icon, Gtk.IconSize.BUTTON)
self.search_prev_btn.set_image(prev_image)
self.search_next_btn = Gtk.Button()
self.search_next_btn.set_can_focus(False)
next_icon = Gio.ThemedIcon(name="go-down-symbolic")
next_image = Gtk.Image.new_from_gicon(next_icon, Gtk.IconSize.BUTTON)
self.search_next_btn.set_image(next_image)
# Pack into box
self.search_box.pack_start(self.search_close_btn, False, False, 0)
self.search_box.pack_start(self.search_entry, False, False, 0)
self.search_box.pack_start(self.search_prev_btn, False, False, 0)
self.search_box.pack_start(self.search_next_btn, False, False, 0)
# Add into frame
self.search_frame.add(self.search_box)
# Frame
self.search_frame.set_margin_end(12)
self.search_frame.get_style_context().add_class("background")
css_provider = Gtk.CssProvider()
css_provider.load_from_data(
b"#search-frame border {" b" padding: 5px 5px 5px 5px;" b" border: none;" b"}"
)
Gtk.StyleContext.add_provider_for_screen(
Gdk.Screen.get_default(),
css_provider,
Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION,
)
# Add to revealer
self.search_revealer.add(self.search_frame)
self.search_revealer.set_transition_duration(500)
self.search_revealer.set_transition_type(Gtk.RevealerTransitionType.CROSSFADE)
self.search_revealer.set_valign(Gtk.Align.END)
self.search_revealer.set_halign(Gtk.Align.END)
# Welcome to the overlay
self.add_overlay(self.search_revealer)
# Events
self.search_entry.connect("key-press-event", self.on_search_entry_keypress)
self.search_entry.connect("changed", self.set_search)
self.search_entry.connect("activate", self.do_search)
self.search_entry.connect("focus-in-event", self.on_search_entry_focus_in)
self.search_entry.connect("focus-out-event", self.on_search_entry_focus_out)
self.search_next_btn.connect("clicked", self.on_search_next_clicked)
self.search_prev_btn.connect("clicked", self.on_search_prev_clicked)
self.search_close_btn.connect("clicked", self.close_search_box)
self.search_prev = True
# Search revealer visible
def search_revealer_show_cb(widget):
if not widget.get_child_revealed():
widget.hide()
self.search_revealer.hide()
self.search_revealer_show_cb_id = self.search_revealer.connect(
"show", search_revealer_show_cb
)
self.search_frame.connect("unmap", lambda x: self.search_revealer.hide())
def get_terminals(self):
return self.get_child().get_terminals()
def iter_terminals(self):
if self.get_child() is not None:
for t in self.get_child().iter_terminals():
yield t
def replace_child(self, old, new):
self.remove(old)
self.set_child(new)
def set_child(self, terminal_holder):
if isinstance(terminal_holder, TerminalHolder):
self.child = terminal_holder
self.add(self.child)
else:
raise RuntimeError(f"Error adding (RootTerminalBox.add({type(terminal_holder)}))")
def get_child(self):
return self.child
def get_guake(self):
return self.guake
def get_window(self):
return self.guake.window
def get_settings(self):
return self.guake.settings
def get_root_box(self):
return self
def save_box_layout(self, box, panes: list):
"""Save box layout with pre-order traversal, it should result `panes` with
a full binary tree in list.
"""
if not box:
panes.append({"type": None, "directory": None})
return
if isinstance(box, DualTerminalBox):
btype = "dual" + ("_h" if box.orient is DualTerminalBox.ORIENT_V else "_v")
panes.append({"type": btype, "directory": None})
self.save_box_layout(box.get_child1(), panes)
self.save_box_layout(box.get_child2(), panes)
elif isinstance(box, TerminalBox):
btype = "term"
directory = box.terminal.get_current_directory()
panes.append(
{
"type": btype,
"directory": directory,
"custom_colors": box.terminal.get_custom_colors_dict(),
}
)
def restore_box_layout(self, box, panes: list):
"""Restore box layout by `panes`"""
if not panes or not isinstance(panes, list):
return
if not box or not isinstance(box, TerminalBox):
# Should only called on TerminalBox
return
cur = panes.pop(0)
if cur["type"].startswith("dual"):
while True:
if self.guake:
# If Guake are not visible, we should pending the restore, then do the
# restore when Guake is visible again.
#
# Otherwise we will stuck in the infinite loop, since new DualTerminalBox
# cannot get any allocation when Guake is invisible
if (
not self.guake.window.get_property("visible")
or self.get_notebook()
is not self.guake.notebook_manager.get_current_notebook()
):
panes.insert(0, cur)
self.guake._failed_restore_page_split.append((self, box, panes))
return
# UI didn't update, wait for it
alloc = box.get_allocation()
if alloc.width == 1 and alloc.height == 1:
time.sleep(0.01)
else:
break
# Waiting for UI update..
while Gtk.events_pending():
Gtk.main_iteration()
if cur["type"].endswith("v"):
box = box.split_v_no_save()
else:
box = box.split_h_no_save()
self.restore_box_layout(box.get_child1(), panes)
self.restore_box_layout(box.get_child2(), panes)
else:
if box.terminal:
term = box.terminal
# Remove signal handler from terminal
for i in term.handler_ids:
term.disconnect(i)
term.handler_ids = []
box.remove(box.scroll)
box.remove(term)
box.unset_terminal()
# Replace term in the TerminalBox
term = self.get_notebook().terminal_spawn(cur["directory"])
term.set_custom_colors_from_dict(cur.get("custom_colors", None))
box.set_terminal(term)
self.get_notebook().terminal_attached(term)
def set_last_terminal_focused(self, terminal):
self.last_terminal_focused = terminal
self.get_notebook().set_last_terminal_focused(terminal)
def get_last_terminal_focused(self, terminal):
return self.last_terminal_focused
def get_notebook(self):
return self.notebook
def remove_dead_child(self, child):
page_num = self.get_notebook().page_num(self)
self.get_notebook().remove_page(page_num)
def block_notebook_on_button_press_id(self):
GObject.signal_handler_block(
self.get_notebook(), self.get_notebook().notebook_on_button_press_id
)
def unblock_notebook_on_button_press_id(self):
GObject.signal_handler_unblock(
self.get_notebook(), self.get_notebook().notebook_on_button_press_id
)
def show_search_box(self):
if not self.search_revealer.get_reveal_child():
GObject.signal_handler_block(self.search_revealer, self.search_revealer_show_cb_id)
self.search_revealer.set_visible(True)
self.search_revealer.set_reveal_child(True)
GObject.signal_handler_unblock(self.search_revealer, self.search_revealer_show_cb_id)
# XXX: Mestery line to avoid Gtk-CRITICAL stuff
# (guake:22694): Gtk-CRITICAL **: 18:04:57.345:
# gtk_widget_event: assertion 'WIDGET_REALIZED_FOR_EVENT (widget, event)' failed
self.search_entry.realize()
self.search_entry.grab_focus()
def hide_search_box(self):
if self.search_revealer.get_reveal_child():
self.search_revealer.set_reveal_child(False)
self.last_terminal_focused.grab_focus()
self.last_terminal_focused.unselect_all()
def close_search_box(self, event):
self.hide_search_box()
def on_search_entry_focus_in(self, event, user_data):
self.block_notebook_on_button_press_id()
def on_search_entry_focus_out(self, event, user_data):
self.unblock_notebook_on_button_press_id()
def on_search_prev_clicked(self, widget):
term = self.last_terminal_focused
result = term.search_find_previous()
if not result:
term.search_find_previous()
def on_search_next_clicked(self, widget):
term = self.last_terminal_focused
result = term.search_find_next()
if not result:
term.search_find_next()
def on_search_entry_keypress(self, widget, event):
key = Gdk.keyval_name(event.keyval)
if key == "Escape":
self.hide_search_box()
elif key == "Return":
# Combine with Shift?
if event.state & Gdk.ModifierType.SHIFT_MASK:
self.search_prev = False
self.do_search(None)
else:
self.search_prev = True
def reset_term_search(self, term):
term.search_set_regex(None, 0)
term.search_find_next()
def set_search(self, widget):
term = self.last_terminal_focused
text = self.search_entry.get_text()
if not text:
self.reset_term_search(term)
return
if text != self.searchstring:
self.reset_term_search(term)
# Set search regex on term
self.searchstring = text
self.searchre = Vte.Regex.new_for_search(
text, -1, Vte.REGEX_FLAGS_DEFAULT | PCRE2_MULTILINE
)
term.search_set_regex(self.searchre, 0)
self.do_search(None)
def do_search(self, widget):
if self.search_prev:
self.on_search_prev_clicked(None)
else:
self.on_search_next_clicked(None)
class TerminalBox(Gtk.Box, TerminalHolder):
"""A box to group the terminal and a scrollbar."""
def __init__(self):
super().__init__(orientation=Gtk.Orientation.HORIZONTAL)
self.terminal = None
def set_terminal(self, terminal):
"""Packs the terminal widget."""
if self.terminal is not None:
raise RuntimeError("TerminalBox: terminal already set")
self.terminal = terminal
self.terminal.handler_ids.append(
self.terminal.connect("grab-focus", self.on_terminal_focus)
)
self.terminal.handler_ids.append(
self.terminal.connect("button-press-event", self.on_button_press, None)
)
self.terminal.handler_ids.append(
self.terminal.connect("child-exited", self.on_terminal_exited)
)
self.pack_start(self.terminal, True, True, 0)
self.terminal.show()
self.add_scroll_bar()
def add_scroll_bar(self):
"""Packs the scrollbar."""
adj = self.terminal.get_vadjustment()
self.scroll = Gtk.Scrollbar.new(Gtk.Orientation.VERTICAL, adj)
self.scroll.show()
self.pack_start(self.scroll, False, False, 0)
self.terminal.handler_ids.append(
self.terminal.connect("scroll-event", self.__scroll_event_cb)
)
def __scroll_event_cb(self, widget, event):
# Adjust scrolling speed when adding "shift" or "shift + ctrl"
adj = self.scroll.get_adjustment()
page_size = adj.get_page_size()
if (
event.get_state() & Gdk.ModifierType.SHIFT_MASK
and event.get_state() & Gdk.ModifierType.CONTROL_MASK
):
# Ctrl + Shift + Mouse Scroll (4 pages)
adj.set_page_increment(page_size * 40)
elif event.get_state() & Gdk.ModifierType.SHIFT_MASK:
# Shift + Mouse Scroll (1 page)
adj.set_page_increment(page_size * 10)
else:
# Mouse Scroll
adj.set_page_increment(page_size)
def get_terminal(self):
return self.terminal
def get_terminals(self):
if self.terminal is not None:
return [self.terminal]
return []
def iter_terminals(self):
if self.terminal is not None:
yield self.terminal
def replace_child(self, old, new):
print("why would you call this on me?")
pass
def unset_terminal(self, *args):
self.terminal = None
def split_h(self, split_percentage: int = 50):
return self.split(DualTerminalBox.ORIENT_V, split_percentage)
def split_v(self, split_percentage: int = 50):
return self.split(DualTerminalBox.ORIENT_H, split_percentage)
def split_h_no_save(self, split_percentage: int = 50):
return self.split_no_save(DualTerminalBox.ORIENT_V, split_percentage)
def split_v_no_save(self, split_percentage: int = 50):
return self.split_no_save(DualTerminalBox.ORIENT_H, split_percentage)
@save_tabs_when_changed
def split(self, orientation, split_percentage: int = 50):
self.split_no_save(orientation, split_percentage)
def split_no_save(self, orientation, split_percentage: int = 50):
notebook = self.get_notebook()
parent = self.get_parent() # RootTerminalBox
if orientation == DualTerminalBox.ORIENT_H:
position = self.get_allocation().width * ((100 - split_percentage) / 100)
else:
position = self.get_allocation().height * ((100 - split_percentage) / 100)
terminal_box = TerminalBox()
terminal = notebook.terminal_spawn()
terminal_box.set_terminal(terminal)
dual_terminal_box = DualTerminalBox(orientation)
dual_terminal_box.set_position(position)
parent.replace_child(self, dual_terminal_box)
dual_terminal_box.set_child_first(self)
dual_terminal_box.set_child_second(terminal_box)
terminal_box.show()
dual_terminal_box.show()
if self.terminal is not None:
# preserve font and font_scale in the new terminal
terminal.set_font(self.terminal.font)
terminal.font_scale = self.terminal.font_scale
notebook.terminal_attached(terminal)
return dual_terminal_box
def get_guake(self):
return self.get_parent().get_guake()
def get_window(self):
return self.get_parent().get_window()
def get_settings(self):
return self.get_parent().get_settings()
def get_root_box(self):
return self.get_parent().get_root_box()
def get_notebook(self):
return self.get_parent().get_notebook()
def remove_dead_child(self, child):
print('Can\'t do, have no "child"')
def on_terminal_focus(self, *args):
self.get_root_box().set_last_terminal_focused(self.terminal)
def on_terminal_exited(self, terminal, status):
if not self.get_parent():
return
self.get_parent().remove_dead_child(self)
def on_button_press(self, target, event, user_data):
if event.button == 3:
# First send to background process if handled, do nothing else
if (
not event.get_state() & Gdk.ModifierType.SHIFT_MASK
and Vte.Terminal.do_button_press_event(self.terminal, event)
):
return True
menu = mk_terminal_context_menu(
self.terminal,
self.get_window(),
self.get_settings(),
TerminalContextMenuCallbacks(
self.terminal,
self.get_window(),
self.get_settings(),
self.get_root_box().get_notebook(),
),
)
menu.connect("hide", MenuHideCallback(self.get_window()).on_hide)
HidePrevention(self.get_window()).prevent()
try:
menu.popup_at_pointer(event)
except AttributeError:
# Gtk 3.18 fallback ("'Menu' object has no attribute 'popup_at_pointer'")
menu.popup(None, None, None, None, event.button, event.time)
self.terminal.grab_focus()
return True
self.terminal.grab_focus()
return False
class DualTerminalBox(Gtk.Paned, TerminalHolder):
ORIENT_H = 0
ORIENT_V = 1
def __init__(self, orientation):
super().__init__()
self.orient = orientation
if orientation is DualTerminalBox.ORIENT_H:
self.set_orientation(orientation=Gtk.Orientation.HORIZONTAL)
else:
self.set_orientation(orientation=Gtk.Orientation.VERTICAL)
def set_child_first(self, terminal_holder):
if isinstance(terminal_holder, TerminalHolder):
self.add1(terminal_holder)
else:
print("wtf, what have you added to me???")
def set_child_second(self, terminal_holder):
if isinstance(terminal_holder, TerminalHolder):
self.add2(terminal_holder)
else:
print("wtf, what have you added to me???")
def get_terminals(self):
return self.get_child1().get_terminals() + self.get_child2().get_terminals()
def iter_terminals(self):
for t in self.get_child1().iter_terminals():
yield t
for t in self.get_child2().iter_terminals():
yield t
def replace_child(self, old, new):
if self.get_child1() is old:
self.remove(old)
self.set_child_first(new)
elif self.get_child2() is old:
self.remove(old)
self.set_child_second(new)
else:
print("I have never seen this widget!")
def get_guake(self):
return self.get_parent().get_guake()
def get_window(self):
return self.get_parent().get_window()
def get_settings(self):
return self.get_parent().get_settings()
def get_root_box(self):
return self.get_parent().get_root_box()
def get_notebook(self):
return self.get_parent().get_notebook()
def grab_box_terminal_focus(self, box):
if isinstance(box, DualTerminalBox):
try:
next(box.iter_terminals()).grab_focus()
except StopIteration:
log.error("Both panes are empty")
else:
box.get_terminal().grab_focus()
@save_tabs_when_changed
def remove_dead_child(self, child):
if self.get_child1() is child:
living_child = self.get_child2()
self.remove(living_child)
self.get_parent().replace_child(self, living_child)
self.grab_box_terminal_focus(living_child)
elif self.get_child2() is child:
living_child = self.get_child1()
self.remove(living_child)
self.get_parent().replace_child(self, living_child)
self.grab_box_terminal_focus(living_child)
else:
print("I have never seen this widget!")
class TabLabelEventBox(Gtk.EventBox):
def __init__(self, notebook, text, settings):
super().__init__()
self.notebook = notebook
self.box = Gtk.Box(homogeneous=Gtk.Orientation.HORIZONTAL, spacing=0, visible=True)
self.label = Gtk.Label(label=text, visible=True)
self.close_button = Gtk.Button(
image=Gtk.Image.new_from_icon_name("window-close", Gtk.IconSize.MENU),
relief=Gtk.ReliefStyle.NONE,
)
self.close_button.connect("clicked", self.on_close)
settings.general.bind(
"tab-close-buttons", self.close_button, "visible", Gio.SettingsBindFlags.GET
)
self.box.pack_start(self.label, True, True, 0)
self.box.pack_end(self.close_button, False, False, 0)
self.add(self.box)
self.connect("button-press-event", self.on_button_press, self.label)
def set_text(self, text):
self.label.set_text(text)
def get_text(self):
return self.label.get_text()
def grab_focus_on_last_focused_terminal(self):
server_time = get_server_time(self.notebook.guake.window)
self.notebook.guake.window.get_window().focus(server_time)
self.notebook.get_current_terminal().grab_focus()
def on_button_press(self, target, event, user_data):
if event.button == 3:
menu = mk_tab_context_menu(self)
menu.connect("hide", MenuHideCallback(self.get_toplevel()).on_hide)
HidePrevention(self.get_toplevel()).prevent()
try:
menu.popup_at_pointer(event)
except AttributeError:
# Gtk 3.18 fallback ("'Menu' object has no attribute 'popup_at_pointer'")
menu.popup(None, None, None, None, event.button, event.get_time())
return True
if event.button == 2:
prompt_cfg = self.notebook.guake.settings.general.get_int("prompt-on-close-tab")
self.notebook.delete_page_by_label(self, prompt=prompt_cfg)
return True
if event.button == 1 and event.type == Gdk.EventType._2BUTTON_PRESS:
self.on_rename(None)
return False
@save_tabs_when_changed
def on_new_tab(self, user_data):
self.notebook.new_page_with_focus()
@save_tabs_when_changed
def on_rename(self, user_data):
HidePrevention(self.get_toplevel()).prevent()
dialog = RenameDialog(self.notebook.guake.window, self.label.get_text())
r = dialog.run()
if r == Gtk.ResponseType.ACCEPT:
new_text = TabNameUtils.shorten(dialog.get_text(), self.notebook.guake.settings)
page_num = self.notebook.find_tab_index_by_label(self)
self.notebook.rename_page(page_num, new_text, True)
dialog.destroy()
HidePrevention(self.get_toplevel()).allow()
self.grab_focus_on_last_focused_terminal()
@save_tabs_when_changed
def on_reset_custom_colors(self, user_data):
HidePrevention(self.get_toplevel()).prevent()
if PromptResetColorsDialog(self.notebook.guake.window).reset_tab_custom_colors():
page_num = self.notebook.find_tab_index_by_label(self)
for t in self.notebook.get_nth_page(page_num).iter_terminals():
t.reset_custom_colors()
self.notebook.guake.set_colors_from_settings_on_page(page_num=page_num)
HidePrevention(self.get_toplevel()).allow()
self.grab_focus_on_last_focused_terminal()
def on_close(self, user_data):
prompt_cfg = self.notebook.guake.settings.general.get_int("prompt-on-close-tab")
self.notebook.delete_page_by_label(self, prompt=prompt_cfg)
| 26,511
|
Python
|
.py
| 602
| 33.852159
| 97
| 0.60982
|
Guake/guake
| 4,406
| 575
| 405
|
GPL-2.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,047
|
about.py
|
Guake_guake/guake/about.py
|
# -*- coding: utf-8; -*-
"""
Copyright (C) 2007-2012 Lincoln de Sousa <lincoln@minaslivre.org>
Copyright (C) 2007 Gabriel Falc√£o <gabrielteratos@gmail.com>
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 gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk
from guake import guake_version
from guake.common import gladefile
from guake.common import pixmapfile
from guake.simplegladeapp import SimpleGladeApp
class AboutDialog(SimpleGladeApp):
"""The About Guake dialog class"""
def __init__(self):
super().__init__(gladefile("about.glade"), root="aboutdialog")
dialog = self.get_widget("aboutdialog")
# images
image = Gtk.Image()
image.set_from_file(pixmapfile("guake-notification.png"))
pixbuf = image.get_pixbuf()
dialog.set_property("logo", pixbuf)
dialog.set_name(_("Guake Terminal"))
dialog.set_version(guake_version())
dialog.connect("response", lambda x, y: dialog.destroy())
| 1,638
|
Python
|
.py
| 37
| 40.540541
| 70
| 0.745592
|
Guake/guake
| 4,406
| 575
| 405
|
GPL-2.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,048
|
dbusiface.py
|
Guake_guake/guake/dbusiface.py
|
# -*- coding: utf-8; -*-
"""
Copyright (C) 2007-2013 Guake authors
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
import dbus
import dbus.glib
import dbus.service
log = logging.getLogger(__name__)
dbus.glib.threads_init()
DBUS_PATH = "/org/guake3/RemoteControl"
DBUS_NAME = "org.guake3.RemoteControl"
class DbusManager(dbus.service.Object):
def __init__(self, guakeinstance):
self.guake = guakeinstance
self.bus = dbus.SessionBus()
bus_name = dbus.service.BusName(DBUS_NAME, bus=self.bus)
super().__init__(bus_name, DBUS_PATH)
@dbus.service.method(DBUS_NAME)
def show_hide(self):
self.guake.show_hide()
@dbus.service.method(DBUS_NAME)
def show(self):
self.guake.show()
self.guake.set_terminal_focus()
@dbus.service.method(DBUS_NAME)
def show_from_remote(self):
self.guake.show_from_remote()
self.guake.set_terminal_focus()
@dbus.service.method(DBUS_NAME)
def hide(self):
self.guake.hide()
@dbus.service.method(DBUS_NAME)
def hide_from_remote(self):
self.guake.hide_from_remote()
@dbus.service.method(DBUS_NAME, out_signature="i")
def get_visibility(self):
return self.guake.get_visibility()
@dbus.service.method(DBUS_NAME)
def fullscreen(self):
self.guake.fullscreen()
@dbus.service.method(DBUS_NAME)
def unfullscreen(self):
self.guake.unfullscreen()
@dbus.service.method(DBUS_NAME, in_signature="s")
def add_tab(self, directory=""):
return self.guake.add_tab(directory)
@dbus.service.method(DBUS_NAME)
def close_tab(self):
self.guake.close_tab()
@dbus.service.method(DBUS_NAME, in_signature="i")
def select_tab(self, tab_index=0):
return self.guake.get_notebook().set_current_page(int(tab_index))
@dbus.service.method(DBUS_NAME, out_signature="i")
def get_selected_tab(self):
return self.guake.get_notebook().get_current_page()
@dbus.service.method(DBUS_NAME, out_signature="s")
def get_selected_tablabel(self):
return self.guake.get_notebook().get_tab_text_index(
self.guake.get_notebook().get_current_page()
)
@dbus.service.method(DBUS_NAME, out_signature="i")
def get_tab_count(self):
return len(self.guake.notebook_manager.get_terminals())
@dbus.service.method(DBUS_NAME, in_signature="i")
def select_terminal(self, term_index=0):
notebook = self.guake.get_notebook()
current_page_index = notebook.get_current_page()
terminals = notebook.get_terminals_for_page(current_page_index)
return terminals[term_index].grab_focus()
@dbus.service.method(DBUS_NAME, out_signature="i")
def get_selected_terminal(self):
notebook = self.guake.get_notebook()
current_page_index = notebook.get_current_page()
terminals = notebook.get_terminals_for_page(current_page_index)
for i, term in enumerate(terminals, 0):
if term.is_focus():
return i
return -1
@dbus.service.method(DBUS_NAME, out_signature="i")
def get_term_count(self):
notebook = self.guake.get_notebook()
current_page_index = notebook.get_current_page()
terminals = notebook.get_terminals_for_page(current_page_index)
return len(terminals)
@dbus.service.method(DBUS_NAME, in_signature="s")
def set_bgcolor(self, bgcolor):
return self.guake.set_bgcolor(bgcolor)
@dbus.service.method(DBUS_NAME, in_signature="s")
def set_fgcolor(self, fgcolor):
return self.guake.set_fgcolor(fgcolor)
@dbus.service.method(DBUS_NAME, in_signature="s")
def set_bgcolor_current_terminal(self, bgcolor):
return self.guake.set_bgcolor(bgcolor, current_terminal_only=True)
@dbus.service.method(DBUS_NAME, in_signature="s")
def set_fgcolor_current_terminal(self, fgcolor):
return self.guake.set_fgcolor(fgcolor, current_terminal_only=True)
@dbus.service.method(DBUS_NAME, in_signature="s")
def change_palette_name(self, palette_name):
self.guake.change_palette_name(palette_name)
@dbus.service.method(DBUS_NAME)
def reset_colors(self):
self.guake.reset_terminal_custom_colors(current_page=True)
self.guake.set_colors_from_settings_on_page()
@dbus.service.method(DBUS_NAME)
def reset_colors_current(self):
self.guake.reset_terminal_custom_colors(current_terminal=True)
self.guake.set_colors_from_settings_on_page(current_terminal_only=True)
@dbus.service.method(DBUS_NAME, in_signature="s")
def execute_command(self, command):
self.guake.add_tab()
self.guake.execute_command(command)
@dbus.service.method(DBUS_NAME, in_signature="i", out_signature="s")
def get_tab_name(self, tab_index=0):
return self.guake.get_notebook().get_tab_text_index(tab_index)
@dbus.service.method(DBUS_NAME, in_signature="ss")
def rename_tab_uuid(self, tab_uuid, new_text):
self.guake.rename_tab_uuid(tab_uuid, new_text, True)
@dbus.service.method(DBUS_NAME, in_signature="is")
def rename_tab(self, tab_index, new_text):
self.guake.get_notebook().rename_page(tab_index, new_text, True)
@dbus.service.method(DBUS_NAME, in_signature="s")
def rename_current_tab(self, new_text):
self.guake.rename_current_tab(new_text, True)
@dbus.service.method(DBUS_NAME)
def show_about(self):
self.guake.show_about()
@dbus.service.method(DBUS_NAME)
def show_prefs(self):
self.guake.show_prefs()
@dbus.service.method(DBUS_NAME)
def quit(self):
self.guake.quit()
@dbus.service.method(DBUS_NAME, in_signature="i", out_signature="s")
def get_gtktab_name(self, tab_index=0):
return self.guake.get_notebook().get_tab_text_index(tab_index)
@dbus.service.method(DBUS_NAME, out_signature="s")
def get_selected_uuidtab(self):
return self.guake.get_selected_uuidtab()
@dbus.service.method(DBUS_NAME, in_signature="i")
def v_split_current_terminal(self, split_percentage: int):
self.guake.get_notebook().get_current_terminal().get_parent().split_v(split_percentage)
@dbus.service.method(DBUS_NAME, in_signature="i")
def h_split_current_terminal(self, split_percentage: int):
self.guake.get_notebook().get_current_terminal().get_parent().split_h(split_percentage)
@dbus.service.method(DBUS_NAME, in_signature="si")
def v_split_current_terminal_with_command(self, command, split_percentage: int):
self.guake.get_notebook().get_current_terminal().get_parent().split_v(split_percentage)
self.guake.execute_command(command)
@dbus.service.method(DBUS_NAME, in_signature="si")
def h_split_current_terminal_with_command(self, command, split_percentage: int):
self.guake.get_notebook().get_current_terminal().get_parent().split_h(split_percentage)
self.guake.execute_command(command)
@dbus.service.method(DBUS_NAME, in_signature="s", out_signature="i")
def get_index_from_uuid(self, tab_uuid):
return self.guake.get_index_from_uuid(tab_uuid)
| 7,846
|
Python
|
.py
| 168
| 40.386905
| 95
| 0.699305
|
Guake/guake
| 4,406
| 575
| 405
|
GPL-2.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,049
|
dialogs.py
|
Guake_guake/guake/dialogs.py
|
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk
class RenameDialog(Gtk.Dialog):
def __init__(self, window, current_name):
super().__init__(
_("Rename tab"),
window,
Gtk.DialogFlags.MODAL | Gtk.DialogFlags.DESTROY_WITH_PARENT,
(
Gtk.STOCK_CANCEL,
Gtk.ResponseType.REJECT,
Gtk.STOCK_OK,
Gtk.ResponseType.ACCEPT,
),
)
self.entry = Gtk.Entry()
self.entry.set_text(current_name)
self.entry.set_property("can-default", True)
self.entry.show()
vbox = Gtk.VBox()
vbox.set_border_width(6)
vbox.show()
self.set_size_request(300, -1)
self.vbox.pack_start(vbox, True, True, 0)
self.set_border_width(4)
self.set_default_response(Gtk.ResponseType.ACCEPT)
self.add_action_widget(self.entry, Gtk.ResponseType.ACCEPT)
self.entry.reparent(vbox)
def get_text(self):
return self.entry.get_text()
class PromptQuitDialog(Gtk.MessageDialog):
"""Prompts the user whether to quit/close a tab."""
def __init__(self, parent, procs, tabs, notebooks):
super().__init__(
parent,
Gtk.DialogFlags.MODAL | Gtk.DialogFlags.DESTROY_WITH_PARENT,
Gtk.MessageType.QUESTION,
Gtk.ButtonsType.YES_NO,
)
if tabs == -1:
primary_msg = _("Do you want to close the tab?")
tab_str = ""
notebooks_str = ""
else:
primary_msg = _("Do you really want to quit Guake?")
if tabs == 1:
tab_str = _(" and one tab open")
else:
tab_str = _(" and {0} tabs open").format(tabs)
if notebooks > 1:
notebooks_str = _(" on {0} workspaces").format(notebooks)
else:
notebooks_str = ""
if not procs:
proc_str = _("There are no processes running")
elif len(procs) == 1:
proc_str = _("There is a process still running")
else:
proc_str = _("There are {0} processes still running").format(len(procs))
if procs:
proc_list = "\n\n" + "\n".join(f"{name} ({pid})" for pid, name in procs)
else:
proc_list = ""
self.set_markup(primary_msg)
self.format_secondary_markup(f"<b>{proc_str}{tab_str}{notebooks_str}.</b>{proc_list}")
def quit(self):
"""Run the "are you sure" dialog for quitting Guake"""
# Stop an open "close tab" dialog from obstructing a quit
response = self.run() == Gtk.ResponseType.YES
self.destroy()
# Keep Guake focussed after dismissing tab-close prompt
# if tab == -1:
# self.window.present()
return response
def close_tab(self):
response = self.run() == Gtk.ResponseType.YES
self.destroy()
# Keep Guake focussed after dismissing tab-close prompt
# if tab == -1:
# self.window.present()
return response
class PromptResetColorsDialog(Gtk.MessageDialog):
"""Prompts the user whether to reset tab colors."""
def __init__(self, parent):
super().__init__(
parent,
Gtk.DialogFlags.MODAL | Gtk.DialogFlags.DESTROY_WITH_PARENT,
Gtk.MessageType.QUESTION,
Gtk.ButtonsType.YES_NO,
)
primary_msg = _("Do you want to reset custom colors for this tab?")
self.set_markup(primary_msg)
def reset_tab_custom_colors(self):
"""Run the "are you sure" dialog for resetting tab colors"""
# Stop an open "close tab" dialog from obstructing a quit
response = self.run() == Gtk.ResponseType.YES
self.destroy()
# Keep Guake focussed after dismissing tab-close prompt
# if tab == -1:
# self.window.present()
return response
class SaveTerminalDialog(Gtk.FileChooserDialog):
def __init__(self, terminal, window):
super().__init__(
_("Save to..."),
window,
Gtk.FileChooserAction.SAVE,
(
Gtk.STOCK_CANCEL,
Gtk.ResponseType.CANCEL,
Gtk.STOCK_SAVE,
Gtk.ResponseType.OK,
),
)
self.set_default_response(Gtk.ResponseType.OK)
self.terminal = terminal
self.parent_window = window
def run(self):
self.terminal.select_all()
self.terminal.copy_clipboard()
self.terminal.unselect_all()
clipboard = Gtk.Clipboard.get_default(self.parent_window.get_display())
selection = clipboard.wait_for_text()
if not selection:
return
selection = selection.rstrip()
filter = Gtk.FileFilter()
filter.set_name(_("All files"))
filter.add_pattern("*")
self.add_filter(filter)
filter = Gtk.FileFilter()
filter.set_name(_("Text and Logs"))
filter.add_pattern("*.log")
filter.add_pattern("*.txt")
self.add_filter(filter)
response = super().run()
if response == Gtk.ResponseType.OK:
filename = self.get_filename()
with open(filename, "w", encoding="utf-8") as f:
f.write(selection)
self.destroy()
| 5,415
|
Python
|
.py
| 142
| 27.950704
| 94
| 0.565491
|
Guake/guake
| 4,406
| 575
| 405
|
GPL-2.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,050
|
customcommands.py
|
Guake_guake/guake/customcommands.py
|
import json
import os
import gi
import logging
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk
log = logging.getLogger(__name__)
class CustomCommands:
"""
Example for a custom commands file
[
{
"type": "menu",
"description": "dir listing",
"items": [
{
"description": "la",
"cmd":["ls", "-la"]
},
{
"description": "tree",
"cmd":["tree", ""]
}
]
},
{
"description": "less ls",
"cmd": ["ls | less", ""]
}
]
"""
def __init__(self, settings, callback):
self.settings = settings
self.callback = callback
def should_load(self):
file_path = self.settings.general.get_string("custom-command-file")
return file_path is not None
def get_file_path(self):
return os.path.expanduser(self.settings.general.get_string("custom-command-file"))
def _load_json(self, file_name):
if not os.path.exists(file_name):
log.error("Custom file does not exit: %s", file_name)
return None
try:
with open(file_name, encoding="utf-8") as f:
data_file = f.read()
return json.loads(data_file)
except Exception as e:
log.exception("Invalid custom command file %s. Exception: %s", file_name, str(e))
def build_menu(self):
if not self.should_load():
return None
menu = Gtk.Menu()
cust_comms = self._load_json(self.get_file_path())
if not cust_comms:
return None
for obj in cust_comms:
try:
self._parse_custom_commands(obj, menu)
except AttributeError:
log.error("Error parsing %s", obj)
return menu
def _parse_custom_commands(self, json_object, menu):
if json_object.get("type") == "menu":
newmenu = Gtk.Menu()
newmenuitem = Gtk.MenuItem(json_object["description"])
newmenuitem.set_submenu(newmenu)
newmenuitem.show()
menu.append(newmenuitem)
for item in json_object["items"]:
self._parse_custom_commands(item, newmenu)
else:
menu_item = Gtk.MenuItem(json_object["description"])
custom_command = ""
space = ""
for command in json_object["cmd"]:
custom_command += space + command
space = " "
menu_item.connect("activate", self.on_menu_item_activated, custom_command)
menu.append(menu_item)
menu_item.show()
def on_menu_item_activated(self, item, cmd):
self.callback.on_command_selected(cmd)
| 2,958
|
Python
|
.py
| 83
| 23.927711
| 93
| 0.516771
|
Guake/guake
| 4,406
| 575
| 405
|
GPL-2.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,051
|
terminal.py
|
Guake_guake/guake/terminal.py
|
# -*- coding: utf-8; -*-
"""
Copyright (C) 2007-2013 Guake authors
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 code
import logging
import os
import re
import shlex
import signal
import subprocess
import sys
import threading
import uuid
from enum import IntEnum
from pathlib import Path
from typing import Optional
from typing import Tuple
from urllib.parse import unquote
from urllib.parse import urlparse
import gi
gi.require_version("Gtk", "3.0")
gi.require_version("Vte", "2.91") # vte-0.38
from gi.repository import GLib
from gi.repository import Gdk
from gi.repository import Gtk
from gi.repository import Pango
from gi.repository import Vte
from guake.common import clamp
from guake.globals import QUICK_OPEN_MATCHERS
from guake.globals import TERMINAL_MATCH_EXPRS
from guake.globals import TERMINAL_MATCH_TAGS
log = logging.getLogger(__name__)
libutempter = None
try:
# this allow to run some commands that requires libuterm to
# be injected in current process, as: wall
from atexit import register as at_exit_call
from ctypes import cdll
libutempter = cdll.LoadLibrary("libutempter.so.0")
if libutempter is not None:
# We absolutely need to remove the old tty from the utmp !!!
at_exit_call(libutempter.utempter_remove_added_record)
except Exception as e:
libutempter = None
sys.stderr.write("[WARN] ===================================================================\n")
sys.stderr.write("[WARN] Unable to load the library libutempter !\n")
sys.stderr.write(
"[WARN] Some feature might not work:\n"
"[WARN] - 'exit' command might freeze the terminal instead of closing the tab\n"
"[WARN] - the 'wall' command is known to work badly\n"
)
sys.stderr.write("[WARN] Error: " + str(e) + "\n")
sys.stderr.write(
"[WARN] ===================================================================²\n"
)
def halt(loc):
code.interact(local=loc)
__all__ = ["GuakeTerminal"]
# pylint: enable=anomalous-backslash-in-string
class DropTargets(IntEnum):
URIS = 0
TEXT = 1
class GuakeTerminal(Vte.Terminal):
"""Just a vte.Terminal with some properties already set."""
def __init__(self, guake):
super().__init__()
self.guake = guake
self.configure_terminal()
if self.guake.settings.general.get_boolean("quick-open-enable"):
self.add_matches()
self.handler_ids = []
self.handler_ids.append(self.connect("button-press-event", self.button_press))
self.connect("child-exited", self.on_child_exited) # Call on_child_exited, don't remove it
self.connect("selection-changed", self.copy_on_select)
self.matched_value = ""
self.font_scale_index = 0
self._pid = None
self.found_link = None
self.uuid = uuid.uuid4()
# Custom colors
self.custom_bgcolor = None
self.custom_fgcolor = None
self.custom_palette = None
self.setup_drag_and_drop()
self.ENVV_EXCLUDE_LIST = ["GDK_BACKEND"]
self.envv = [f"{i}={os.environ[i]}" for i in os.environ if i not in self.ENVV_EXCLUDE_LIST]
self.envv.append(f"GUAKE_TAB_UUID={self.uuid}")
def setup_drag_and_drop(self):
self.targets = Gtk.TargetList()
self.targets.add_uri_targets(DropTargets.URIS)
self.targets.add_text_targets(DropTargets.TEXT)
self.drag_dest_set(Gtk.DestDefaults.ALL, [], Gdk.DragAction.COPY)
self.drag_dest_set_target_list(self.targets)
self.connect("drag-data-received", self.on_drag_data_received)
def get_uuid(self):
return self.uuid
@property
def pid(self):
return self._pid
@pid.setter
def pid(self, pid):
self._pid = pid
def feed_child(self, resolved_cmdline):
if (Vte.MAJOR_VERSION, Vte.MINOR_VERSION) >= (0, 42):
encoded = resolved_cmdline.encode("utf-8")
try:
super().feed_child_binary(encoded)
except TypeError:
# The doc doest not say clearly at which version the feed_child* function has lost
# the "len" parameter :(
super().feed_child(resolved_cmdline, len(resolved_cmdline))
else:
super().feed_child(resolved_cmdline, len(resolved_cmdline))
def execute_command(self, command):
if command[-1] != "\n":
command += "\n"
self.feed_child(command)
def copy_clipboard(self):
if self.get_has_selection():
super().copy_clipboard()
elif self.matched_value:
guake_clipboard = Gtk.Clipboard.get_default(self.guake.window.get_display())
guake_clipboard.set_text(self.matched_value, len(self.matched_value))
def copy_on_select(self, event):
if self.guake.settings.general.get_boolean("copy-on-select") and self.get_has_selection():
self.copy_clipboard()
def configure_terminal(self):
"""Sets all customized properties on the terminal"""
client = self.guake.settings.general
word_chars = client.get_string("word-chars")
if word_chars:
self.set_word_char_exceptions(word_chars)
self.set_audible_bell(client.get_boolean("use-audible-bell"))
self.set_sensitive(True)
cursor_blink_mode = self.guake.settings.style.get_int("cursor-blink-mode")
self.set_property("cursor-blink-mode", cursor_blink_mode)
if (Vte.MAJOR_VERSION, Vte.MINOR_VERSION) >= (0, 50):
self.set_allow_hyperlink(True)
if (Vte.MAJOR_VERSION, Vte.MINOR_VERSION) >= (0, 52):
try:
self.set_cell_height_scale(
self.guake.settings.styleFont.get_double("cell-height-scale")
)
except: # pylint: disable=bare-except
log.error("set_cell_height_scale not supported by your version of VTE")
try:
self.set_cell_width_scale(
self.guake.settings.styleFont.get_double("cell-width-scale")
)
except: # pylint: disable=bare-except
log.error("set_cell_width_scale not supported by your version of VTE")
if (Vte.MAJOR_VERSION, Vte.MINOR_VERSION) >= (0, 56):
try:
self.set_bold_is_bright(self.guake.settings.styleFont.get_boolean("bold-is-bright"))
except: # pylint: disable=bare-except
log.error("set_bold_is_bright not supported by your version of VTE")
# TODO PORT is this still the case with the newer vte version?
# -- Ubuntu has a patch to libvte which disables mouse scrolling in apps
# -- like vim and less by default. If this is the case, enable it back.
if hasattr(self, "set_alternate_screen_scroll"):
self.set_alternate_screen_scroll(True)
self.set_can_default(True)
self.set_can_focus(True)
def add_matches(self):
"""Adds all regular expressions declared in
guake.globals.TERMINAL_MATCH_EXPRS to the terminal to make vte
highlight text that matches them.
"""
try:
# NOTE: PCRE2_UTF | PCRE2_NO_UTF_CHECK | PCRE2_MULTILINE
# reference from vte/bindings/vala/app.vala, flags = 0x40080400u
# also ref: https://mail.gnome.org/archives/commits-list/2016-September/msg06218.html
VTE_REGEX_FLAGS = 0x40080400
for expr in TERMINAL_MATCH_EXPRS:
tag = self.match_add_regex(
Vte.Regex.new_for_match(expr, len(expr), VTE_REGEX_FLAGS), 0
)
self.match_set_cursor_name(tag, "hand")
for _useless, match, _otheruseless in QUICK_OPEN_MATCHERS:
tag = self.match_add_regex(
Vte.Regex.new_for_match(match, len(match), VTE_REGEX_FLAGS), 0
)
self.match_set_cursor_name(tag, "hand")
except (
GLib.Error,
AttributeError,
): # pylint: disable=catching-non-exception
try:
compile_flag = 0
if (Vte.MAJOR_VERSION, Vte.MINOR_VERSION) >= (0, 44):
compile_flag = GLib.RegexCompileFlags.MULTILINE
for expr in TERMINAL_MATCH_EXPRS:
tag = self.match_add_gregex(GLib.Regex.new(expr, compile_flag, 0), 0)
self.match_set_cursor_type(tag, Gdk.CursorType.HAND2)
for _useless, match, _otheruseless in QUICK_OPEN_MATCHERS:
tag = self.match_add_gregex(GLib.Regex.new(match, compile_flag, 0), 0)
self.match_set_cursor_type(tag, Gdk.CursorType.HAND2)
except GLib.Error as err: # pylint: disable=catching-non-exception
log.error(
"ERROR: PCRE2 does not seems to be enabled on your system. "
"Quick Edit and other Ctrl+click features are disabled. "
"Please update your VTE package or contact your distribution to ask "
"to enable regular expression support in VTE. Exception: '%s'",
str(err),
)
def get_current_directory(self):
directory = os.path.expanduser("~")
if self.pid is not None:
try:
cwd = os.readlink(f"/proc/{self.pid}/cwd")
except Exception:
return directory
if os.path.exists(cwd):
directory = cwd
return directory
def is_file_on_local_server(self, text) -> Tuple[Optional[Path], Optional[int], Optional[int]]:
"""Test if the provided text matches a file on local server
Supports:
- absolute path
- relative path (using current working directory)
- file:line syntax
- file:line:colum syntax
Args:
text (str): candidate for file search
Returns
- Tuple(None, None, None) if the provided text does not match anything
- Tuple(file path, None, None) if only a file path is found
- Tuple(file path, linenumber, None) if line number is found
- Tuple(file path, linenumber, columnnumber) if line and column numbers are found
"""
lineno = None
colno = None
py_func = None
# "<File>:<line>:<col>"
m = re.compile(r"(.*)\:(\d+)\:(\d+)$").match(text)
if m:
text = m.group(1)
lineno = m.group(2)
colno = m.group(3)
else:
# "<File>:<line>"
m = re.compile(r"(.*)\:(\d+)$").match(text)
if m:
text = m.group(1)
lineno = m.group(2)
else:
# "<File>::<python_function>"
m = re.compile(r"^(.*)\:\:([a-zA-Z0-9\_]+)$").match(text)
if m:
text = m.group(1)
py_func = m.group(2).strip()
def find_lineno(text, pt, lineno, py_func):
if lineno:
return lineno
if not py_func:
return
with pt.open() as f:
for i, line in enumerate(f.readlines()):
if line.startswith(f"def {py_func}"):
return i + 1
break
pt = Path(text)
log.debug("checking file existance: %r", pt)
try:
if pt.exists():
lineno = find_lineno(text, pt, lineno, py_func)
log.info("File exists: %r, line=%r", pt.absolute().as_posix(), lineno)
return (pt, lineno, colno)
log.debug("No file found matching: %r", text)
cwd = self.get_current_directory()
pt = Path(cwd) / pt
log.debug("checking file existance: %r", pt)
if pt.exists():
lineno = find_lineno(text, pt, lineno, py_func)
log.info("File exists: %r, line=%r", pt.absolute().as_posix(), lineno)
return (pt, lineno, colno)
log.debug("file does not exist: %s", str(pt))
except OSError:
log.debug("not a file name: %r", text)
return (None, None, None)
def button_press(self, terminal, event):
"""Handles the button press event in the terminal widget. If
any match string is caught, another application is open to
handle the matched resource uri.
"""
self.matched_value = ""
if self.guake.settings.general.get_boolean("quick-open-enable"):
if (Vte.MAJOR_VERSION, Vte.MINOR_VERSION) >= (0, 46):
matched_string = self.match_check_event(event)
else:
matched_string = self.match_check(
int(event.x / self.get_char_width()),
int(event.y / self.get_char_height()),
)
self.found_link = None
if event.button == 1 and (event.get_state() & Gdk.ModifierType.CONTROL_MASK):
if (Vte.MAJOR_VERSION, Vte.MINOR_VERSION) > (0, 50):
s = self.hyperlink_check_event(event)
else:
s = None
if s is not None:
self._on_ctrl_click_matcher((s, None))
elif self.get_has_selection():
self.quick_open()
elif matched_string and matched_string[0]:
self._on_ctrl_click_matcher(matched_string)
elif event.button == 3 and matched_string:
self.found_link = self.handleTerminalMatch(matched_string)
self.matched_value = matched_string[0]
def on_child_exited(self, target, status, *user_data):
if None not in (libutempter, self.get_pty()):
libutempter.utempter_remove_record(self.get_pty().get_fd())
def on_drag_data_received(self, widget, drag_context, x, y, data, info, time):
if info == DropTargets.URIS:
uris = data.get_uris()
for uri in uris:
path = Path(unquote(urlparse(uri).path))
self.feed_child(shlex.quote(str(path.absolute())) + " ")
elif info == DropTargets.TEXT:
text = data.get_text()
if text:
self.feed_child(text)
def quick_open(self):
self.copy_clipboard()
clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
text = clipboard.wait_for_text()
if not text:
return
(fp, lo, co) = self.is_file_on_local_server(text)
self._execute_quick_open(fp, lo)
def _on_ctrl_click_matcher(self, matched_string):
value, tag = matched_string
found_matcher = False
log.debug("matched string: %s", matched_string)
# First searching in additional matchers
use_quick_open = self.guake.settings.general.get_boolean("quick-open-enable")
if use_quick_open:
found_matcher = self._find_quick_matcher(value)
if not found_matcher:
self.found_link = self.handleTerminalMatch(matched_string)
if self.found_link:
self.browse_link_under_cursor()
def _find_quick_matcher(self, value):
for _useless, _otheruseless, extractor in QUICK_OPEN_MATCHERS:
g = re.compile(extractor).match(value)
if g and g.groups():
filename = g.group(1).strip()
if len(g.groups()) >= 2:
line_number = g.group(2)
else:
line_number = None
log.info("Quick action executed filename=%s, line=%s", filename, line_number)
(filepath, ln, _) = self.is_file_on_local_server(filename)
if ln:
line_number = ln
if not filepath:
continue
if line_number is None:
line_number = "1"
self._execute_quick_open(filepath, line_number)
return True
return False
def _execute_quick_open(self, filepath, line_number):
if not filepath:
return
cmdline = self.guake.settings.general.get_string("quick-open-command-line")
if not line_number:
line_number = ""
else:
line_number = str(line_number)
logging.debug("Opening file %s at line %s", filepath, line_number)
resolved_cmdline = cmdline % {"file_path": filepath, "line_number": line_number}
logging.debug("Command line: %s", resolved_cmdline)
quick_open_in_current_terminal = self.guake.settings.general.get_boolean(
"quick-open-in-current-terminal"
)
if quick_open_in_current_terminal:
logging.debug("Executing it in current tab")
if resolved_cmdline[-1] != "\n":
resolved_cmdline += "\n"
self.feed_child(resolved_cmdline)
else:
resolved_cmdline += " &"
logging.debug("Executing it independently")
subprocess.call(resolved_cmdline, shell=True)
def handleTerminalMatch(self, matched_string):
value, tag = matched_string
log.debug("found tag: %r, item: %r", tag, value)
if tag in TERMINAL_MATCH_TAGS:
if TERMINAL_MATCH_TAGS[tag] == "schema":
# value here should not be changed, it is right and
# ready to be used.
pass
elif TERMINAL_MATCH_TAGS[tag] == "http":
value = f"http://{value}"
elif TERMINAL_MATCH_TAGS[tag] == "https":
value = f"https://{value}"
elif TERMINAL_MATCH_TAGS[tag] == "ftp":
value = f"ftp://{value}"
elif TERMINAL_MATCH_TAGS[tag] == "email":
value = f"mailto:{value}"
if value:
return value
def get_link_under_terminal_cursor(self):
cursor_position = self.get_cursor_position()
matched_string = self.match_check(cursor_position.column, cursor_position.row)
link = self.handleTerminalMatch(matched_string)
if link:
return link
def get_link_under_cursor(self):
return self.found_link
def browse_link_under_cursor(self, url=None):
# TODO move the call to xdg-open to guake.utils
if not self.found_link and url is None:
return
url = url if url is not None else self.found_link
log.debug("Opening link: %s", url)
cmd = ["xdg-open", url]
with subprocess.Popen(cmd, shell=False):
pass
def set_font(self, font):
self.font = font
self.set_font_scale_index(self.font_scale)
def set_font_scale_index(self, scale_index):
self.font_scale_index = clamp(scale_index, -6, 12)
font = Pango.FontDescription(self.font.to_string())
scale_factor = 2 ** (self.font_scale_index / 6)
new_size = int(scale_factor * font.get_size())
if font.get_size_is_absolute():
font.set_absolute_size(new_size)
else:
font.set_size(new_size)
super().set_font(font)
font_scale = property(fset=set_font_scale_index, fget=lambda self: self.font_scale_index)
def increase_font_size(self):
self.font_scale += 1
def decrease_font_size(self):
self.font_scale -= 1
def kill(self):
pid = self.pid
threading.Thread(target=self.delete_shell, args=(pid,)).start()
def delete_shell(self, pid):
"""Kill the shell with SIGHUP
NOTE: Leave it alone, DO NOT USE os.waitpid
> sys:1: Warning: GChildWatchSource: Exit status of a child process was requested but
ECHILD was received by waitpid(). See the documentation of
g_child_watch_source_new() for possible causes.
g_child_watch_source_new() documentation:
https://developer.gnome.org/glib/stable/glib-The-Main-Event-Loop.html#g-child-watch-source-new
On POSIX platforms, the following restrictions apply to this API due to limitations
in POSIX process interfaces:
...
* the application must not wait for pid to exit by any other mechanism,
including waitpid(pid, ...) or a second child-watch source for the same pid
...
For this reason, we should not call os.waitpid(pid, ...), leave it to OS
"""
try:
os.kill(pid, signal.SIGHUP)
except OSError:
pass
def spawn_sync_pid(self, directory):
argv = []
user_shell = self.guake.settings.general.get_string("default-shell")
if user_shell and os.path.exists(user_shell):
argv.append(user_shell)
else:
try:
argv.append(os.environ["SHELL"])
except KeyError:
argv.append("/usr/bin/bash")
login_shell = self.guake.settings.general.get_boolean("use-login-shell")
if login_shell:
argv.append("--login")
log.debug('Spawn command: "%s"', " ".join(argv))
pid = self.spawn_sync(
Vte.PtyFlags.DEFAULT,
directory,
argv,
self.envv,
GLib.SpawnFlags(Vte.SPAWN_NO_PARENT_ENVV),
None,
None,
None,
)
try:
tuple_type = gi._gi.ResultTuple # pylint: disable=c-extension-no-member
except: # pylint: disable=bare-except
tuple_type = tuple
if isinstance(pid, (tuple, tuple_type)):
# Return a tuple in 2.91
# https://lazka.github.io/pgi-docs/Vte-2.91/classes/Terminal.html#Vte.Terminal.spawn_sync
pid = pid[1]
if not isinstance(pid, int):
raise TypeError("pid must be an int")
if libutempter is not None:
libutempter.utempter_add_record(self.get_pty().get_fd(), os.uname()[1])
self.pid = pid
return pid
def set_color_foreground(self, font_color, *args, **kwargs):
real_fgcolor = self.custom_fgcolor if self.custom_fgcolor else font_color
super().set_color_foreground(real_fgcolor, *args, **kwargs)
def set_color_background(self, bgcolor, *args, **kwargs):
real_bgcolor = self.custom_bgcolor if self.custom_bgcolor else bgcolor
super().set_color_background(real_bgcolor, *args, **kwargs)
def set_color_bold(self, font_color, *args, **kwargs):
real_fgcolor = self.custom_fgcolor if self.custom_fgcolor else font_color
super().set_color_bold(real_fgcolor, *args, **kwargs)
def set_colors(self, font_color, bg_color, palette_list, *args, **kwargs):
real_bgcolor = self.custom_bgcolor if self.custom_bgcolor else bg_color
real_fgcolor = self.custom_fgcolor if self.custom_fgcolor else font_color
real_palette = self.custom_palette if self.custom_palette else palette_list
super().set_colors(real_fgcolor, real_bgcolor, real_palette, *args, **kwargs)
def set_color_foreground_custom(self, fgcolor, *args, **kwargs):
"""Sets custom foreground color for this terminal"""
print(f"set_color_foreground_custom: {self.uuid}")
self.custom_fgcolor = fgcolor
super().set_color_foreground(self.custom_fgcolor, *args, **kwargs)
def set_color_background_custom(self, bgcolor, *args, **kwargs):
"""Sets custom background color for this terminal"""
self.custom_bgcolor = bgcolor
super().set_color_background(self.custom_bgcolor, *args, **kwargs)
def reset_custom_colors(self):
self.custom_fgcolor = None
self.custom_bgcolor = None
self.custom_palette = None
@staticmethod
def _color_to_list(color):
"""This method is used for serialization."""
if color is None:
return None
return [color.red, color.green, color.blue, color.alpha]
@staticmethod
def _color_from_list(color_list):
"""This method is used for deserialization."""
return Gdk.RGBA(
red=color_list[0],
green=color_list[1],
blue=color_list[2],
alpha=color_list[3],
)
def get_custom_colors_dict(self):
"""Returns dictionary of custom colors."""
return {
"fg_color": self._color_to_list(self.custom_fgcolor),
"bg_color": self._color_to_list(self.custom_bgcolor),
"palette": [self._color_to_list(col) for col in self.custom_palette]
if self.custom_palette
else None,
}
def set_custom_colors_from_dict(self, colors_dict):
if not isinstance(colors_dict, dict):
return
bg_color = colors_dict.get("bg_color", None)
if isinstance(bg_color, list):
self.custom_bgcolor = self._color_from_list(bg_color)
else:
self.custom_bgcolor = None
fg_color = colors_dict.get("fg_color", None)
if isinstance(fg_color, list):
self.custom_fgcolor = self._color_from_list(fg_color)
else:
self.custom_fgcolor = None
palette = colors_dict.get("palette", None)
if isinstance(palette, list):
self.custom_palette = [self._color_from_list(col) for col in palette]
else:
self.custom_palette = None
| 26,119
|
Python
|
.py
| 581
| 34.402754
| 106
| 0.596045
|
Guake/guake
| 4,406
| 575
| 405
|
GPL-2.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,052
|
settings.py
|
Guake_guake/guake/settings.py
|
# -*- coding: utf-8; -*-
"""
Copyright (C) 2007-2012 Lincoln de Sousa <lincoln@minaslivre.org>
Copyright (C) 2007 Gabriel Falc√£o <gabrielteratos@gmail.com>
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
import subprocess
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gio
log = logging.getLogger(__name__)
class Settings:
def __init__(self, schema_source):
Settings.compat()
Settings.enhanceSetting()
self.guake = Gio.Settings.new_full(
Gio.SettingsSchemaSource.lookup(schema_source, "guake", False), None, None
)
self.guake.initEnhancements()
self.guake.connect("changed", self.guake.triggerOnChangedValue)
self.general = Gio.Settings.new_full(
Gio.SettingsSchemaSource.lookup(schema_source, "guake.general", False),
None,
None,
)
self.general.initEnhancements()
self.general.connect("changed", self.general.triggerOnChangedValue)
self.keybindings = Gio.Settings.new_full(
Gio.SettingsSchemaSource.lookup(schema_source, "guake.keybindings", False),
None,
None,
)
self.keybindings.initEnhancements()
self.keybindings.connect("changed", self.keybindings.triggerOnChangedValue)
self.keybindingsGlobal = Gio.Settings.new_full(
Gio.SettingsSchemaSource.lookup(schema_source, "guake.keybindings.global", False),
None,
None,
)
self.keybindingsGlobal.initEnhancements()
self.keybindingsGlobal.connect("changed", self.keybindingsGlobal.triggerOnChangedValue)
self.keybindingsLocal = Gio.Settings.new_full(
Gio.SettingsSchemaSource.lookup(schema_source, "guake.keybindings.local", False),
None,
None,
)
self.keybindingsLocal.initEnhancements()
self.keybindingsLocal.connect("changed", self.keybindingsLocal.triggerOnChangedValue)
self.styleBackground = Gio.Settings.new_full(
Gio.SettingsSchemaSource.lookup(schema_source, "guake.style.background", False),
None,
None,
)
self.styleBackground.initEnhancements()
self.styleBackground.connect("changed", self.styleBackground.triggerOnChangedValue)
self.styleFont = Gio.Settings.new_full(
Gio.SettingsSchemaSource.lookup(schema_source, "guake.style.font", False),
None,
None,
)
self.styleFont.initEnhancements()
self.styleFont.connect("changed", self.styleFont.triggerOnChangedValue)
self.style = Gio.Settings.new_full(
Gio.SettingsSchemaSource.lookup(schema_source, "guake.style", False),
None,
None,
)
self.style.initEnhancements()
self.style.connect("changed", self.style.triggerOnChangedValue)
self.hooks = Gio.Settings.new_full(
Gio.SettingsSchemaSource.lookup(schema_source, "guake.hooks", False),
None,
None,
)
self.hooks.initEnhancements()
self.hooks.connect("changed", self.hooks.triggerOnChangedValue)
def enhanceSetting():
def initEnhancements(self):
self.listeners = {}
def onChangedValue(self, key, user_func):
if key not in self.listeners:
self.listeners[key] = []
self.listeners[key].append(user_func)
def triggerOnChangedValue(self, settings, key, user_data=None):
if key in self.listeners:
for func in self.listeners[key]:
func(settings, key, user_data)
gi.repository.Gio.Settings.initEnhancements = initEnhancements
gi.repository.Gio.Settings.onChangedValue = onChangedValue
gi.repository.Gio.Settings.triggerOnChangedValue = triggerOnChangedValue
def compat():
try:
if len(subprocess.check_output(["dconf", "dump", "/org/guake/"])) == 0:
prefs = subprocess.check_output(["dconf", "dump", "/apps/guake/"])
if len(prefs) > 0:
with subprocess.Popen(
["dconf", "load", "/org/guake/"], stdin=subprocess.PIPE
) as p:
p.communicate(input=prefs)
except FileNotFoundError:
log.exception(
"""First run with newer Guake version detected.
dconf not installed, skipping preferences transfer."""
)
| 5,186
|
Python
|
.py
| 116
| 35.310345
| 95
| 0.658281
|
Guake/guake
| 4,406
| 575
| 405
|
GPL-2.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,053
|
palettes.py
|
Guake_guake/guake/palettes.py
|
# -*- coding: utf-8; -*-
"""
Copyright (C) 2007-2013 Guake authors
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
"""
# index 00: Host
# index 01: Syntax string
# index 02: Command
# index 03: Command color 2
# index 04: Path
# index 05: Syntax var
# index 06: Promp
# index 07:
# index 08:
# index 09: Command error
# index 10: Exec
# index 11:
# index 12: Folder
# index 13:
# index 14:
# index 15:
# index 16: Background Color
# index 17: Foreground Color
PALETTES = {
"3024 Day": (
"#090903030000:#DBDB2D2D2020:#0101A2A25252:#FDFDEDED0202:#0101A0A0E4E4:"
"#A1A16A6A9494:#B5B5E4E4F4F4:#A5A5A2A2A2A2:#5C5C58585555:#E8E8BBBBD0D0:"
"#3A3A34343232:#4A4A45454343:#80807D7D7C7C:#D6D6D5D5D4D4:#CDCDABAB5353:"
"#F7F7F7F7F7F7:#4A4A45454343:#F7F7F7F7F7F7"
),
"3024 Night": (
"#090903030000:#DBDB2D2D2020:#0101A2A25252:#FDFDEDED0202:#0101A0A0E4E4:"
"#A1A16A6A9494:#B5B5E4E4F4F4:#A5A5A2A2A2A2:#5C5C58585555:#E8E8BBBBD0D0:"
"#3A3A34343232:#4A4A45454343:#80807D7D7C7C:#D6D6D5D5D4D4:#CDCDABAB5353:"
"#F7F7F7F7F7F7:#A5A5A2A2A2A2:#090903030000"
),
"Adventure Time": (
"#050504040404:#BCBC00001313:#4949B1B11717:#E6E674741D1D:#0F0F4949C6C6:"
"#666659599292:#6F6FA4A49797:#F8F8DBDBC0C0:#4E4E7B7BBFBF:#FCFC5E5E5959:"
"#9D9DFFFF6E6E:#EFEFC1C11A1A:#18189696C6C6:#9A9A59595252:#C8C8F9F9F3F3:"
"#F5F5F4F4FBFB:#F8F8DBDBC0C0:#1E1E1C1C4444"
),
"Afterglow": (
"#151515151515:#ACAC41414242:#7E7E8D8D5050:#E5E5B5B56767:#6C6C9999BABA:"
"#9E9E4E4E8585:#7D7DD5D5CFCF:#D0D0D0D0D0D0:#505050505050:#ACAC41414242:"
"#7E7E8D8D5050:#E5E5B5B56666:#6C6C9999BBBB:#9E9E4E4E8585:#7D7DD5D5CFCF:"
"#F5F5F5F5F5F5:#D0D0D0D0D0D0:#202020202020"
),
"Alien Blood": (
"#111126261515:#7F7F2B2B2626:#2F2F7E7E2525:#70707F7F2323:#2F2F69697F7F:"
"#474757577E7E:#31317F7F7676:#64647D7D7575:#3C3C47471111:#DFDF80800808:"
"#1818E0E00000:#BDBDE0E00000:#0000A9A9DFDF:#00005858DFDF:#0000DFDFC3C3:"
"#7373F9F99090:#63637D7D7575:#0F0F16160F0F"
),
"Argonaut": (
"#222222222222:#FFFF00000F0F:#8C8CE0E00A0A:#FFFFB9B90000:#00008D8DF8F8:"
"#6C6C4343A5A5:#0000D7D7EBEB:#FFFFFFFFFFFF:#444444444444:#FFFF27273F3F:"
"#ABABE0E05A5A:#FFFFD1D14141:#00009292FFFF:#9A9A5F5FEBEB:#6767FFFFEFEF:"
"#FFFFFFFFFFFF:#FFFFFAFAF3F3:#0D0D0F0F1818"
),
"Arthur": (
"#3D3D35352A2A:#CDCD5C5C5C5C:#8686AFAF8080:#E8E8AEAE5B5B:#64649595EDED:"
"#DEDEB8B88787:#B0B0C4C4DEDE:#BBBBAAAA9999:#555544444444:#CCCC55553333:"
"#8888AAAA2222:#FFFFA7A75D5D:#8787CECEEBEB:#999966660000:#B0B0C4C4DEDE:"
"#DDDDCCCCBBBB:#DDDDEEEEDDDD:#1C1C1C1C1C1C"
),
"Atom": (
"#000000000000:#FCFC5E5EF0F0:#8787C3C38A8A:#FFFFD7D7B1B1:#8585BEBEFDFD:"
"#B9B9B5B5FCFC:#8585BEBEFDFD:#DFDFDFDFDFDF:#000000000000:#FCFC5E5EF0F0:"
"#9494F9F93636:#F5F5FFFFA7A7:#9696CBCBFEFE:#B9B9B5B5FCFC:#8585BEBEFDFD:"
"#DFDFDFDFDFDF:#C5C5C8C8C6C6:#161617171818"
),
"Belafonte Day": (
"#202011111B1B:#BEBE10100E0E:#858581816262:#EAEAA5A54949:#42426A6A7979:"
"#979752522C2C:#98989A9A9C9C:#96968C8C8383:#5E5E52525252:#BEBE10100E0E:"
"#858581816262:#EAEAA5A54949:#42426A6A7979:#979752522C2C:#98989A9A9C9C:"
"#D5D5CCCCBABA:#454537373C3C:#D5D5CCCCBABA"
),
"Belafonte Night": (
"#202011111B1B:#BEBE10100E0E:#858581816262:#EAEAA5A54949:#42426A6A7979:"
"#979752522C2C:#98989A9A9C9C:#96968C8C8383:#5E5E52525252:#BEBE10100E0E:"
"#858581816262:#EAEAA5A54949:#42426A6A7979:#979752522C2C:#98989A9A9C9C:"
"#D5D5CCCCBABA:#96968C8C8383:#202011111B1B"
),
"Birdsofparadise": (
"#57573D3D2525:#BEBE2D2D2626:#6B6BA0A08A8A:#E9E99C9C2929:#5A5A8686ACAC:"
"#ABAB8080A6A6:#7474A5A5ACAC:#DFDFDADAB7B7:#9A9A6B6B4949:#E8E845452626:"
"#9494D7D7BABA:#D0D0D0D04F4F:#B8B8D3D3EDED:#D0D09D9DCACA:#9292CECED6D6:"
"#FFFFF9F9D4D4:#DFDFDADAB7B7:#2A2A1E1E1D1D"
),
"Blazer": (
"#000000000000:#B8B87A7A7A7A:#7A7AB8B87A7A:#B8B8B8B87A7A:#7A7A7A7AB8B8:"
"#B8B87A7AB8B8:#7A7AB8B8B8B8:#D9D9D9D9D9D9:#262626262626:#DBDBBDBDBDBD:"
"#BDBDDBDBBDBD:#DBDBDBDBBDBD:#BDBDBDBDDBDB:#DBDBBDBDDBDB:#BDBDDBDBDBDB:"
"#FFFFFFFFFFFF:#D9D9E6E6F2F2:#0D0D19192626"
),
"Bluloco": (
"#505050505050:#FFFF2E2E3F3F:#6F6FD6D65D5D:#FFFF6F6F2323:#34347676FFFF:"
"#98986161F8F8:#0000CDCDB3B3:#FFFFFCFCC2C2:#7C7C7C7C7C7C:#FFFF64648080:"
"#3F3FC5C56B6B:#F9F9C8C85959:#0000B1B1FEFE:#B6B68D8DFFFF:#B3B38B8B7D7D:"
"#FFFFFEFEE3E3:#DEDEE0E0DFDF:#262626262626"
),
"Borland": (
"#4E4E4E4E4E4E:#FFFF6B6B6060:#A7A7FFFF6060:#FFFFFFFFB6B6:#9696CACAFDFD:"
"#FFFF7373FDFD:#C6C6C4C4FDFD:#EEEEEEEEEEEE:#7C7C7C7C7C7C:#FFFFB6B6B0B0:"
"#CECEFFFFABAB:#FFFFFFFFCBCB:#B5B5DCDCFEFE:#FFFF9C9CFEFE:#DFDFDFDFFEFE:"
"#FFFFFFFFFFFF:#FFFFFFFF4E4E:#00000000A4A4"
),
"Broadcast": (
"#000000000000:#DADA49493939:#51519F9F5050:#FFFFD2D24A4A:#6D6D9C9CBEBE:"
"#D0D0D0D0FFFF:#6E6E9C9CBEBE:#FFFFFFFFFFFF:#323232323232:#FFFF7B7B6B6B:"
"#8383D1D18282:#FFFFFFFF7C7C:#9F9FCECEF0F0:#FFFFFFFFFFFF:#A0A0CECEF0F0:"
"#FFFFFFFFFFFF:#E6E6E1E1DCDC:#2B2B2B2B2B2B"
),
"Brogrammer": (
"#1F1F1F1F1F1F:#F7F711111818:#2C2CC5C55D5D:#ECECB9B90F0F:#2A2A8484D2D2:"
"#4E4E5959B7B7:#0F0F8080D5D5:#D6D6DADAE4E4:#D6D6DADAE4E4:#DEDE34342E2E:"
"#1D1DD2D26060:#F2F2BDBD0909:#0F0F8080D5D5:#52524F4FB9B9:#0F0F7C7CDADA:"
"#FFFFFFFFFFFF:#D6D6DADAE4E4:#131313131313"
),
"C64": (
"#090903030000:#888839393232:#5555A0A04949:#BFBFCECE7272:#404031318D8D:"
"#8B8B3F3F9696:#6767B6B6BDBD:#FFFFFFFFFFFF:#000000000000:#888839393232:"
"#5555A0A04949:#BFBFCECE7272:#404031318D8D:#8B8B3F3F9696:#6767B6B6BDBD:"
"#F7F7F7F7F7F7:#78786969C4C4:#404031318D8D"
),
"Chalk": (
"#7C7C8A8A8F8F:#B2B23A3A5151:#78789A9A6969:#B9B9ABAB4A4A:#2A2A7F7FACAC:"
"#BCBC4F4F5A5A:#4444A7A79999:#D2D2D8D8D9D9:#888888888888:#F2F248484040:"
"#8080C4C46F6F:#FFFFEBEB6262:#40409595FFFF:#FBFB51517575:#5252CCCCBDBD:"
"#D2D2D8D8D9D9:#D2D2D8D8D9D9:#2B2B2C2C2E2E"
),
"Chalkboard": (
"#000000000000:#C3C373737272:#7272C3C37373:#C2C2C3C37272:#73737272C3C3:"
"#C3C37272C2C2:#7272C2C2C3C3:#D9D9D9D9D9D9:#323232323232:#DBDBAAAAAAAA:"
"#AAAADBDBAAAA:#DADADBDBAAAA:#AAAAAAAADBDB:#DBDBAAAADADA:#AAAADADADBDB:"
"#FFFFFFFFFFFF:#D9D9E6E6F2F2:#292926262F2F"
),
"Ciapre": (
"#181818181818:#808000000909:#484851513B3B:#CCCC8A8A3E3E:#56566D6D8C8C:"
"#72724C4C7C7C:#5B5B4F4F4A4A:#ADADA3A37E7E:#555555555555:#ABAB38383434:"
"#A6A6A6A65D5D:#DCDCDEDE7B7B:#2F2F9797C6C6:#D3D330306060:#F3F3DADAB1B1:"
"#F3F3F3F3F3F3:#ADADA3A37A7A:#18181C1C2727"
),
"Clrs": (
"#000000000000:#F7F727272929:#323289895C5C:#F9F96F6F1C1C:#12125C5CCFCF:"
"#9F9F0000BCBC:#3232C2C2C0C0:#B2B2B2B2B2B2:#545457575353:#FBFB04041616:"
"#2C2CC6C63131:#FCFCD6D62727:#15156F6FFEFE:#E8E80000B0B0:#3939D5D5CECE:"
"#EDEDEDEDECEC:#262626262626:#FFFFFFFFFFFF"
),
"Cobalt Neon": (
"#141426263030:#FFFF23232020:#3A3AA5A5FFFF:#E9E9E7E75C5C:#8F8FF5F58686:"
"#78781A1AA0A0:#8F8FF5F58686:#BABA4545B1B1:#FFFFF6F68888:#D4D431312E2E:"
"#8F8FF5F58686:#E9E9F0F06D6D:#3C3C7D7DD2D2:#82823030A7A7:#6C6CBCBC6767:"
"#8F8FF5F58686:#8F8FF5F58686:#141428283838"
),
"Cobalt2": (
"#000000000000:#FFFF00000000:#3737DDDD2121:#FEFEE4E40909:#14146060D2D2:"
"#FFFF00005D5D:#0000BBBBBBBB:#BBBBBBBBBBBB:#555555555555:#F4F40D0D1717:"
"#3B3BCFCF1D1D:#ECECC8C80909:#55555555FFFF:#FFFF5555FFFF:#6A6AE3E3F9F9:"
"#FFFFFFFFFFFF:#FFFFFFFFFFFF:#121226263737"
),
"Crayon Pony Fish": (
"#2A2A1A1A1C1C:#909000002A2A:#575795952323:#AAAA30301B1B:#8B8B8787AFAF:"
"#68682E2E5050:#E8E8A7A76666:#686852525959:#3C3C2A2A2E2E:#C5C524245C5C:"
"#8D8DFFFF5656:#C7C737371D1D:#CFCFC9C9FFFF:#FBFB6C6CB9B9:#FFFFCECEAEAE:"
"#AFAF94949D9D:#686852525959:#141406060707"
),
"Dark Pastel": (
"#000000000000:#FFFF55555555:#5555FFFF5555:#FFFFFFFF5555:#55555555FFFF:"
"#FFFF5555FFFF:#5555FFFFFFFF:#BBBBBBBBBBBB:#555555555555:#FFFF55555555:"
"#5555FFFF5555:#FFFFFFFF5555:#55555555FFFF:#FFFF5555FFFF:#5555FFFFFFFF:"
"#FFFFFFFFFFFF:#FFFFFFFFFFFF:#000000000000"
),
"Darkside": (
"#000000000000:#E8E834341C1C:#6868C2C25656:#F2F2D3D32C2C:#1C1C9898E8E8:"
"#8E8E6969C9C9:#1C1C9898E8E8:#BABABABABABA:#000000000000:#DFDF5A5A4F4F:"
"#7676B7B76868:#EEEED6D64A4A:#38387B7BD2D2:#95957B7BBDBD:#3D3D9696E2E2:"
"#BABABABABABA:#BABABABABABA:#222223232424"
),
"Desert": (
"#4D4D4D4D4D4D:#FFFF2B2B2B2B:#9898FBFB9898:#F0F0E6E68C8C:#CDCD85853F3F:"
"#FFFFDEDEADAD:#FFFFA0A0A0A0:#F5F5DEDEB3B3:#555555555555:#FFFF55555555:"
"#5555FFFF5555:#FFFFFFFF5555:#8787CECEFFFF:#FFFF5555FFFF:#FFFFD7D70000:"
"#FFFFFFFFFFFF:#FFFFFFFFFFFF:#333333333333"
),
"Dimmed Monokai": (
"#3A3A3C3C4343:#BEBE3E3E4848:#86869A9A3A3A:#C4C4A5A53535:#4E4E7676A1A1:"
"#85855B5B8D8D:#56568E8EA3A3:#B8B8BCBCB9B9:#888889898787:#FBFB00001E1E:"
"#0E0E71712E2E:#C3C370703333:#17176C6CE3E3:#FBFB00006767:#2D2D6F6F6C6C:"
"#FCFCFFFFB8B8:#B8B8BCBCB9B9:#1E1E1E1E1E1E"
),
"Dracula": (
"#000000000000:#FFFF55555555:#5050FAFA7B7B:#F1F1FAFA8C8C:#BDBD9393F9F9:"
"#FFFF7979C6C6:#8B8BE9E9FDFD:#BBBBBBBBBBBB:#555555555555:#FFFF55555555:"
"#5050FAFA7B7B:#F1F1FAFA8C8C:#BDBD9393F9F9:#FFFF7979C6C6:#8B8BE9E9FDFD:"
"#FFFFFFFFFFFF:#F8F8F8F8F2F2:#1E1E1F1F2828"
),
"Earthsong": (
"#111114141717:#C8C841413434:#8484C4C44B4B:#F4F4AEAE2E2E:#13139797B9B9:"
"#D0D062623C3C:#4F4F94945252:#E5E5C5C5A9A9:#66665E5E5454:#FFFF64645959:"
"#9797E0E03535:#DFDFD5D56161:#5E5ED9D9FFFF:#FFFF91916868:#8383EFEF8888:"
"#F6F6F6F6ECEC:#E5E5C6C6A8A8:#282824242020"
),
"Elemental": (
"#3C3C3B3B3030:#979728280F0F:#474799994242:#7F7F71711010:#49497F7F7D7D:"
"#7E7E4E4E2E2E:#38387F7F5858:#808079797474:#545454544444:#DFDF50502A2A:"
"#6060E0E06F6F:#D6D698982727:#7878D8D8D8D8:#CDCD7C7C5353:#5858D5D59898:"
"#FFFFF1F1E8E8:#808079797373:#212121211C1C"
),
"Elementary Loki": (
"#070736364242:#DCDC32322F2F:#858599990000:#B5B589890000:#26268B8BD2D2:"
"#ECEC00004848:#2A2AA1A19898:#9494A3A3A5A5:#58586E6E7575:#CBCB4B4B1616:"
"#858599990000:#B5B589890000:#26268B8BD2D2:#D3D336368282:#2A2AA1A19898:"
"#EEEEEEEEEEEE:#9494A3A3A5A5:#25252E2E3232"
),
"Espresso Libre": (
"#000000000000:#CCCC00000000:#1A1A92921C1C:#EFEFE4E43A3A:#00006666FFFF:"
"#C5C565656B6B:#050598989A9A:#D3D3D7D7CFCF:#545457575353:#EFEF28282828:"
"#9A9AFFFF8787:#FFFFFAFA5C5C:#4343A8A8EDED:#FFFF80808989:#3434E2E2E2E2:"
"#EDEDEDEDECEC:#B8B8A8A89898:#2A2A21211C1C"
),
"Espresso": (
"#343434343434:#D2D251515151:#A5A5C2C26161:#FFFFC6C66D6D:#6C6C9999BBBB:"
"#D1D19797D9D9:#BEBED6D6FFFF:#EEEEEEEEECEC:#535353535353:#F0F00C0C0C0C:"
"#C2C2E0E07575:#E1E1E3E38B8B:#8A8AB7B7D9D9:#EFEFB5B5F7F7:#DCDCF3F3FFFF:"
"#FFFFFFFFFFFF:#FFFFFFFFFFFF:#323232323232"
),
"Fideloper": (
"#28282F2F3232:#CACA1D1D2C2C:#EDEDB7B7ABAB:#B7B7AAAA9A9A:#2E2E7878C1C1:"
"#C0C022226E6E:#303091918585:#E9E9E2E2CDCD:#090920202727:#D3D35F5F5A5A:"
"#D3D35F5F5A5A:#A8A865657171:#7C7C8484C4C4:#5B5B5D5DB2B2:#818190908F8F:"
"#FCFCF4F4DEDE:#DADAD9D9DFDF:#28282F2F3232"
),
"Fishtank": (
"#030306063C3C:#C6C600004949:#ABABF1F15757:#FDFDCDCD5E5E:#52525F5FB8B8:"
"#97976F6F8181:#969686866262:#ECECEFEFFCFC:#6C6C5A5A3030:#D9D94A4A8A8A:"
"#DADAFFFFA8A8:#FEFEE6E6A8A8:#B1B1BDBDF9F9:#FDFDA4A4CCCC:#A4A4BCBC8686:"
"#F6F6FFFFECEC:#ECECEFEFFDFD:#222224243636"
),
"Flat": (
"#22222D2D3F3F:#A8A823232020:#3232A5A54848:#E5E58D8D1111:#31316767ACAC:"
"#78781A1AA0A0:#2C2C93937070:#B0B0B6B6BABA:#21212C2C3C3C:#D4D431312E2E:"
"#2D2D94944040:#E5E5BEBE0C0C:#3C3C7D7DD2D2:#82823030A7A7:#3535B3B38787:"
"#E7E7ECECEDED:#2C2CC5C55D5D:#000022224040"
),
"Flatland": (
"#1C1C1D1D1919:#F1F182823838:#9E9ED2D26464:#F3F3EFEF6D6D:#4F4F9696BEBE:"
"#69695A5ABBBB:#D5D538386464:#FEFEFFFFFEFE:#1C1C1D1D1919:#D1D12A2A2424:"
"#A7A7D3D32C2C:#FFFF89894848:#6161B8B8D0D0:#69695A5ABBBB:#D5D538386464:"
"#FEFEFFFFFEFE:#B8B8DADAEEEE:#1C1C1E1E2020"
),
"Frontend Delight": (
"#242424242626:#F8F850501A1A:#565657574646:#F9F976761D1D:#2C2C7070B7B7:"
"#F0F02D2D4E4E:#3B3BA0A0A5A5:#ACACACACACAC:#5E5EACAC6C6C:#F6F643431919:"
"#7474EBEB4C4C:#FCFCC2C22424:#33339393C9C9:#E7E75E5E4E4E:#4E4EBCBCE5E5:"
"#8B8B73735A5A:#ACACACACACAC:#1B1B1B1B1D1D"
),
"Frontend Fun Forrest": (
"#000000000000:#D5D525252B2B:#90909B9B0000:#BDBD8A8A1313:#46469898A2A2:"
"#8C8C42423131:#D9D981811212:#DDDDC1C16565:#7E7E69695454:#E4E459591B1B:"
"#BFBFC6C65959:#FFFFCACA1B1B:#7C7CC9C9CECE:#D1D163634949:#E6E6A9A96B6B:"
"#FFFFE9E9A3A3:#DDDDC1C16565:#242412120000"
),
"Frontend Galaxy": (
"#000000000000:#F9F955555F5F:#2020AFAF8989:#FDFDF0F02929:#58589C9CF5F5:"
"#93934D4D9595:#1E1E9E9EE6E6:#BBBBBBBBBBBB:#555555555555:#FAFA8B8B8E8E:"
"#3434BBBB9999:#FFFFFFFF5555:#58589C9CF5F5:#E7E755559898:#39397878BBBB:"
"#FFFFFFFFFFFF:#FFFFFFFFFFFF:#1C1C28283636"
),
"Galizur": (
"#222233334444:#aaaa11112222:#3333aaaa1111:#ccccaaaa2222:#22225555cccc:"
"#77775555aaaa:#2222bbbbcccc:#88889999aaaa:#555566667777:#ffff11113333:"
"#3333ffff1111:#ffffdddd3333:#33337777ffff:#aaaa7777ffff:#3333ddddffff:"
"#bbbbccccdddd:#ddddeeeeffff:#070713131717"
),
"Github": (
"#3E3E3E3E3E3E:#97970B0B1616:#070796962A2A:#F8F8EEEEC7C7:#00003E3E8A8A:"
"#E9E946469191:#8989D1D1ECEC:#FFFFFFFFFFFF:#666666666666:#DEDE00000000:"
"#8787D5D5A2A2:#F1F1D0D00707:#2E2E6C6CBABA:#FFFFA2A29F9F:#1C1CFAFAFEFE:"
"#FFFFFFFFFFFF:#3E3E3E3E3E3E:#F4F4F4F4F4F4"
),
"Grape": (
"#2D2D28283E3E:#ECEC21216060:#1F1FA9A91B1B:#8D8DDCDC1F1F:#48487C7CF4F4:"
"#8C8C3535C8C8:#3A3ADDDDEDED:#9E9E9E9EA0A0:#585850506A6A:#F0F071719A9A:"
"#5252A9A95D5D:#B2B2DCDC8787:#A9A9BBBBEBEB:#ACAC8181C1C1:#9C9CE3E3EAEA:"
"#A1A18888F7F7:#9E9E9E9EA0A0:#161614142323"
),
"Grass": (
"#000000000000:#BBBB00000000:#0000BBBB0000:#E7E7B0B00000:#00000000A3A3:"
"#959500006161:#0000BBBBBBBB:#BBBBBBBBBBBB:#555555555555:#BBBB00000000:"
"#0000BBBB0000:#E7E7B0B00000:#00000000BBBB:#FFFF5555FFFF:#5555FFFFFFFF:"
"#FFFFFFFFFFFF:#FFFFF0F0A5A5:#131377773C3C"
),
"Hardcore": (
"#1B1B1D1D1E1E:#F9F926267272:#A6A6E2E22E2E:#FDFD97971F1F:#6666D9D9EFEF:"
"#9E9E6F6FFEFE:#5E5E71717575:#CCCCCCCCC6C6:#505053535454:#FFFF66669D9D:"
"#BEBEEDED5F5F:#E6E6DBDB7474:#6666D9D9EFEF:#9E9E6F6FFEFE:#A3A3BABABFBF:"
"#F8F8F8F8F2F2:#A0A0A0A0A0A0:#121212121212"
),
"Harper": (
"#010101010101:#F8F8B6B63F3F:#7F7FB5B5E1E1:#D6D6DADA2525:#48489E9E4848:"
"#B2B29696C6C6:#F5F5BFBFD7D7:#A8A8A4A49D9D:#72726E6E6A6A:#F8F8B6B63F3F:"
"#7F7FB5B5E1E1:#D6D6DADA2525:#48489E9E4848:#B2B29696C6C6:#F5F5BFBFD7D7:"
"#FEFEFBFBEAEA:#A8A8A4A49D9D:#010101010101"
),
"Highway": (
"#000000000000:#CFCF0D0D1717:#121280803333:#FFFFCACA3D3D:#00006A6AB3B3:"
"#6A6A26267474:#383845456363:#EDEDEDEDEDED:#5C5C4F4F4949:#EFEF7D7D1717:"
"#B1B1D1D13030:#FFFFF1F11F1F:#4F4FC2C2FDFD:#DEDE00007070:#5C5C4F4F4949:"
"#FEFEFFFFFEFE:#EDEDEDEDEDED:#212122222424"
),
"Hipster Green": (
"#000000000000:#B6B620204A4A:#0000A6A60000:#BEBEBEBE0000:#24246D6DB2B2:"
"#B2B20000B2B2:#0000A6A6B2B2:#BFBFBFBFBFBF:#666666666666:#E5E500000000:"
"#8686A8A83E3E:#E5E5E5E50000:#00000000FFFF:#E5E50000E5E5:#0000E5E5E5E5:"
"#E5E5E5E5E5E5:#8484C1C13737:#0F0F0A0A0505"
),
"Homebrew": (
"#000000000000:#999900000000:#0000A6A60000:#999999990000:#00000000B2B2:"
"#B2B20000B2B2:#0000A6A6B2B2:#BFBFBFBFBFBF:#666666666666:#E5E500000000:"
"#0000D9D90000:#E5E5E5E50000:#00000000FFFF:#E5E50000E5E5:#0000E5E5E5E5:"
"#E5E5E5E5E5E5:#0000FFFF0000:#000000000000"
),
"Hurtado": (
"#575757575757:#FFFF1B1B0000:#A5A5DFDF5555:#FBFBE7E74A4A:#484863638787:"
"#FCFC5E5EF0F0:#8585E9E9FEFE:#CBCBCBCBCBCB:#252525252525:#D4D41C1C0000:"
"#A5A5DFDF5555:#FBFBE7E74949:#8989BDBDFFFF:#BFBF0000C0C0:#8585E9E9FEFE:"
"#DBDBDBDBDBDB:#DADADBDBDADA:#000000000000"
),
"Hybrid": (
"#2A2A2E2E3333:#B7B74D4D5050:#B3B3BEBE5A5A:#E3E3B5B55E5E:#6D6D9090B0B0:"
"#A0A07E7EABAB:#7F7FBEBEB3B3:#B5B5B8B8B6B6:#1D1D1E1E2121:#8C8C2D2D3232:"
"#787883833131:#E5E589894F4F:#4B4B6B6B8888:#6E6E4F4F7979:#4D4D7B7B7373:"
"#5A5A61616969:#B7B7BCBCB9B9:#161617171818"
),
"Ic Green Ppl": (
"#1E1E1E1E1E1E:#FBFB00002929:#32329B9B2424:#64649A9A2525:#14149B9B4545:"
"#5353B8B82B2B:#2B2BB7B76767:#DFDFFEFEEEEE:#030326260F0F:#A6A6FFFF3E3E:"
"#9F9FFFFF6D6D:#D1D1FFFF6D6D:#7272FFFFB5B5:#5050FFFF3D3D:#2222FFFF7171:"
"#DADAEEEED0D0:#D9D9EEEED2D2:#3A3A3C3C3E3E"
),
"Ic Orange Ppl": (
"#000000000000:#C0C039390000:#A3A3A9A90000:#CACAAEAE0000:#BDBD6C6C0000:"
"#FBFB5D5D0000:#F7F794940000:#FFFFC8C88A8A:#6A6A4E4E2929:#FFFF8B8B6767:"
"#F6F6FFFF3F3F:#FFFFE3E36E6E:#FFFFBDBD5454:#FCFC87874F4F:#C5C597975252:"
"#F9F9F9F9FEFE:#FFFFCBCB8383:#262626262626"
),
"Idle Toes": (
"#323232323232:#D2D252525252:#7F7FE1E17373:#FFFFC6C66D6D:#40409898FFFF:"
"#F5F57F7FFFFF:#BEBED6D6FFFF:#EEEEEEEEECEC:#535353535353:#F0F070707070:"
"#9D9DFFFF9090:#FFFFE4E48B8B:#5E5EB7B7F7F7:#FFFF9D9DFFFF:#DCDCF4F4FFFF:"
"#FFFFFFFFFFFF:#FFFFFFFFFFFF:#323232323232"
),
"Ir Black": (
"#4F4F4F4F4F4F:#FAFA6C6C5F5F:#A8A8FEFE6060:#FFFFFEFEB6B6:#9696CACAFDFD:"
"#FAFA7272FCFC:#C6C6C4C4FDFD:#EEEEEDEDEEEE:#7B7B7B7B7B7B:#FCFCB6B6AFAF:"
"#CECEFFFFABAB:#FFFFFEFECCCC:#B5B5DCDCFEFE:#FBFB9B9BFEFE:#DFDFDFDFFDFD:"
"#FEFEFFFFFEFE:#F1F1F1F1F1F1:#000000000000"
),
"Jackie Brown": (
"#2C2C1D1D1616:#EFEF57573434:#2B2BAFAF2B2B:#BDBDBEBE0000:#24246D6DB2B2:"
"#CFCF5E5EC0C0:#0000ACACEEEE:#BFBFBFBFBFBF:#666666666666:#E5E500000000:"
"#8686A8A83E3E:#E5E5E5E50000:#00000000FFFF:#E5E50000E5E5:#0000E5E5E5E5:"
"#E5E5E5E5E5E5:#FFFFCCCC2F2F:#2C2C1C1C1515"
),
"Japanesque": (
"#343438383535:#CECE3E3E6060:#7B7BB7B75B5B:#E8E8B3B32A2A:#4C4C9999D3D3:"
"#A5A57F7FC4C4:#38389A9AACAC:#F9F9FAFAF6F6:#58585A5A5858:#D1D18E8EA6A6:"
"#76767E7E2B2B:#777759592E2E:#131358587979:#5F5F41419090:#7676BBBBCACA:"
"#B1B1B5B5AEAE:#F7F7F6F6ECEC:#1D1D1D1D1D1D"
),
"Jellybeans": (
"#929292929292:#E2E273737373:#9393B9B97979:#FFFFBABA7B7B:#9797BEBEDCDC:"
"#E1E1C0C0FAFA:#000098988E8E:#DEDEDEDEDEDE:#BDBDBDBDBDBD:#FFFFA1A1A1A1:"
"#BDBDDEDEABAB:#FFFFDCDCA0A0:#B1B1D8D8F6F6:#FBFBDADAFFFF:#1A1AB2B2A8A8:"
"#FFFFFFFFFFFF:#DEDEDEDEDEDE:#121212121212"
),
"Kibble": (
"#4D4D4D4D4D4D:#C7C700003131:#2929CFCF1313:#D8D8E3E30E0E:#34344949D1D1:"
"#84840000FFFF:#07079898ABAB:#E2E2D1D1E3E3:#5A5A5A5A5A5A:#F0F015157878:"
"#6C6CE0E05C5C:#F3F3F7F79E9E:#9797A4A4F7F7:#C4C49595F0F0:#6868F2F2E0E0:"
"#FFFFFFFFFFFF:#F7F7F7F7F7F7:#0E0E10100A0A"
),
"Later This Evening": (
"#2B2B2B2B2B2B:#D3D35A5A5F5F:#AFAFBABA6666:#E5E5D2D28989:#A0A0B9B9D5D5:"
"#BFBF9292D5D5:#9191BEBEB6B6:#3B3B3C3C3C3C:#444447474747:#D3D322222E2E:"
"#AAAABBBB3939:#E4E4BDBD3939:#65659999D5D5:#AAAA5252D5D5:#5F5FBFBFADAD:"
"#C0C0C2C2C2C2:#949494949494:#212121212121"
),
"Lavandula": (
"#232300004545:#7C7C15152525:#33337E7E6F6F:#7F7F6F6F4949:#4F4F4A4A7F7F:"
"#59593F3F7E7E:#575776767F7F:#73736E6E7D7D:#37372C2C4646:#DFDF50506666:"
"#5252E0E0C4C4:#E0E0C2C28686:#8E8E8686DFDF:#A6A67575DFDF:#9A9AD3D3DFDF:"
"#8C8C9191FAFA:#73736E6E7D7D:#050500001414"
),
"Linux Console": (
"#000000000000:#aaaa00000000:#0000aaaa0000:#aaaa55550000:#00000000aaaa:"
"#aaaa0000aaaa:#0000aaaaaaaa:#aaaaaaaaaaaa:#555555555556:#ffff55555555:"
"#5555ffff5555:#ffffffff5555:#55555555ffff:#ffff5555ffff:#5555ffffffff:"
"#ffffffffffff:#ffffffffffff:#000000000000"
),
"Liquid Carbon Transparent": (
"#000000000000:#FFFF2F2F2F2F:#54549A9A6F6F:#CCCCACAC0000:#00009999CCCC:"
"#CCCC6868C8C8:#7979C4C4CCCC:#BCBCCCCCCCCC:#000000000000:#FFFF2F2F2F2F:"
"#54549A9A6F6F:#CCCCACAC0000:#00009999CCCC:#CCCC6868C8C8:#7979C4C4CCCC:"
"#BCBCCCCCCCCC:#AFAFC2C2C2C2:#000000000000"
),
"Liquid Carbon": (
"#000000000000:#FFFF2F2F2F2F:#54549A9A6F6F:#CCCCACAC0000:#00009999CCCC:"
"#CCCC6868C8C8:#7979C4C4CCCC:#BCBCCCCCCCCC:#000000000000:#FFFF2F2F2F2F:"
"#54549A9A6F6F:#CCCCACAC0000:#00009999CCCC:#CCCC6868C8C8:#7979C4C4CCCC:"
"#BCBCCCCCCCCC:#AFAFC2C2C2C2:#2F2F2F2F2F2F"
),
"Lucario": (
"#4E4E4E4E4E4E:#FFFF6B6B6060:#FAFAB0B03636:#FFFFFFFFB6B6:#56569696EDED:"
"#FFFF7373FDFD:#8E8EE4E47878:#EEEEEEEEEEEE:#4F4F4F4F4F4F:#F9F968686060:"
"#FAFAB0B03636:#FDFDFFFFB8B8:#6B6B9F9FEDED:#FCFC6E6EF9F9:#8E8EE4E47878:"
"#FFFFFFFFFFFF:#F8F8F8F8F2F2:#2B2B3E3E5050"
),
"Man Page": (
"#000000000000:#CCCC00000000:#0000A6A60000:#999999990000:#00000000B2B2:"
"#B2B20000B2B2:#0000A6A6B2B2:#CCCCCCCCCCCC:#666666666666:#E5E500000000:"
"#0000D9D90000:#E5E5E5E50000:#00000000FFFF:#E5E50000E5E5:#0000E5E5E5E5:"
"#E5E5E5E5E5E5:#000000000000:#FEFEF4F49C9C"
),
"Mathias": (
"#000000000000:#E5E522222222:#A6A6E3E32D2D:#FCFC95951E1E:#C4C48D8DFFFF:"
"#FAFA25257373:#6767D9D9F0F0:#F2F2F2F2F2F2:#555555555555:#FFFF55555555:"
"#5555FFFF5555:#FFFFFFFF5555:#55555555FFFF:#FFFF5555FFFF:#5555FFFFFFFF:"
"#FFFFFFFFFFFF:#BBBBBBBBBBBB:#000000000000"
),
"Medallion": (
"#000000000000:#B5B54C4C0000:#7C7C8A8A1616:#D2D2BDBD2525:#60606B6BAFAF:"
"#8B8B59599090:#90906B6B2525:#C9C9C1C19999:#5E5E51511818:#FFFF91914848:"
"#B1B1C9C93A3A:#FFFFE4E44949:#ABABB8B8FFFF:#FEFE9F9FFFFF:#FFFFBBBB5151:"
"#FEFED5D59797:#CACAC2C29696:#1D1D18180808"
),
"Misterioso": (
"#000000000000:#FFFF42424242:#7474AFAF6868:#FFFFADAD2929:#33338F8F8686:"
"#94941313E5E5:#2323D7D7D7D7:#E1E1E1E1E0E0:#555555555555:#FFFF32324242:"
"#7474CDCD6868:#FFFFB9B92929:#2323D7D7D7D7:#FFFF3737FFFF:#0000EDEDE1E1:"
"#FFFFFFFFFFFF:#E1E1E1E1E0E0:#2D2D37374343"
),
"Molokai": (
"#121212121212:#FAFA25257373:#9797E1E12323:#DFDFD4D46060:#0F0F7F7FCFCF:"
"#87870000FFFF:#4242A7A7CFCF:#BBBBBBBBBBBB:#555555555555:#F5F566669C9C:"
"#B0B0E0E05E5E:#FEFEF2F26C6C:#0000AFAFFFFF:#AFAF8787FFFF:#5050CDCDFEFE:"
"#FFFFFFFFFFFF:#BBBBBBBBBBBB:#121212121212"
),
"Mona Lisa": (
"#34341A1A0D0D:#9B9B28281B1B:#626261613232:#C2C26E6E2727:#51515B5B5C5C:"
"#9B9B1D1D2929:#585880805656:#F6F6D7D75C5C:#878742422727:#FFFF42423030:"
"#B3B3B1B16363:#FFFF95956565:#9E9EB2B2B3B3:#FFFF5B5B6A6A:#8989CCCC8E8E:"
"#FFFFE5E59797:#F6F6D5D56A6A:#11110B0B0D0D"
),
"Monokai Cobalt2": (
"#1C1C1D1D1919:#D0D01B1B2424:#A7A7D3D32C2C:#D8D8CFCF6767:#6161B8B8D0D0:"
"#69695A5ABBBB:#D5D538386464:#FEFEFFFFFEFE:#1C1C1D1D1919:#D0D01B1B2424:"
"#A7A7D3D32C2C:#D8D8CFCF6767:#6161B8B8D0D0:#69695A5ABBBB:#D5D538386464:"
"#FEFEFFFFFEFE:#FFFFFFFFFFFF:#121226263737"
),
"Monokai Soda": (
"#191919191919:#F3F300005F5F:#9797E0E02323:#FAFA84841919:#9C9C6464FEFE:"
"#F3F300005F5F:#5757D1D1EAEA:#C4C4C4C4B5B5:#61615E5E4B4B:#F3F300005F5F:"
"#9797E0E02323:#DFDFD5D56161:#9C9C6464FEFE:#F3F300005F5F:#5757D1D1EAEA:"
"#F6F6F6F6EEEE:#C4C4C4C4B5B5:#191919191919"
),
"Monokai": (
"#1C1C1D1D1919:#D0D01B1B2424:#A7A7D3D32C2C:#D8D8CFCF6767:#6161B8B8D0D0:"
"#69695A5ABBBB:#D5D538386464:#FEFEFFFFFEFE:#1C1C1D1D1919:#D0D01B1B2424:"
"#A7A7D3D32C2C:#D8D8CFCF6767:#6161B8B8D0D0:#69695A5ABBBB:#D5D538386464:"
"#FEFEFFFFFEFE:#F6F6F5F5EEEE:#232325252626"
),
"N0tch2k": (
"#383838383838:#A9A955555151:#666666666666:#A9A980805151:#65657D7D3E3E:"
"#767676767676:#C9C9C9C9C9C9:#D0D0B8B8A3A3:#474747474747:#A9A977777575:"
"#8C8C8C8C8C8C:#A9A991917575:#9898BDBD5E5E:#A3A3A3A3A3A3:#DCDCDCDCDCDC:"
"#D8D8C8C8BBBB:#A0A0A0A0A0A0:#222222222222"
),
"Neopolitan": (
"#000000000000:#808000000000:#6161CECE3C3C:#FBFBDEDE2D2D:#25253B3B7676:"
"#FFFF00008080:#8D8DA6A6CECE:#F8F8F8F8F8F8:#000000000000:#808000000000:"
"#6161CECE3C3C:#FBFBDEDE2D2D:#25253B3B7676:#FFFF00008080:#8D8DA6A6CECE:"
"#F8F8F8F8F8F8:#FFFFFFFFFFFF:#27271F1F1919"
),
"Neutron": (
"#222225252B2B:#B5B53F3F3636:#5A5AB9B97777:#DDDDB5B56666:#6A6A7B7B9292:"
"#A3A379799D9D:#3F3F9393A8A8:#E6E6E8E8EEEE:#222225252B2B:#B5B53F3F3636:"
"#5A5AB9B97777:#DDDDB5B56666:#6A6A7B7B9292:#A3A379799D9D:#3F3F9393A8A8:"
"#EBEBEDEDF2F2:#E6E6E8E8EEEE:#1B1B1D1D2222"
),
"Nightlion V1": (
"#4C4C4C4C4C4C:#BBBB00000000:#5E5EDEDE8F8F:#F2F2F0F06767:#26266A6AD7D7:"
"#BBBB0000BBBB:#0000D9D9DFDF:#BBBBBBBBBBBB:#555555555555:#FFFF55555555:"
"#5555FFFF5555:#FFFFFFFF5555:#55555555FFFF:#FFFF5555FFFF:#5555FFFFFFFF:"
"#FFFFFFFFFFFF:#BBBBBBBBBBBB:#000000000000"
),
"Nightlion V2": (
"#4C4C4C4C4C4C:#BBBB00000000:#0303F6F62222:#F2F2F0F06767:#6363D0D0F0F0:"
"#CECE6F6FDADA:#0000D9D9DFDF:#BBBBBBBBBBBB:#555555555555:#FFFF55555555:"
"#7D7DF6F61C1C:#FFFFFFFF5555:#6262CACAE7E7:#FFFF9A9AF5F5:#0000CCCCD7D7:"
"#FFFFFFFFFFFF:#BBBBBBBBBBBB:#171717171717"
),
"Nord": (
"#3B3B42425252:#BFBF61616A6A:#A3A3BEBE8C8C:#EBEBCBCB8B8B:#8181A1A1C1C1:"
"#B4B48E8EADAD:#8888C0C0D0D0:#E5E5E9E9F0F0:#4C4C56566A6A:#BFBF61616A6A:"
"#A3A3BEBE8C8C:#EBEBCBCB8B8B:#8181A1A1C1C1:#B4B48E8EADAD:#8F8FBCBCBBBB:"
"#ECECEFEFF4F4:#D8D8DEDEE9E9:#2E2E34344040"
),
"Novel": (
"#000000000000:#CCCC00000000:#000096960000:#D0D06B6B0000:#00000000CCCC:"
"#CCCC0000CCCC:#00008787CCCC:#CCCCCCCCCCCC:#7F7F7F7F7F7F:#CCCC00000000:"
"#000096960000:#D0D06B6B0000:#00000000CCCC:#CCCC0000CCCC:#00008686CBCB:"
"#FFFFFFFFFFFF:#3B3B23232222:#DFDFDBDBC3C3"
),
"Obsidian": (
"#000000000000:#A5A500000101:#0000BBBB0000:#FEFECCCC2222:#39399B9BDADA:"
"#BBBB0000BBBB:#0000BBBBBBBB:#BBBBBBBBBBBB:#555555555555:#FFFF00000303:"
"#9292C7C76363:#FEFEF7F77373:#A0A0D6D6FFFF:#FFFF5555FFFF:#5555FFFFFFFF:"
"#FFFFFFFFFFFF:#CCCCCCCCCCCC:#272730303232"
),
"Ocean": (
"#000000000000:#999900000000:#0000A6A60000:#999999990000:#00000000B2B2:"
"#B2B20000B2B2:#0000A6A6B2B2:#BFBFBFBFBFBF:#666666666666:#E5E500000000:"
"#0000D9D90000:#E5E5E5E50000:#00000000FFFF:#E5E50000E5E5:#0000E5E5E5E5:"
"#E5E5E5E5E5E5:#FFFFFFFFFFFF:#22224F4FBCBC"
),
"Ocean Dark": (
"#2B2B30303B3B:#BFBF61616A6A:#A3A3BEBE8C8C:#EBEBCBCB8B8B:#8F8FA1A1B3B3:"
"#B4B48E8EADAD:#9696B5B5B4B4:#C0C0C5C5CECE:#656573737E7E:#BFBF61616A6A:"
"#A3A3BEBE8C8C:#EBEBCBCB8B8B:#8F8FA1A1B3B3:#B4B48E8EADAD:#9696B5B5B4B4:"
"#EFEFF1F1F5F5:#C0C0C5C5CECE:#2B2B30303B3B"
),
"Ocean Light": (
"#EFEFF1F1F5F5:#BFBF61616A6A:#A3A3BEBE8C8C:#EBEBCBCB8B8B:#8F8FA1A1B3B3:"
"#B4B48E8EADAD:#9696B5B5B4B4:#C0C0C5C5CECE:#656573737E7E:#BFBF61616A6A:"
"#A3A3BEBE8C8C:#EBEBCBCB8B8B:#8F8FA1A1B3B3:#B4B48E8EADAD:#9696B5B5B4B4:"
"#2B2B30303B3B:#4F4F5B5B6666:#EFEFF1F1F5F5"
),
"Oceanic Next Dark": (
"#1B1B2B2B3434:#ECEC5f5f6767:#9999C7C79494:#FAFAC8C86363:#66669999CCCC:"
"#C5C59494C5C5:#5F5FB3B3B3B3:#C0C0C5C5CECE:#656573737E7E:#ECEC5f5f6767:"
"#9999C7C79494:#FAFAC8C86363:#66669999CCCC:#C5C59494C5C5:#5F5FB3B3B3B3:"
"#D8D8DEDEE9E9:#C0C0C5C5CECE:#1B1B2B2B3434"
),
"Oceanic Next Light": (
"#D8D8DEDEE9E9:#ECEC5f5f6767:#9999C7C79494:#FAFAC8C86363:#66669999CCCC:"
"#C5C59494C5C5:#5F5FB3B3B3B3:#C0C0C5C5CECE:#656573737E7E:#ECEC5f5f6767:"
"#9999C7C79494:#FAFAC8C86363:#66669999CCCC:#C5C59494C5C5:#5F5FB3B3B3B3:"
"#1B1B2B2B3434:#4F4F5B5B6666:#D8D8DEDEE9E9"
),
"Ollie": (
"#000000000000:#ABAB2E2E3030:#3131ABAB6060:#ABAB42420000:#2C2C5656ABAB:"
"#AFAF84842727:#1F1FA5A5ABAB:#8A8A8D8DABAB:#5A5A36362525:#FFFF3D3D4848:"
"#3B3BFFFF9999:#FFFF5E5E1E1E:#44448787FFFF:#FFFFC2C21C1C:#1E1EFAFAFFFF:"
"#5B5B6D6DA7A7:#8A8A8D8DAEAE:#212120202424"
),
"One Dark": (
"#000000000000:#B0B058586969:#7676A6A66565:#CFCFB0B07373:#4A4AA4A4B8B8:"
"#A1A16565C1C1:#4A4AA4A4B8B8:#B1B1B1B1B1B1:#4C4C57577272:#B0B058586969:"
"#7676A6A66565:#CFCFB0B07373:#4A4AA4A4B8B8:#A1A16565C1C1:#4A4AA4A4B8B8:"
"#DEDEDEDEDEDE:#4C4C57577171:#171718181C1C"
),
"Paul Millr": (
"#2A2A2A2A2A2A:#FFFF00000000:#7979FFFF0F0F:#E7E7BFBF0000:#38386B6BD7D7:"
"#B3B34949BEBE:#6666CCCCFFFF:#BBBBBBBBBBBB:#666666666666:#FFFF00008080:"
"#6666FFFF6666:#F3F3D6D64E4E:#70709A9AEDED:#DBDB6767E6E6:#7979DFDFF2F2:"
"#FFFFFFFFFFFF:#F2F2F2F2F2F2:#000000000000"
),
"Pencil Dark": (
"#212121212121:#C3C307077171:#1010A7A77878:#A8A89C9C1414:#00008E8EC4C4:"
"#52523C3C7979:#2020A5A5BABA:#D9D9D9D9D9D9:#424242424242:#FBFB00007A7A:"
"#5F5FD7D7AFAF:#F3F3E4E43030:#2020BBBBFCFC:#68685555DEDE:#4F4FB8B8CCCC:"
"#F1F1F1F1F1F1:#F1F1F1F1F1F1:#212121212121"
),
"Pencil Light": (
"#212121212121:#C3C307077171:#1010A7A77878:#A8A89C9C1414:#00008E8EC4C4:"
"#52523C3C7979:#2020A5A5BABA:#D9D9D9D9D9D9:#424242424242:#FBFB00007A7A:"
"#5F5FD7D7AFAF:#F3F3E4E43030:#2020BBBBFCFC:#68685555DEDE:#4F4FB8B8CCCC:"
"#F1F1F1F1F1F1:#424242424242:#F1F1F1F1F1F1"
),
"Pnevma": (
"#2F2F2E2E2D2D:#A3A366666666:#9090A5A57D7D:#D7D7AFAF8787:#7F7FA5A5BDBD:"
"#C7C79E9EC4C4:#8A8ADBDBB4B4:#D0D0D0D0D0D0:#4A4A48484545:#D7D787878787:"
"#AFAFBEBEA2A2:#E4E4C9C9AFAF:#A1A1BDBDCECE:#D7D7BEBEDADA:#B1B1E7E7DDDD:"
"#EFEFEFEFEFEF:#D0D0D0D0D0D0:#1C1C1C1C1C1C"
),
"Pro": (
"#000000000000:#999900000000:#0000A6A60000:#999999990000:#1F1F0808DBDB:"
"#B2B20000B2B2:#0000A6A6B2B2:#BFBFBFBFBFBF:#666666666666:#E5E500000000:"
"#0000D9D90000:#E5E5E5E50000:#00000000FFFF:#E5E50000E5E5:#0000E5E5E5E5:"
"#E5E5E5E5E5E5:#F2F2F2F2F2F2:#000000000000"
),
"Red Alert": (
"#000000000000:#D5D52E2E4D4D:#7171BEBE6B6B:#BEBEB8B86B6B:#47479B9BEDED:"
"#E8E87878D6D6:#6B6BBEBEB8B8:#D6D6D6D6D6D6:#262626262626:#E0E024245353:"
"#AFAFF0F08B8B:#DFDFDDDDB7B7:#6565A9A9F0F0:#DDDDB7B7DFDF:#B7B7DFDFDDDD:"
"#FFFFFFFFFFFF:#FFFFFFFFFFFF:#767624242323"
),
"Red Sands": (
"#000000000000:#FFFF3F3F0000:#0000BBBB0000:#E7E7B0B00000:#00007171FFFF:"
"#BBBB0000BBBB:#0000BBBBBBBB:#BBBBBBBBBBBB:#555555555555:#BBBB00000000:"
"#0000BBBB0000:#E7E7B0B00000:#00007171AEAE:#FFFF5555FFFF:#5555FFFFFFFF:"
"#FFFFFFFFFFFF:#D7D7C9C9A7A7:#797924241E1E"
),
"Rippedcasts": (
"#000000000000:#CDCDAFAF9595:#A7A7FFFF6060:#BFBFBBBB1F1F:#7575A5A5B0B0:"
"#FFFF7373FDFD:#595964647E7E:#BFBFBFBFBFBF:#666666666666:#EEEECBCBADAD:"
"#BCBCEEEE6868:#E5E5E5E50000:#8686BDBDC9C9:#E5E50000E5E5:#8C8C9B9BC3C3:"
"#E5E5E5E5E5E5:#FFFFFFFFFFFF:#2B2B2B2B2B2B"
),
"Royal": (
"#24241F1F2A2A:#909027274B4B:#232380801C1C:#B4B49D9D2727:#64648080AFAF:"
"#66664D4D9696:#8A8AAAAABDBD:#515149496565:#31312D2D3C3C:#D4D434346C6C:"
"#2C2CD8D84545:#FDFDE8E83A3A:#8F8FB9B9F9F9:#A4A47979E2E2:#ABABD3D3EBEB:"
"#9D9D8B8BBDBD:#505048486868:#101008081414"
),
"Rxvt": (
"#000000000000:#cdcd00000000:#0000cdcd0000:#cdcdcdcd0000:#00000000cdcd:"
"#cdcd0000cdcd:#0000cdcdcdcd:#fafaebebd7d7:#404040404040:#ffff00000000:"
"#0000ffff0000:#ffffffff0000:#00000000ffff:#ffff0000ffff:#0000ffffffff:"
"#ffffffffffff:#ffffffffffff:#000000000000"
),
"Sea Shells": (
"#171738384C4C:#D1D150502323:#02027C7C9B9B:#FCFCA0A02F2F:#1E1E49495050:"
"#6868D3D3F1F1:#5050A3A3B5B5:#DEDEB8B88D8D:#42424B4B5252:#D3D386867777:"
"#61618C8C9898:#FDFDD2D29E9E:#1B1BBCBCDDDD:#BBBBE3E3EEEE:#8686ABABB3B3:"
"#FEFEE3E3CDCD:#DEDEB8B88D8D:#080813131A1A"
),
"Seafoam Pastel": (
"#757575757575:#82825D5D4D4D:#71718C8C6161:#ADADA1A16D6D:#4D4D7B7B8282:"
"#8A8A71716767:#717193939393:#E0E0E0E0E0E0:#8A8A8A8A8A8A:#CFCF93937979:"
"#9898D9D9AAAA:#FAFAE7E79D9D:#7979C3C3CFCF:#D6D6B2B2A1A1:#ADADE0E0E0E0:"
"#E0E0E0E0E0E0:#D3D3E7E7D3D3:#242434343434"
),
"Seti": (
"#323232323232:#C2C228283232:#8E8EC4C43D3D:#E0E0C6C64F4F:#4343A5A5D5D5:"
"#8B8B5757B5B5:#8E8EC4C43D3D:#EEEEEEEEEEEE:#323232323232:#C2C228283232:"
"#8E8EC4C43D3D:#E0E0C6C64F4F:#4343A5A5D5D5:#8B8B5757B5B5:#8E8EC4C43D3D:"
"#FFFFFFFFFFFF:#CACACECECDCD:#111112121313"
),
"Shades of Purple": (
"#000000000000:#D9D904042929:#3A3AD9D90000:#FFFFE7E70000:#69694343FFFF:"
"#FFFF2B2B7070:#0000C5C5C7C7:#C7C7C7C7C7C7:#676767676767:#F9F929291B1B:"
"#4242D4D42525:#F1F1D0D00000:#68687171FFFF:#FFFF7676FFFF:#7979E7E7FAFA:"
"#FEFEFFFFFFFF:#1E1E1D1D4040:#FEFEFFFFFFFF"
),
"Shaman": (
"#010120202626:#B1B12F2F2C2C:#0000A9A94040:#5D5D8A8AA9A9:#444499998585:"
"#000059599C9C:#5C5C7E7E1919:#404055555454:#373743435050:#FFFF42424242:"
"#2A2AEAEA5E5E:#8D8DD3D3FDFD:#6161D4D4B9B9:#12129898FFFF:#9898CFCF2828:"
"#5858FAFAD6D6:#404055555555:#000010101414"
),
"Slate": (
"#212121212121:#E1E1A7A7BFBF:#8080D7D77878:#C4C4C9C9BFBF:#25254A4A4949:"
"#A3A38080D3D3:#1414ABAB9C9C:#0202C4C4E0E0:#FFFFFFFFFFFF:#FFFFCCCCD8D8:"
"#BDBDFFFFA8A8:#D0D0CBCBC9C9:#7979AFAFD2D2:#C4C4A7A7D8D8:#8B8BDEDEE0E0:"
"#E0E0E0E0E0E0:#3434B0B0D2D2:#212121212121"
),
"Smyck": (
"#000000000000:#B7B741413131:#7D7DA9A90000:#C4C4A4A40000:#6262A3A3C4C4:"
"#B9B98A8ACCCC:#202073738383:#A0A0A0A0A0A0:#7A7A7A7A7A7A:#D6D683837B7B:"
"#C4C4F0F03636:#FEFEE1E14D4D:#8D8DCFCFF0F0:#F7F79999FFFF:#6969D9D9CFCF:"
"#F7F7F7F7F7F7:#F7F7F7F7F7F7:#1B1B1B1B1B1B"
),
"Soft Server": (
"#000000000000:#A1A168686969:#9999A5A56969:#A2A290906969:#6A6A8F8FA3A3:"
"#69697171A3A3:#6B6BA4A48F8F:#9999A3A3A2A2:#66666C6C6B6B:#DCDC5B5B5F5F:"
"#BFBFDEDE5454:#DEDEB3B35F5F:#6262B1B1DFDF:#5F5F6E6EDEDE:#6464E3E39C9C:"
"#D1D1DFDFDEDE:#9999A3A3A2A2:#242426262626"
),
"Solarized Darcula": (
"#252529292A2A:#F2F248484040:#626296965555:#B6B688880000:#20207575C7C7:"
"#79797F7FD4D4:#151596968D8D:#D2D2D8D8D9D9:#252529292A2A:#F2F248484040:"
"#626296965555:#B6B688880000:#20207575C7C7:#79797F7FD4D4:#151596968D8D:"
"#D2D2D8D8D9D9:#D2D2D8D8D9D9:#3D3D3F3F4141"
),
"Solarized Dark Higher Contrast": (
"#000027273131:#D0D01B1B2424:#6B6BBEBE6C6C:#A5A577770505:#20207575C7C7:"
"#C6C61B1B6E6E:#252591918585:#E9E9E2E2CBCB:#000063638888:#F4F415153B3B:"
"#5050EEEE8484:#B1B17E7E2828:#17178D8DC7C7:#E1E14D4D8E8E:#0000B2B29E9E:"
"#FCFCF4F4DCDC:#9B9BC1C1C2C2:#00001E1E2626"
),
"Solarized Dark": (
"#000027273131:#D0D01B1B2424:#727289890505:#A5A577770505:#20207575C7C7:"
"#C6C61B1B6E6E:#252591918585:#E9E9E2E2CBCB:#00001E1E2626:#BDBD36361212:"
"#46465A5A6161:#525267676F6F:#707081818383:#58585656B9B9:#818190908F8F:"
"#FCFCF4F4DCDC:#707081818383:#00001E1E2626"
),
"Solarized Light": (
"#000027273131:#D0D01B1B2424:#727289890505:#A5A577770505:#20207575C7C7:"
"#C6C61B1B6E6E:#252591918585:#E9E9E2E2CBCB:#00001E1E2626:#BDBD36361212:"
"#46465A5A6161:#525267676F6F:#707081818383:#58585656B9B9:#818190908F8F:"
"#FCFCF4F4DCDC:#525267676F6F:#FCFCF4F4DCDC"
),
"Space Gray Eighties": (
"#151517171C1C:#ECEC5F5F6767:#8080A7A76363:#FDFDC2C25353:#54548585C0C0:"
"#BFBF8383C0C0:#5757C2C2C0C0:#EEEEECECE7E7:#555555555555:#FFFF69697373:"
"#9393D3D39393:#FFFFD1D15656:#4D4D8383D0D0:#FFFF5555FFFF:#8383E8E8E4E4:"
"#FFFFFFFFFFFF:#BDBDB9B9AEAE:#212121212121"
),
"Space Gray": (
"#000000000000:#AFAF4B4B5757:#8787B2B27979:#E5E5C0C07878:#7C7C8F8FA3A3:"
"#A3A379799696:#8484A6A6A4A4:#B2B2B8B8C2C2:#000000000000:#AFAF4B4B5757:"
"#8787B2B27979:#E5E5C0C07878:#7C7C8F8FA3A3:#A3A379799696:#8484A6A6A4A4:"
"#FFFFFEFEFEFE:#B2B2B8B8C2C2:#202023232C2C"
),
"Spacedust": (
"#6E6E52524646:#E3E35A5A0000:#5C5CABAB9696:#E3E3CDCD7B7B:#0E0E54548B8B:"
"#E3E35A5A0000:#0606AFAFC7C7:#F0F0F1F1CECE:#67674C4C3131:#FFFF8A8A3939:"
"#ADADCACAB8B8:#FFFFC7C77777:#6767A0A0CDCD:#FFFF8A8A3939:#8383A6A6B3B3:"
"#FEFEFFFFF0F0:#ECECEFEFC1C1:#0A0A1E1E2424"
),
"Spixel": (
"#000000000000:#A4A43E3E6363:#8A8AB5B54444:#F3F39A9A2626:#51518B8BA3A3:"
"#97977070B3B3:#5B5BA6A6A5A5:#D3D3D7D7CFCF:#707073736D6D:#E8E84A4A8484:"
"#A7A7E3E34646:#F1F1C5C58B8B:#7373B9B9D6D6:#C5E49865E6E6:#8282D9D9D8D8:"
"#EEEEEEEEECEC:#FFFFFFFFFFFF:#262626262222"
),
"Spring": (
"#000000000000:#FFFF4C4C8383:#1F1F8C8C3A3A:#1F1FC9C95A5A:#1C1CD2D2EEEE:"
"#89895959A8A8:#3E3E99999F9F:#FFFFFEFEFEFE:#000000000000:#FFFF00002121:"
"#1F1FC2C23131:#D4D4B7B70606:#1515A9A9FDFD:#89895959A8A8:#3E3E99999F9F:"
"#FFFFFEFEFEFE:#4D4D4D4D4C4C:#FFFFFFFFFFFF"
),
"Square": (
"#050505050505:#E9E989897C7C:#B6B637377D7D:#ECECEBEBBEBE:#A9A9CDCDEBEB:"
"#757550507B7B:#C9C9CACAECEC:#F2F2F2F2F2F2:#141414141414:#F9F992928686:"
"#C3C3F7F78686:#FCFCFBFBCCCC:#B6B6DEDEFBFB:#ADAD7F7FA8A8:#D7D7D9D9FCFC:"
"#E2E2E2E2E2E2:#ACACACACABAB:#1A1A1A1A1A1A"
),
"Sundried": (
"#30302B2B2A2A:#A6A646463D3D:#575776764444:#9C9C5F5F2A2A:#48485A5A9898:"
"#858545455151:#9C9C81814E4E:#C8C8C8C8C8C8:#4D4D4D4D4747:#AAAA00000C0C:"
"#12128C8C2020:#FCFC6A6A2020:#78789898F7F7:#FCFC8989A0A0:#FAFAD3D38484:"
"#FFFFFEFEFEFE:#C8C8C8C8C8C8:#1A1A18181818"
),
"Symphonic": (
"#000000000000:#DCDC32322F2F:#5656DBDB3A3A:#FFFF84840000:#00008484D4D4:"
"#B7B72929D9D9:#CCCCCCCCFFFF:#FFFFFFFFFFFF:#1B1B1D1D2121:#DCDC32322F2F:"
"#5656DBDB3A3A:#FFFF84840000:#00008484D4D4:#B7B72929D9D9:#CCCCCCCCFFFF:"
"#FFFFFFFFFFFF:#FFFFFFFFFFFF:#000000000000"
),
"Tango": (
"#000000000000:#cccc00000000:#4e4e9a9a0606:#c4c4a0a00000:#34346565a4a4:"
"#757550507b7b:#060698209a9a:#d3d3d7d7cfcf:#555557575353:#efef29292929:"
"#8a8ae2e23434:#fcfce9e94f4f:#72729f9fcfcf:#adad7f7fa8a8:#3434e2e2e2e2:"
"#eeeeeeeeecec:#ffffffffffff:#000000000000"
),
"Teerb": (
"#1C1C1C1C1C1C:#D6D686868686:#AEAED6D68686:#D7D7AFAF8787:#8686AEAED6D6:"
"#D6D6AEAED6D6:#8A8ADBDBB4B4:#D0D0D0D0D0D0:#1C1C1C1C1C1C:#D6D686868686:"
"#AEAED6D68686:#E4E4C9C9AFAF:#8686AEAED6D6:#D6D6AEAED6D6:#B1B1E7E7DDDD:"
"#EFEFEFEFEFEF:#D0D0D0D0D0D0:#262626262626"
),
"Terminal Basic": (
"#000000000000:#999900000000:#0000A6A60000:#999999990000:#00000000B2B2:"
"#B2B20000B2B2:#0000A6A6B2B2:#BFBFBFBFBFBF:#666666666666:#E5E500000000:"
"#0000D9D90000:#E5E5E5E50000:#00000000FFFF:#E5E50000E5E5:#0000E5E5E5E5:"
"#E5E5E5E5E5E5:#000000000000:#FFFFFFFFFFFF"
),
"Thayer Bright": (
"#1B1B1D1D1E1E:#F9F926267272:#4D4DF7F74040:#F3F3FDFD2121:#26265656D6D6:"
"#8C8C5454FEFE:#3737C8C8B4B4:#CCCCCCCCC6C6:#505053535454:#FFFF59599595:"
"#B6B6E3E35454:#FEFEEDED6C6C:#3F3F7878FFFF:#9E9E6F6FFEFE:#2323CECED4D4:"
"#F8F8F8F8F2F2:#F8F8F8F8F8F8:#1B1B1D1D1E1E"
),
"Tomorrow Night Blue": (
"#000000000000:#FFFF9D9DA3A3:#D1D1F1F1A9A9:#FFFFEEEEADAD:#BBBBDADAFFFF:"
"#EBEBBBBBFFFF:#9999FFFFFFFF:#FFFFFEFEFEFE:#000000000000:#FFFF9C9CA3A3:"
"#D0D0F0F0A8A8:#FFFFEDEDACAC:#BABADADAFFFF:#EBEBBABAFFFF:#9999FFFFFFFF:"
"#FFFFFEFEFEFE:#FFFFFEFEFEFE:#000024245151"
),
"Tomorrow Night Bright": (
"#000000000000:#D5D54E4E5353:#B9B9CACA4949:#E7E7C5C54747:#7979A6A6DADA:"
"#C3C39797D8D8:#7070C0C0B1B1:#FFFFFEFEFEFE:#000000000000:#D4D44D4D5353:"
"#B9B9C9C94949:#E6E6C4C44646:#7979A6A6DADA:#C3C39696D7D7:#7070C0C0B1B1:"
"#FFFFFEFEFEFE:#E9E9E9E9E9E9:#000000000000"
),
"Tomorrow Night Eighties": (
"#000000000000:#F2F277777979:#9999CCCC9999:#FFFFCCCC6666:#66669999CCCC:"
"#CCCC9999CCCC:#6666CCCCCCCC:#FFFFFEFEFEFE:#000000000000:#F1F177777979:"
"#9999CCCC9999:#FFFFCCCC6666:#66669999CCCC:#CCCC9999CCCC:#6666CCCCCCCC:"
"#FFFFFEFEFEFE:#CCCCCCCCCCCC:#2C2C2C2C2C2C"
),
"Tomorrow Night": (
"#000000000000:#CCCC66666666:#B5B5BDBD6868:#F0F0C6C67474:#8181A2A2BEBE:"
"#B2B29393BBBB:#8A8ABEBEB7B7:#FFFFFEFEFEFE:#000000000000:#CCCC66666666:"
"#B5B5BDBD6868:#F0F0C5C57474:#8080A1A1BDBD:#B2B29494BABA:#8A8ABDBDB6B6:"
"#FFFFFEFEFEFE:#C5C5C8C8C6C6:#1D1D1F1F2121"
),
"Tomorrow": (
"#000000000000:#C8C828282828:#71718C8C0000:#EAEAB7B70000:#41417171AEAE:"
"#89895959A8A8:#3E3E99999F9F:#FFFFFEFEFEFE:#000000000000:#C8C828282828:"
"#70708B8B0000:#E9E9B6B60000:#41417070AEAE:#89895858A7A7:#3D3D99999F9F:"
"#FFFFFEFEFEFE:#4D4D4D4D4C4C:#FFFFFFFFFFFF"
),
"Toy Chest": (
"#2C2C3F3F5757:#BEBE2D2D2626:#191991917171:#DADA8E8E2626:#32325D5D9696:"
"#8A8A5D5DDBDB:#3535A0A08F8F:#2323D0D08282:#323268688989:#DDDD59594343:"
"#3030CFCF7B7B:#E7E7D7D74B4B:#3333A5A5D9D9:#ADAD6B6BDCDC:#4141C3C3ADAD:"
"#D4D4D4D4D4D4:#3030CFCF7B7B:#232336364A4A"
),
"Treehouse": (
"#323212120000:#B1B127270E0E:#4444A9A90000:#A9A981810B0B:#575784849999:"
"#969636363C3C:#B2B259591D1D:#77776B6B5353:#424236362525:#EDED5C5C2020:"
"#5555F2F23737:#F1F1B7B73131:#8585CFCFECEC:#E0E04B4B5A5A:#F0F07D7D1414:"
"#FFFFC8C80000:#77776B6B5353:#191919191919"
),
"Twilight": (
"#141414141414:#C0C06C6C4343:#AFAFB9B97979:#C2C2A8A86C6C:#444446464949:"
"#B4B4BEBE7B7B:#777782828484:#FEFEFFFFD3D3:#262626262626:#DDDD7C7C4C4C:"
"#CBCBD8D88C8C:#E1E1C4C47D7D:#5A5A5D5D6161:#D0D0DBDB8E8E:#8A8A98989A9A:"
"#FEFEFFFFD3D3:#FEFEFFFFD3D3:#141414141414"
),
"Urple": (
"#000000000000:#AFAF42425B5B:#3737A3A31515:#ACAC5B5B4141:#55554D4D9A9A:"
"#6C6C3B3BA1A1:#808080808080:#878779799C9C:#5C5C31312525:#FFFF63638787:"
"#2828E5E51F1F:#F0F080806161:#85857979EDED:#A0A05D5DEEEE:#EAEAEAEAEAEA:"
"#BFBFA3A3FFFF:#868679799A9A:#1B1B1B1B2323"
),
"Vaughn": (
"#242423234F4F:#707050505050:#6060B4B48A8A:#DFDFAFAF8F8F:#55555555FFFF:"
"#F0F08C8CC3C3:#8C8CD0D0D3D3:#707090908080:#707090908080:#DCDCA3A3A3A3:"
"#6060B4B48A8A:#F0F0DFDFAFAF:#55555555FFFF:#ECEC9393D3D3:#9393E0E0E3E3:"
"#FFFFFFFFFFFF:#DCDCDCDCCCCC:#252523234E4E"
),
"Vibrant Ink": (
"#878787878787:#FFFF66660000:#CCCCFFFF0404:#FFFFCCCC0000:#4444B3B3CCCC:"
"#99993333CCCC:#4444B3B3CCCC:#F5F5F5F5F5F5:#555555555555:#FFFF00000000:"
"#0000FFFF0000:#FFFFFFFF0000:#00000000FFFF:#FFFF0000FFFF:#0000FFFFFFFF:"
"#E5E5E5E5E5E5:#FFFFFFFFFFFF:#000000000000"
),
"Warm Neon": (
"#000000000000:#E2E243434545:#3838B1B13939:#DADAE1E14545:#42426060C5C5:"
"#F8F81F1FFBFB:#2929BABAD3D3:#D0D0B8B8A3A3:#FDFDFCFCFCFC:#E8E86F6F7171:"
"#9B9BC0C08F8F:#DDDDD9D97979:#7A7A9090D5D5:#F6F67474B9B9:#5E5ED1D1E4E4:"
"#D8D8C8C8BBBB:#AFAFDADAB6B6:#3F3F3F3F3F3F"
),
"Wez": (
"#000000000000:#CCCC55555555:#5555CCCC5555:#CDCDCDCD5555:#54545555CBCB:"
"#CCCC5555CCCC:#7A7ACACACACA:#CCCCCCCCCCCC:#555555555555:#FFFF55555555:"
"#5555FFFF5555:#FFFFFFFF5555:#55555555FFFF:#FFFF5555FFFF:#5555FFFFFFFF:"
"#FFFFFFFFFFFF:#B3B3B3B3B3B3:#000000000000"
),
"Wild Cherry": (
"#000005050606:#D9D940408585:#2A2AB2B25050:#FFFFD1D16F6F:#88883C3CDCDC:"
"#ECECECECECEC:#C1C1B8B8B7B7:#FFFFF8F8DDDD:#00009C9CC9C9:#DADA6B6BABAB:"
"#F4F4DBDBA5A5:#EAEAC0C06666:#2F2F8B8BB9B9:#AEAE63636B6B:#FFFF91919D9D:"
"#E4E483838D8D:#D9D9FAFAFFFF:#1F1F16162626"
),
"Wombat": (
"#000000000000:#FFFF60605A5A:#B1B1E8E86969:#EAEAD8D89C9C:#5D5DA9A9F6F6:"
"#E8E86A6AFFFF:#8282FFFFF6F6:#DEDED9D9CECE:#313131313131:#F5F58B8B7F7F:"
"#DCDCF8F88F8F:#EEEEE5E5B2B2:#A5A5C7C7FFFF:#DDDDAAAAFFFF:#B6B6FFFFF9F9:"
"#FEFEFFFFFEFE:#DEDED9D9CECE:#171717171717"
),
"Wryan": (
"#333333333333:#8C8C46466565:#282873737373:#7C7C7C7C9999:#393955557373:"
"#5E5E46468C8C:#313165658C8C:#89899C9CA1A1:#3D3D3D3D3D3D:#BFBF4D4D8080:"
"#5353A6A6A6A6:#9E9E9E9ECBCB:#47477A7AB3B3:#7E7E6262B3B3:#60609696BFBF:"
"#C0C0C0C0C0C0:#999999999393:#101010101010"
),
"Xterm": (
"#000000000000:#cdcb00000000:#0000cdcb0000:#cdcbcdcb0000:#1e1a908fffff:"
"#cdcb0000cdcb:#0000cdcbcdcb:#e5e2e5e2e5e2:#4ccc4ccc4ccc:#ffff00000000:"
"#0000ffff0000:#ffffffff0000:#46458281b4ae:#ffff0000ffff:#0000ffffffff:"
"#ffffffffffff:#ffffffffffff:#000000000000"
),
"Zenburn": (
"#4D4D4D4D4D4D:#707050505050:#6060B4B48A8A:#F0F0DFDFAFAF:#505060607070:"
"#DCDC8C8CC3C3:#8C8CD0D0D3D3:#DCDCDCDCCCCC:#707090908080:#DCDCA3A3A3A3:"
"#C3C3BFBF9F9F:#E0E0CFCF9F9F:#9494BFBFF3F3:#ECEC9393D3D3:#9393E0E0E3E3:"
"#FFFFFFFFFFFF:#DCDCDCDCCCCC:#3F3F3F3F3F3F"
),
"Aci": (
"#363636363636:#FFFF08088383:#8383FFFF0808:#FFFF83830808:#08088383FFFF:"
"#83830808FFFF:#0808FFFF8383:#B6B6B6B6B6B6:#424242424242:#FFFF1E1E8E8E:"
"#8E8EFFFF1E1E:#FFFF8E8E1E1E:#1E1E8E8EFFFF:#8E8E1E1EFFFF:#1E1EFFFF8E8E:"
"#C2C2C2C2C2C2:#B4B4E1E1FDFD:#0D0D19192626"
),
"Aco": (
"#3F3F3F3F3F3F:#FFFF08088383:#8383FFFF0808:#FFFF83830808:#08088383FFFF:"
"#83830808FFFF:#0808FFFF8383:#BEBEBEBEBEBE:#474747474747:#FFFF1E1E8E8E:"
"#8E8EFFFF1E1E:#FFFF8E8E1E1E:#1E1E8E8EFFFF:#8E8E1E1EFFFF:#1E1EFFFF8E8E:"
"#C4C4C4C4C4C4:#B4B4E1E1FDFD:#1F1F13130505"
),
"Azu": (
"#000000000000:#ACAC6D6D7474:#7474ACAC6D6D:#ACACA4A46D6D:#6D6D7474ACAC:"
"#A4A46D6DACAC:#6D6DACACA4A4:#E6E6E6E6E6E6:#262626262626:#D6D6B8B8BCBC:"
"#BCBCD6D6B8B8:#D6D6D3D3B8B8:#B8B8BCBCD6D6:#D3D3B8B8D6D6:#B8B8D6D6D3D3:"
"#FFFFFFFFFFFF:#D9D9E6E6F2F2:#090911111A1A"
),
"Bim": (
"#2C2C24242323:#F5F55757A0A0:#A9A9EEEE5555:#F5F5A2A25555:#5E5EA2A2ECEC:"
"#A9A95757ECEC:#5E5EEEEEA0A0:#919189898888:#919189898888:#F5F57979B2B2:"
"#BBBBEEEE7878:#F5F5B3B37878:#8181B3B3ECEC:#BBBB7979ECEC:#8181EEEEB2B2:"
"#F5F5EEEEECEC:#A9A9BEBED8D8:#010128284949"
),
"Cai": (
"#000000000000:#CACA27274D4D:#4D4DCACA2727:#CACAA4A42727:#27274D4DCACA:"
"#A4A42727CACA:#2727CACAA4A4:#808080808080:#808080808080:#E9E98D8DA3A3:"
"#A3A3E9E98D8D:#E9E9D4D48D8D:#8D8DA3A3E9E9:#D4D48D8DE9E9:#8D8DE9E9D4D4:"
"#FFFFFFFFFFFF:#D9D9E6E6F2F2:#090911111A1A"
),
"Elementary": (
"#303030303030:#E1E132321A1A:#6A6AB0B01717:#FFFFC0C00505:#00004F4F9E9E:"
"#ECEC00004848:#2A2AA7A7E7E7:#F2F2F2F2F2F2:#5D5D5D5D5D5D:#FFFF36361E1E:"
"#7B7BC9C91F1F:#FFFFD0D00A0A:#00007171FFFF:#FFFF1D1D6262:#4B4BB8B8FDFD:"
"#A0A02020F0F0:#F2F2F2F2F2F2:#101010101010"
),
"Elic": (
"#303030303030:#E1E132321A1A:#6A6AB0B01717:#FFFFC0C00505:#72729F9FCFCF:"
"#ECEC00004848:#F2F2F2F2F2F2:#2A2AA7A7E7E7:#5D5D5D5D5D5D:#FFFF36361E1E:"
"#7B7BC9C91F1F:#FFFFD0D00A0A:#00007171FFFF:#FFFF1D1D6262:#4B4BB8B8FDFD:"
"#A0A02020F0F0:#F2F2F2F2F2F2:#4A4A45453E3E"
),
"Elio": (
"#303030303030:#E1E132321A1A:#6A6AB0B01717:#FFFFC0C00505:#72729F9FCFCF:"
"#ECEC00004848:#2A2AA7A7E7E7:#F2F2F2F2F2F2:#5D5D5D5D5D5D:#FFFF36361E1E:"
"#7B7BC9C91F1F:#FFFFD0D00A0A:#00007171FFFF:#FFFF1D1D6262:#4B4BB8B8FDFD:"
"#A0A02020F0F0:#F2F2F2F2F2F2:#04041A1A3B3B"
),
"Freya": (
"#070736364242:#DCDC32322F2F:#858599990000:#B5B589890000:#26268B8BD2D2:"
"#ECEC00004848:#2A2AA1A19898:#9494A3A3A5A5:#58586E6E7575:#CBCB4B4B1616:"
"#858599990000:#B5B589890000:#26268B8BD2D2:#D3D336368282:#2A2AA1A19898:"
"#6C6C7171C4C4:#9494A3A3A5A5:#25252E2E3232"
),
"Gruvbox Dark": (
"#282828282828:#CCCC24241D1D:#989897971A19:#D7D799992120:#454585858888:"
"#B1B162618685:#68689D9D6A6A:#EBEBDBDBB2B2:#3C3C38383636:#FBFB49493434:"
"#B8B8BBBB2626:#FAFABDBC2F2F:#8383A5A59898:#D3D386869B9B:#8E8EC0C07C7B:"
"#FBFBF1F1C7C7:#EBEBDBDBB2B2:#282828282828"
),
"Gruvbox Material Dark": (
"#3C3C38383636:#EAEA69696262:#A9A9B6B66565:#D8D8A6A65757:#7D7DAEAEA3A3:"
"#D3D386869B9B:#8989B4B48282:#D4D4BEBE9898:#3C3C38383636:#EAEA69696262:"
"#A9A9B6B66565:#D8D8A6A65757:#7D7DAEAEA3A3:#D3D386869B9B:#8989B4B48282:"
"#D4D4BEBE9898:#D4D4BEBE9898:#282828282828"
),
"Hemisu Dark": (
"#444444444444:#FFFF00005454:#B1B1D6D63030:#9D9D89895E5E:#6767BEBEE3E3:"
"#B5B57676BCBC:#56569A9A9F9F:#EDEDEDEDEDED:#777777777777:#D6D65E5E7575:"
"#BABAFFFFAAAA:#ECECE1E1C8C8:#9F9FD3D3E5E5:#DEDEB3B3DFDF:#B6B6E0E0E5E5:"
"#FFFFFFFFFFFF:#FFFFFFFFFFFF:#000000000000"
),
"Hemisu Light": (
"#777777777777:#FFFF00005555:#737391910000:#50503D3D1515:#535380809191:"
"#5B5B34345E5E:#535380809191:#999999999999:#999999999999:#D6D65E5E7676:"
"#9C9CC7C70000:#949475755555:#9D9DB3B3CDCD:#A1A18484A4A4:#8585B2B2AAAA:"
"#BABABABABABA:#444444444444:#EFEFEFEFEFEF"
),
"Jup": (
"#000000000000:#DDDD00006F6F:#6F6FDDDD0000:#DDDD6F6F0000:#00006F6FDDDD:"
"#6F6F0000DDDD:#0000DDDD6F6F:#F2F2F2F2F2F2:#7D7D7D7D7D7D:#FFFF7474B9B9:"
"#B9B9FFFF7474:#FFFFB9B97474:#7474B9B9FFFF:#B9B97474FFFF:#7474FFFFB9B9:"
"#FFFFFFFFFFFF:#232347476A6A:#757584848080"
),
"Mar": (
"#000000000000:#B5B540407B7B:#7B7BB5B54040:#B5B57B7B4040:#40407B7BB5B5:"
"#7B7B4040B5B5:#4040B5B57B7B:#F8F8F8F8F8F8:#737373737373:#CDCD7373A0A0:"
"#A0A0CDCD7373:#CDCDA0A07373:#7373A0A0CDCD:#A0A07373CDCD:#7373CDCDA0A0:"
"#FFFFFFFFFFFF:#232347476A6A:#FFFFFFFFFFFF"
),
"Material": (
"#070736364141:#EBEB60606B6B:#C3C3E8E88D8D:#F7F7EBEB9595:#8080CBCBC3C3:"
"#FFFF24249090:#AEAEDDDDFFFF:#FFFFFFFFFFFF:#00002B2B3636:#EBEB60606B6B:"
"#C3C3E8E88D8D:#F7F7EBEB9595:#7D7DC6C6BFBF:#6C6C7171C3C3:#343443434D4D:"
"#FFFFFFFFFFFF:#C3C3C7C7D1D1:#1E1E28282C2C"
),
"Miu": (
"#000000000000:#B8B87A7A7A7A:#7A7AB8B87A7A:#B8B8B8B87A7A:#7A7A7A7AB8B8:"
"#B8B87A7AB8B8:#7A7AB8B8B8B8:#D9D9D9D9D9D9:#262626262626:#DBDBBDBDBDBD:"
"#BDBDDBDBBDBD:#DBDBDBDBBDBD:#BDBDBDBDDBDB:#DBDBBDBDDBDB:#BDBDDBDBDBDB:"
"#FFFFFFFFFFFF:#D9D9E6E6F2F2:#0D0D19192626"
),
"Monokai dark": (
"#757571715E5E:#F9F926267272:#A6A6E2E22E2E:#F4F4BFBF7575:#6666D9D9EFEF:"
"#AEAE8181FFFF:#2A2AA1A19898:#F9F9F8F8F5F5:#272728282222:#F9F926267272:"
"#A6A6E2E22E2E:#F4F4BFBF7575:#6666D9D9EFEF:#AEAE8181FFFF:#2A2AA1A19898:"
"#F8F8F8F8F2F2:#F8F8F8F8F2F2:#272728282222"
),
"Nep": (
"#000000000000:#DDDD6F6F0000:#0000DDDD6F6F:#6F6FDDDD0000:#6F6F0000DDDD:"
"#DDDD00006F6F:#00006F6FDDDD:#F2F2F2F2F2F2:#7D7D7D7D7D7D:#FFFFB9B97474:"
"#7474FFFFB9B9:#B9B9FFFF7474:#B9B97474FFFF:#FFFF7474B9B9:#7474B9B9FFFF:"
"#FFFFFFFFFFFF:#232347476A6A:#757584848080"
),
"One Light": (
"#000000000000:#DADA3E3E3939:#414193933E3E:#858555550404:#31315E5EEEEE:"
"#939300009292:#0E0E6F6FADAD:#8E8E8F8F9696:#2A2A2B2B3232:#DADA3E3E3939:"
"#414193933E3E:#858555550404:#31315E5EEEEE:#939300009292:#0E0E6F6FADAD:"
"#FFFFFEFEFEFE:#2A2A2B2B3232:#F8F8F8F8F8F8"
),
"Pali": (
"#0A0A0A0A0A0A:#ABAB8F8F7474:#7474ABAB8F8F:#8F8FABAB7474:#8F8F7474ABAB:"
"#ABAB74748F8F:#74748F8FABAB:#F2F2F2F2F2F2:#5D5D5D5D5D5D:#FFFF1D1D6262:"
"#9C9CC3C3AFAF:#FFFFD0D00A0A:#AFAF9C9CC3C3:#FFFF1D1D6262:#4B4BB8B8FDFD:"
"#A0A02020F0F0:#D9D9E6E6F2F2:#23232E2E3737"
),
"Peppermint": (
"#353535353535:#E6E645456969:#8989D2D28787:#DADAB7B75252:#43439E9ECFCF:"
"#D9D96161DCDC:#6464AAAAAFAF:#B3B3B3B3B3B3:#535353535353:#E4E485859A9A:"
"#A2A2CCCCA1A1:#E1E1E3E38787:#6F6FBBBBE2E2:#E5E58686E7E7:#9696DCDCDADA:"
"#DEDEDEDEDEDE:#C7C7C7C7C7C7:#000000000000"
),
"Sat": (
"#000000000000:#DDDD00000707:#0707DDDD0000:#DDDDD6D60000:#00000707DDDD:"
"#D6D60000DDDD:#0000DDDDD6D6:#F2F2F2F2F2F2:#7D7D7D7D7D7D:#FFFF74747878:"
"#7878FFFF7474:#FFFFFAFA7474:#74747878FFFF:#FAFA7474FFFF:#7474FFFFFAFA:"
"#FFFFFFFFFFFF:#232347476A6A:#757584848080"
),
"Shel": (
"#2C2C24242323:#ABAB24246363:#6C6CA3A32323:#ABAB64642323:#2C2C6464A2A2:"
"#6C6C2424A2A2:#2C2CA3A36363:#919189898888:#919189898888:#F5F58888B9B9:"
"#C2C2EEEE8686:#F5F5BABA8686:#8F8FBABAECEC:#C2C28888ECEC:#8F8FEEEEB9B9:"
"#F5F5EEEEECEC:#48488282CDCD:#2A2A20201F1F"
),
"Tin": (
"#000000000000:#8D8D53534E4E:#4E4E8D8D5353:#88888D8D4E4E:#53534E4E8D8D:"
"#8D8D4E4E8888:#4E4E88888D8D:#FFFFFFFFFFFF:#000000000000:#B5B57D7D7878:"
"#7878B5B57D7D:#B0B0B5B57878:#7D7D7878B5B5:#B5B57878B0B0:#7878B0B0B5B5:"
"#FFFFFFFFFFFF:#FFFFFFFFFFFF:#2E2E2E2E3535"
),
"Ura": (
"#000000000000:#C2C21B1B6F6F:#6F6FC2C21B1B:#C2C26F6F1B1B:#1B1B6F6FC2C2:"
"#6F6F1B1BC2C2:#1B1BC2C26F6F:#808080808080:#808080808080:#EEEE8484B9B9:"
"#B9B9EEEE8484:#EEEEB9B98484:#8484B9B9EEEE:#B9B98484EEEE:#8484EEEEB9B9:"
"#E5E5E5E5E5E5:#232347476A6A:#FEFEFFFFEEEE"
),
"Vag": (
"#303030303030:#A8A871713939:#3939A8A87171:#7171A8A83939:#71713939A8A8:"
"#A8A839397171:#39397171A8A8:#8A8A8A8A8A8A:#494949494949:#B0B076763B3B:"
"#3B3BB0B07676:#7676B0B03B3B:#76763B3BB0B0:#B0B03B3B7676:#3B3B7676B0B0:"
"#CFCFCFCFCFCF:#D9D9E6E6F2F2:#19191F1F1D1D"
),
}
| 55,379
|
Python
|
.py
| 1,050
| 45.299048
| 80
| 0.713975
|
Guake/guake
| 4,406
| 575
| 405
|
GPL-2.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,054
|
guake_logging.py
|
Guake_guake/guake/guake_logging.py
|
# -*- coding: utf-8; -*-
"""
Copyright (C) 2007-2013 Guake authors
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
import logging.config
try:
from colorlog import ColoredFormatter
except ImportError:
ColoredFormatter = None
log = logging.getLogger(__name__)
def setupLogging(debug_mode):
if debug_mode:
base_logging_level = logging.DEBUG
else:
base_logging_level = logging.INFO
if ColoredFormatter:
level_str = logging.getLevelName(base_logging_level)
logging.config.dictConfig(
{
"version": 1,
"disable_existing_loggers": False,
"loggers": {
"": {
"handlers": ["default"],
"level": level_str,
"propagate": True,
},
},
"handlers": {
"default": {
"level": level_str,
"class": "logging.StreamHandler",
"formatter": "default",
},
},
"formatters": {
"default": {
"()": "colorlog.ColoredFormatter",
"format": "%(log_color)s%(levelname)-8s%(reset)s %(message)s",
"log_colors": {
"DEBUG": "cyan",
"INFO": "green",
"WARNING": "yellow",
"ERROR": "red",
"CRITICAL": "red,bg_white",
},
}
},
}
)
else:
logging.basicConfig(level=base_logging_level, format="%(message)s")
log.setLevel(base_logging_level)
log.debug("Logging configuration complete")
| 2,524
|
Python
|
.py
| 67
| 25.61194
| 86
| 0.534722
|
Guake/guake
| 4,406
| 575
| 405
|
GPL-2.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,055
|
notebook.py
|
Guake_guake/guake/notebook.py
|
# -*- coding: utf-8; -*-
"""
Copyright (C) 2007-2018 Guake authors
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 guake.about import AboutDialog
from guake.boxes import RootTerminalBox
from guake.boxes import TabLabelEventBox
from guake.boxes import TerminalBox
from guake.callbacks import MenuHideCallback
from guake.callbacks import NotebookScrollCallback
from guake.dialogs import PromptQuitDialog
from guake.globals import PROMPT_ALWAYS
from guake.globals import PROMPT_PROCESSES
from guake.menus import mk_notebook_context_menu
from guake.prefs import PrefsDialog
from guake.utils import HidePrevention
from guake.utils import gdk_is_x11_display
from guake.utils import get_process_name
from guake.utils import save_tabs_when_changed
import gi
import os
gi.require_version("Gtk", "3.0")
gi.require_version("Wnck", "3.0")
from gi.repository import GObject
from gi.repository import Gdk
from gi.repository import Gtk
from gi.repository import Wnck
from guake.terminal import GuakeTerminal
import logging
import posix
log = logging.getLogger(__name__)
class TerminalNotebook(Gtk.Notebook):
def __init__(self, *args, **kwargs):
Gtk.Notebook.__init__(self, *args, **kwargs)
self.last_terminal_focused = None
self.set_name("notebook-teminals")
self.set_tab_pos(Gtk.PositionType.BOTTOM)
self.set_property("show-tabs", True)
self.set_property("enable-popup", False)
self.set_property("scrollable", True)
self.set_property("show-border", False)
self.set_property("visible", True)
self.set_property("has-focus", True)
self.set_property("can-focus", True)
self.set_property("is-focus", True)
self.set_property("expand", True)
if GObject.signal_lookup("terminal-spawned", TerminalNotebook) == 0:
GObject.signal_new(
"terminal-spawned",
TerminalNotebook,
GObject.SignalFlags.RUN_LAST,
GObject.TYPE_NONE,
(GObject.TYPE_PYOBJECT, GObject.TYPE_INT),
)
GObject.signal_new(
"page-deleted",
TerminalNotebook,
GObject.SignalFlags.RUN_LAST,
GObject.TYPE_NONE,
(),
)
self.scroll_callback = NotebookScrollCallback(self)
self.add_events(Gdk.EventMask.SCROLL_MASK)
self.connect("scroll-event", self.scroll_callback.on_scroll)
self.notebook_on_button_press_id = self.connect(
"button-press-event", self.on_button_press, None
)
# Action box
self.pin_button = Gtk.ToggleButton(
image=Gtk.Image.new_from_icon_name("view-pin-symbolic", Gtk.IconSize.MENU),
visible=False,
)
self.pin_button.connect("clicked", self.on_pin_clicked)
self.new_page_button = Gtk.Button(
image=Gtk.Image.new_from_icon_name("tab-new-symbolic", Gtk.IconSize.MENU),
visible=True,
)
self.new_page_button.connect("clicked", self.on_new_tab)
self.tab_selection_button = Gtk.Button(
image=Gtk.Image.new_from_icon_name("pan-down-symbolic", Gtk.IconSize.MENU),
visible=True,
)
self.popover = Gtk.Popover()
self.popover_window = None
self.tab_selection_button.connect("clicked", self.on_tab_selection)
self.action_box = Gtk.Box(visible=True)
self.action_box.pack_start(self.pin_button, 0, 0, 0)
self.action_box.pack_start(self.new_page_button, 0, 0, 0)
self.action_box.pack_start(self.tab_selection_button, 0, 0, 0)
self.set_action_widget(self.action_box, Gtk.PackType.END)
def attach_guake(self, guake):
self.guake = guake
self.guake.settings.general.onChangedValue("window-losefocus", self.on_lose_focus_toggled)
self.pin_button.set_visible(self.guake.settings.general.get_boolean("window-losefocus"))
def on_button_press(self, target, event, user_data):
if event.button == 3:
menu = mk_notebook_context_menu(self)
menu.connect("hide", MenuHideCallback(self.guake.window).on_hide)
try:
menu.popup_at_pointer(event)
except AttributeError:
# Gtk 3.18 fallback ("'Menu' object has no attribute 'popup_at_pointer'")
menu.popup(None, None, None, None, event.button, event.time)
elif (
event.type == Gdk.EventType.DOUBLE_BUTTON_PRESS
and event.button == 1
and event.window.get_height() < 60
):
# event.window.get_height() reports the height of the clicked frame
self.new_page_with_focus()
return False
def on_pin_clicked(self, user_data=None):
hide_prevention = HidePrevention(self.guake.window)
if self.pin_button.get_active():
hide_prevention.prevent()
else:
hide_prevention.allow()
def on_lose_focus_toggled(self, settings, key, user_data=None):
self.pin_button.set_visible(settings.get_boolean(key))
@save_tabs_when_changed
def on_new_tab(self, user_data):
self.new_page_with_focus()
def on_tab_selection(self, user_data):
"""Construct the tab selection popover
Since we did not use Gtk.ListStore to store tab information, we will construct the
tab selection popover content each time when user click them.
"""
# Remove previous window
if self.popover_window:
self.popover.remove(self.popover_window)
# This makes the list's background transparent
# ref: epiphany
css_provider = Gtk.CssProvider()
css_provider.load_from_data(
b"#popover-window list { border-style: none; background-color: transparent; }"
)
Gtk.StyleContext.add_provider_for_screen(
Gdk.Screen.get_default(),
css_provider,
Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION,
)
# Construct popover properties
BOX_HEIGHT = 30
LISTBOX_MARGIN = 12
self.popover_window = Gtk.ScrolledWindow(name="popover-window")
self.popover_listbox = Gtk.ListBox()
self.popover_listbox.set_property("margin", LISTBOX_MARGIN)
self.popover_window.add_with_viewport(self.popover_listbox)
max_height = (
self.guake.window.get_allocation().height - BOX_HEIGHT
if self.guake
else BOX_HEIGHT * 10
)
height = BOX_HEIGHT * self.get_n_pages() + LISTBOX_MARGIN * 4
self.popover_window.set_min_content_height(min(max_height, height))
self.popover_window.set_min_content_width(325)
self.popover.add(self.popover_window)
# Construct content
current_term = self.get_current_terminal()
selected_row = 0
for i in range(self.get_n_pages()):
row = Gtk.ListBoxRow()
box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
box.set_size_request(200, BOX_HEIGHT)
label = Gtk.Label(self.get_tab_text_index(i))
label.set_xalign(0.0)
box.pack_start(label, 0, 0, 5)
row.add(box)
setattr(row, "page_index", i)
self.popover_listbox.add(row)
if current_term in self.get_terminals_for_page(i):
self.popover_listbox.select_row(row)
selected_row = i
# Signal
self.popover_listbox.connect("row-activated", self.on_popover_tab_select)
# Show popup
self.popover.set_position(Gtk.PositionType.TOP)
self.popover.set_relative_to(user_data)
self.popover.show_all()
try:
# For GTK >= 3.22
self.popover.popup()
except AttributeError:
pass
# Adjust scrollor
while Gtk.events_pending():
Gtk.main_iteration()
if selected_row:
adj = self.popover_window.get_vadjustment()
v = adj.get_upper() - adj.get_page_size()
part = v / self.get_n_pages()
adj.set_value(part * (selected_row + 1))
def on_popover_tab_select(self, list_box, row):
page_index = getattr(row, "page_index", -1)
if page_index != -1:
self.set_current_page(page_index)
self.get_terminals_for_page(page_index)[0].grab_focus()
def set_tabbar_visible(self, v):
self.set_property("show-tabs", v)
def set_last_terminal_focused(self, terminal):
self.last_terminal_focused = terminal
def get_focused_terminal(self):
for terminal in self.iter_terminals():
if terminal.has_focus():
return terminal
def get_current_terminal(self):
# TODO NOTEBOOK the name of this method should
# be changed, for now it returns the last focused terminal
return self.last_terminal_focused
def get_terminals_for_page(self, index):
page = self.get_nth_page(index)
return page.get_terminals()
def get_terminals(self):
terminals = []
for page in self.iter_pages():
terminals += page.get_terminals()
return terminals
def get_running_fg_processes(self):
processes = []
for page in self.iter_pages():
processes += self.get_running_fg_processes_page(page)
return processes
def get_running_fg_processes_page(self, page):
processes = []
for terminal in page.get_terminals():
pty = terminal.get_pty()
if not pty:
continue
fdpty = pty.get_fd()
term_pid = terminal.pid
try:
fgpid = posix.tcgetpgrp(fdpty)
log.debug("found running pid: %s", fgpid)
if fgpid not in (-1, term_pid):
processes.append((fgpid, get_process_name(fgpid)))
except OSError:
log.debug(
"Cannot retrieve any pid from terminal %s, looks like it is already dead",
terminal,
)
return processes
def has_page(self):
return self.get_n_pages() > 0
def iter_terminals(self):
for page in self.iter_pages():
if page is not None:
for t in page.iter_terminals():
yield t
def iter_tabs(self):
for page_num in range(self.get_n_pages()):
yield self.get_tab_label(self.get_nth_page(page_num))
def iter_pages(self):
for page_num in range(self.get_n_pages()):
yield self.get_nth_page(page_num)
def delete_page(self, page_num, kill=True, prompt=0):
log.debug("Deleting page index %s", page_num)
if page_num >= self.get_n_pages() or page_num < 0:
log.error("Can not delete page %s no such index", page_num)
return
page = self.get_nth_page(page_num)
# TODO NOTEBOOK it would be nice if none of the "ui" stuff
# (PromptQuitDialog) would be in here
procs = self.get_running_fg_processes_page(page)
if prompt == PROMPT_ALWAYS or (prompt == PROMPT_PROCESSES and procs):
# TODO NOTEBOOK remove call to guake
if not PromptQuitDialog(self.guake.window, procs, -1, None).close_tab():
return
for terminal in page.get_terminals():
if kill:
terminal.kill()
terminal.destroy()
if self.get_nth_page(page_num) is page:
# NOTE: GitHub issue #1438
# Previous line `terminal.destroy()` will finally called `on_terminal_exited`,
# and called `RootTerminalBox.remove_dead_child`, then called `remove_page`.
#
# But in some cases (e.g. #1438), it will not remove the page by
# `terminal.destory() chain`.
#
# Check this by compare same page_num page with previous saved page instance,
# and remove the page if it really didn't remove it.
self.remove_page(page_num)
@save_tabs_when_changed
def remove_page(self, page_num):
super().remove_page(page_num)
# focusing the first terminal on the previous page
if self.get_current_page() > -1:
page = self.get_nth_page(self.get_current_page())
if page.get_terminals():
page.get_terminals()[0].grab_focus()
self.hide_tabbar_if_one_tab()
self.emit("page-deleted")
def delete_page_by_label(self, label, kill=True, prompt=0):
self.delete_page(self.find_tab_index_by_label(label), kill, prompt)
def delete_page_current(self, kill=True, prompt=0):
self.delete_page(self.get_current_page(), kill, prompt)
def new_page(self, directory=None, position=None, empty=False, open_tab_cwd=False):
terminal_box = TerminalBox()
if empty:
terminal = None
else:
terminal = self.terminal_spawn(directory, open_tab_cwd)
terminal_box.set_terminal(terminal)
root_terminal_box = RootTerminalBox(self.guake, self)
root_terminal_box.set_child(terminal_box)
page_num = self.insert_page(
root_terminal_box, None, position if position is not None else -1
)
self.set_tab_reorderable(root_terminal_box, True)
self.show_all() # needed to show newly added tabs and pages
# this is needed because self.window.show_all() results in showing every
# thing which includes the scrollbar too
self.guake.settings.general.triggerOnChangedValue(
self.guake.settings.general, "use-scrollbar"
)
# this is needed to initially set the last_terminal_focused,
# one could also call terminal.get_parent().on_terminal_focus()
if not empty:
self.terminal_attached(terminal)
self.hide_tabbar_if_one_tab()
if self.guake:
# Attack background image draw callback to root terminal box
root_terminal_box.connect_after("draw", self.guake.background_image_manager.draw)
return root_terminal_box, page_num, terminal
def hide_tabbar_if_one_tab(self):
"""Hide the tab bar if hide-tabs-if-one-tab is true and there is only one
notebook page"""
if self.guake.settings.general.get_boolean("window-tabbar"):
if self.guake.settings.general.get_boolean("hide-tabs-if-one-tab"):
self.set_property("show-tabs", self.get_n_pages() != 1)
else:
self.set_property("show-tabs", True)
def terminal_spawn(self, directory=None, open_tab_cwd=False):
terminal = GuakeTerminal(self.guake)
terminal.grab_focus()
terminal.connect(
"key-press-event",
lambda x, y: self.guake.accel_group.activate(x, y) if self.guake.accel_group else False,
)
if not isinstance(directory, str):
directory = os.environ["HOME"]
try:
if self.guake.settings.general.get_boolean("open-tab-cwd") or open_tab_cwd:
# Do last focused terminal still alive?
active_terminal = self.get_current_terminal()
if not active_terminal:
# If not alive, can we get any focused terminal?
active_terminal = self.get_focused_terminal()
directory = os.path.expanduser("~")
if active_terminal:
# If found, we will use its directory as new terminal's directory
directory = active_terminal.get_current_directory()
except BaseException:
pass
log.info("Spawning new terminal at %s", directory)
terminal.spawn_sync_pid(directory)
return terminal
def terminal_attached(self, terminal):
terminal.emit("focus", Gtk.DirectionType.TAB_FORWARD)
self.emit("terminal-spawned", terminal, terminal.pid)
def new_page_with_focus(
self,
directory=None,
label=None,
user_set=False,
position=None,
empty=False,
open_tab_cwd=False,
):
box, page_num, terminal = self.new_page(
directory, position=position, empty=empty, open_tab_cwd=open_tab_cwd
)
self.set_current_page(page_num)
if not label:
self.rename_page(page_num, self.guake.compute_tab_title(terminal), False)
else:
self.rename_page(page_num, label, user_set)
if terminal is not None:
terminal.grab_focus()
return box, page_num, terminal
def rename_page(self, page_index, new_text, user_set=False):
"""Rename an already added page by its index. Use user_set to define
if the rename was triggered by the user (eg. rename dialog) or by
an update from the vte (eg. vte:window-title-changed)
"""
page = self.get_nth_page(page_index)
if not getattr(page, "custom_label_set", False) or user_set:
old_label = self.get_tab_label(page)
if isinstance(old_label, TabLabelEventBox):
old_label.set_text(new_text)
else:
label = TabLabelEventBox(self, new_text, self.guake.settings)
label.add_events(Gdk.EventMask.SCROLL_MASK)
label.connect("scroll-event", self.scroll_callback.on_scroll)
self.set_tab_label(page, label)
if user_set:
setattr(page, "custom_label_set", new_text != "-")
def find_tab_index_by_label(self, eventbox):
for index, tab_eventbox in enumerate(self.iter_tabs()):
if eventbox is tab_eventbox:
return index
return -1
def find_page_index_by_terminal(self, terminal):
for index, page in enumerate(self.iter_pages()):
for t in page.iter_terminals():
if t is terminal:
return index
return -1
def get_tab_text_index(self, index):
return self.get_tab_label(self.get_nth_page(index)).get_text()
def get_tab_text_page(self, page):
return self.get_tab_label(page).get_text()
def on_show_preferences(self, user_data):
self.guake.hide()
PrefsDialog(self.guake.settings).show()
def on_show_about(self, user_data):
self.guake.hide()
AboutDialog()
def on_quit(self, user_data):
self.guake.accel_quit()
def on_save_tabs(self, user_data):
self.guake.save_tabs()
def on_restore_tabs(self, user_data):
self.guake.restore_tabs()
def on_restore_tabs_with_dialog(self, user_data):
dialog = Gtk.MessageDialog(
parent=self.guake.window,
flags=Gtk.DialogFlags.MODAL,
buttons=Gtk.ButtonsType.OK_CANCEL,
message_format=_(
"You are going to restore *all* the tabs!\n"
"which means all your terminals & pages "
"will be replaced.\n\nDo you want to continue?"
),
)
dialog.connect("response", self.restore_tabs_dialog_response)
dialog.show()
def restore_tabs_dialog_response(self, widget, response_id):
widget.destroy()
if response_id == Gtk.ResponseType.OK:
self.guake.restore_tabs()
class NotebookManager(GObject.Object):
def __init__(
self,
window,
notebook_parent,
workspaces_enabled,
terminal_spawned_cb,
page_deleted_cb,
):
GObject.Object.__init__(self)
if not GObject.signal_lookup("notebook-created", self):
GObject.signal_new(
"notebook-created",
self,
GObject.SignalFlags.RUN_LAST,
GObject.TYPE_NONE,
(GObject.TYPE_PYOBJECT, GObject.TYPE_INT),
)
self.current_notebook = 0
self.notebooks = {}
self.window = window
self.notebook_parent = notebook_parent
self.terminal_spawned_cb = terminal_spawned_cb
self.page_deleted_cb = page_deleted_cb
if workspaces_enabled and gdk_is_x11_display(Gdk.Display.get_default()):
# NOTE: Wnck didn't support non-X11 display backend, so we need to check if the display
# is X11 or not, if not, it will not able to enable workspace-specific-tab-sets
#
# TODO: Is there anyway to support this in non-X11 display backend?
self.screen = Wnck.Screen.get_default()
self.screen.connect("active-workspace-changed", self.__workspace_changed_cb)
def __workspace_changed_cb(self, screen, previous_workspace):
self.set_workspace(self.screen.get_active_workspace().get_number())
def get_notebook(self, workspace_index: int):
if not self.has_notebook_for_workspace(workspace_index):
self.notebooks[workspace_index] = TerminalNotebook()
self.emit("notebook-created", self.notebooks[workspace_index], workspace_index)
self.notebooks[workspace_index].connect("terminal-spawned", self.terminal_spawned_cb)
self.notebooks[workspace_index].connect("page-deleted", self.page_deleted_cb)
log.info("created fresh notebook for workspace %d", self.current_notebook)
# add a tab if there is none
if not self.notebooks[workspace_index].has_page():
self.notebooks[workspace_index].new_page_with_focus(None)
return self.notebooks[workspace_index]
def get_current_notebook(self):
return self.get_notebook(self.current_notebook)
def has_notebook_for_workspace(self, workspace_index):
return workspace_index in self.notebooks
def set_workspace(self, index: int):
self.notebook_parent.remove(self.get_current_notebook())
self.current_notebook = index
log.info("current workspace is %d", self.current_notebook)
notebook = self.get_current_notebook()
self.notebook_parent.add(notebook)
if self.window.get_property("visible") and notebook.last_terminal_focused is not None:
notebook.last_terminal_focused.grab_focus()
# Restore pending page terminal split
notebook.guake.restore_pending_terminal_split()
# Restore config to workspace
notebook.guake.load_config()
def set_notebooks_tabbar_visible(self, v):
for nb in self.iter_notebooks():
nb.set_tabbar_visible(v)
def get_notebooks(self):
return self.notebooks
def get_terminals(self):
terminals = []
for k in self.notebooks:
terminals += self.notebooks[k].get_terminals()
return terminals
def iter_terminals(self):
for k in self.notebooks:
for t in self.notebooks[k].iter_terminals():
yield t
def get_terminal_by_uuid(self, terminal_uuid):
for t in self.iter_terminals():
if t.uuid == terminal_uuid:
return t
return None
def iter_pages(self):
for k in self.notebooks:
for t in self.notebooks[k].iter_pages():
yield t
def iter_notebooks(self):
for k in self.notebooks:
yield self.notebooks[k]
def get_n_pages(self):
n = 0
for k in self.notebooks:
n += self.notebooks[k].get_n_pages()
return n
def get_n_notebooks(self):
return len(self.notebooks.keys())
def get_running_fg_processes(self):
processes = []
for k in self.notebooks:
processes += self.notebooks[k].get_running_fg_processes()
return processes
| 24,532
|
Python
|
.py
| 551
| 34.404719
| 100
| 0.623446
|
Guake/guake
| 4,406
| 575
| 405
|
GPL-2.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,056
|
globals.py
|
Guake_guake/guake/globals.py
|
# -*- coding: utf-8; -*-
"""
Copyright (C) 2007-2013 Guake authors
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 inspect
import logging
import os
__all__ = [
"ALIGN_BOTTOM",
"ALIGN_CENTER",
"ALIGN_LEFT",
"ALIGN_RIGHT",
"ALIGN_TOP",
"ALWAYS_ON_PRIMARY",
"NAME",
]
log = logging.getLogger(__name__)
def bindtextdomain(app_name, locale_dir=None):
"""
Bind the domain represented by app_name to the locale directory locale_dir.
It has the effect of loading translations, enabling applications for different
languages.
app_name:
a domain to look for translations, typically the name of an application.
locale_dir:
a directory with locales like locale_dir/lang_isocode/LC_MESSAGES/app_name.mo
If omitted or None, then the current binding for app_name is used.
"""
# pylint: disable=import-outside-toplevel
import locale
# pylint: enable=import-outside-toplevel
log.info("Local binding for app '%s', local dir: %s", app_name, locale_dir)
locale.bindtextdomain(app_name, locale_dir)
locale.textdomain(app_name)
def is_run_from_git_workdir():
self_path = os.path.abspath(inspect.getfile(inspect.currentframe()))
return os.path.exists(f"{self_path}.in")
NAME = "guake"
ALIGN_CENTER, ALIGN_LEFT, ALIGN_RIGHT = range(3)
ALIGN_TOP, ALIGN_BOTTOM = range(2)
ALWAYS_ON_PRIMARY = -1
PROMPT_NEVER, PROMPT_PROCESSES, PROMPT_ALWAYS = range(3)
# TODO this is not as fancy as as it could be
# pylint: disable=anomalous-backslash-in-string
TERMINAL_MATCH_TAGS = ("schema", "http", "https", "email", "ftp")
# Beware this is a PRCE (Perl) regular expression, not a Python one!
# Edit: use regex101.com with PCRE syntax
TERMINAL_MATCH_EXPRS = [
r"(news:|telnet:|nntp:|file:\/|https?:|ftps?:|webcal:)\/\/([-[:alnum:]]+"
r"(:[-[:alnum:],?;.:\/!%$^\*&~\"#']+)?\@)?[-[:alnum:]]+(\.[-[:alnum:]]+)*"
r"(:[0-9]{1,5})?(\/[-[:alnum:]_$.+!*(),;:@&=?\/~#%]*[^]'.>) \t\r\n,\\\"])?",
r"(www|ftp)[-[:alnum:]]*\.[-[:alnum:]]+(\.[-[:alnum:]]+)*(:[0-9]{1,5})?"
r"(\/[-[:alnum:]_$.+!*(),;:@&=?\/~#%]*[^]'.>) \t\r\n,\\\"])?",
r"(mailto:)?[-[:alnum:]][-[:alnum:].]*@[-[:alnum:]]+\.[-[:alnum:]]+(\\.[-[:alnum:]]+)*",
]
# tuple (title/quick matcher/filename and line number extractor)
QUICK_OPEN_MATCHERS = [
(
"Python traceback",
r"^\s*File\s\".*\",\sline\s[0-9]+",
r"^\s*File\s\"(.*)\",\sline\s([0-9]+)",
),
(
"Python pytest report",
r"^\s.*\:\:[a-zA-Z0-9\_]+\s",
r"^\s*(.*\:\:[a-zA-Z0-9\_]+)\s",
),
(
"line starts by 'ERROR in Filename:line' pattern (GCC/make). File path should exists.",
r"[a-zA-Z0-9\/\_\-\.\]+\.?[a-zA-Z0-9]+\:[0-9]+",
r"\s.\S[^\s\s].(.*)\:([0-9]+)",
),
(
"line starts by 'Filename:line' pattern (GCC/make). File path should exists.",
r"^\s*[a-zA-Z0-9\/\_\-\.\ ]+\.?[a-zA-Z0-9]+\:[0-9]+",
r"^\s*(.*)\:([0-9]+)",
),
]
# Transparency max level (should be always 100)
MAX_TRANSPARENCY = 100
# Tabs session schema version
TABS_SESSION_SCHEMA_VERSION = 2
# Constants for vte regex matching are documented in the pcre2 api:
# https://www.pcre.org/current/doc/html/pcre2api.html
PCRE2_MULTILINE = 0x00000400
# the urls of the search engine options for the search on web feature.
# Additional engines should be added
ENGINES = {
0: "www.google.com/search?safe=off&q=",
1: "www.duckduckgo.com/",
2: "www.bing.com/search?q=",
3: "www.yandex.com/search?text=",
4: "neeva.com/search?q=",
}
| 4,204
|
Python
|
.py
| 106
| 35.754717
| 95
| 0.633284
|
Guake/guake
| 4,406
| 575
| 405
|
GPL-2.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,057
|
notifier.py
|
Guake_guake/guake/notifier.py
|
# -*- coding: utf-8; -*-
"""
Copyright (C) 2007-2013 Guake authors
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 gi
gi.require_version("Notify", "0.7")
from gi.repository import GLib
from gi.repository import Notify
Notify.init("Guake")
__all__ = ["showMessage"]
def showMessage(brief, body=None, icon=None):
try:
notification = Notify.Notification.new(brief, body, icon)
notification.show()
# pylint: disable=catching-non-exception
except GLib.GError:
pass
# pylint: enable=catching-non-exception
| 1,189
|
Python
|
.py
| 30
| 37
| 66
| 0.767826
|
Guake/guake
| 4,406
| 575
| 405
|
GPL-2.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,058
|
prefs.py
|
Guake_guake/guake/prefs.py
|
# -*- coding: utf-8; -*-
"""
Copyright (C) 2007-2013 Guake authors
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
import os
import re
import shutil
from textwrap import dedent
import gi
gi.require_version("Gtk", "3.0")
gi.require_version("Vte", "2.91") # vte-0.38
from gi.repository import GLib
from gi.repository import Gdk
from gi.repository import Gio
from gi.repository import Gtk
from gi.repository import Vte
from guake.common import ShowableError
from guake.common import get_binaries_from_path
from guake.common import gladefile
from guake.common import hexify_color
from guake.common import pixmapfile
from guake.globals import ALIGN_BOTTOM
from guake.globals import ALIGN_CENTER
from guake.globals import ALIGN_LEFT
from guake.globals import ALIGN_RIGHT
from guake.globals import ALIGN_TOP
from guake.globals import ALWAYS_ON_PRIMARY
from guake.globals import ENGINES
from guake.globals import MAX_TRANSPARENCY
from guake.globals import NAME
from guake.globals import QUICK_OPEN_MATCHERS
from guake.palettes import PALETTES
from guake.paths import AUTOSTART_FOLDER
from guake.paths import LOCALE_DIR
from guake.paths import LOGIN_DESTOP_PATH
from guake.simplegladeapp import SimpleGladeApp
from guake.terminal import GuakeTerminal
from guake.theme import list_all_themes
from guake.theme import select_gtk_theme
# pylint: disable=unsubscriptable-object
log = logging.getLogger(__name__)
# A regular expression to match possible python interpreters when
# filling interpreters combo in preferences (including bpython and ipython)
PYTHONS = re.compile(r"^[a-z]python$|^python\d\.\d$")
# Path to the shells file, it will be used to start to populate
# interpreters combo, see the next variable, its important to fill the
# rest of the combo too.
SHELLS_FILE = "/etc/shells"
# string to show in prefereces dialog for user shell option
USER_SHELL_VALUE = _("<user shell>")
# translating our types to vte types
ERASE_BINDINGS = {
"ASCII DEL": "ascii-delete",
"Escape sequence": "delete-sequence",
"Control-H": "ascii-backspace",
}
HOTKEYS = [
{
"label": _("General"),
"key": "general",
"keys": [
{"key": "show-hide", "label": _("Toggle Guake visibility")},
{"key": "show-focus", "label": _("Show and focus Guake window")},
{"key": "toggle-fullscreen", "label": _("Toggle Fullscreen")},
{
"key": "toggle-hide-on-lose-focus",
"label": _("Toggle Hide on Lose Focus"),
},
{"key": "quit", "label": _("Quit")},
{"key": "reset-terminal", "label": _("Reset terminal")},
{"key": "search-terminal", "label": _("Search terminal")},
],
},
{
"label": _("Tab management"),
"key": "tab",
"keys": [
{"key": "new-tab", "label": _("New tab")},
{"key": "new-tab-home", "label": _("New tab in home directory")},
{"key": "new-tab-cwd", "label": _("New tab in current directory")},
{"key": "close-tab", "label": _("Close tab")},
{"key": "rename-current-tab", "label": _("Rename current tab")},
],
},
{
"label": _("Split management"),
"key": "split",
"keys": [
{"key": "split-tab-vertical", "label": _("Split tab vertical")},
{"key": "split-tab-horizontal", "label": _("Split tab horizontal")},
{"key": "close-terminal", "label": _("Close terminal")},
{"key": "focus-terminal-up", "label": _("Focus terminal above")},
{"key": "focus-terminal-down", "label": _("Focus terminal below")},
{"key": "focus-terminal-left", "label": _("Focus terminal on the left")},
{"key": "focus-terminal-right", "label": _("Focus terminal on the right")},
{
"key": "move-terminal-split-up",
"label": _("Move the terminal split handle up"),
},
{
"key": "move-terminal-split-down",
"label": _("Move the terminal split handle down"),
},
{
"key": "move-terminal-split-right",
"label": _("Move the terminal split handle right"),
},
{
"key": "move-terminal-split-left",
"label": _("Move the terminal split handle left"),
},
],
},
{
"label": _("Navigation"),
"key": "nav",
"keys": [
{"key": "previous-tab", "label": _("Go to previous tab")},
{"key": "previous-tab-alt", "label": _("Go to previous tab (alternative)")},
{"key": "next-tab", "label": _("Go to next tab")},
{"key": "next-tab-alt", "label": _("Go to next tab (alternative)")},
{"key": "move-tab-left", "label": _("Move current tab left")},
{"key": "move-tab-right", "label": _("Move current tab right")},
{"key": "switch-tab1", "label": _("Go to first tab")},
{"key": "switch-tab2", "label": _("Go to second tab")},
{"key": "switch-tab3", "label": _("Go to third tab")},
{"key": "switch-tab4", "label": _("Go to fourth tab")},
{"key": "switch-tab5", "label": _("Go to fifth tab")},
{"key": "switch-tab6", "label": _("Go to sixth tab")},
{"key": "switch-tab7", "label": _("Go to seventh tab")},
{"key": "switch-tab8", "label": _("Go to eighth tab")},
{"key": "switch-tab9", "label": _("Go to ninth tab")},
{"key": "switch-tab10", "label": _("Go to tenth tab")},
{"key": "switch-tab-last", "label": _("Go to last tab")},
],
},
{
"label": _("Appearance"),
"key": "appearance",
"keys": [
{"key": "zoom-out", "label": _("Zoom out")},
{"key": "zoom-in", "label": _("Zoom in")},
{"key": "zoom-in-alt", "label": _("Zoom in (alternative)")},
{"key": "increase-height", "label": _("Increase height")},
{"key": "decrease-height", "label": _("Decrease height")},
{"key": "increase-transparency", "label": _("Increase transparency")},
{"key": "decrease-transparency", "label": _("Decrease transparency")},
{"key": "toggle-transparency", "label": _("Toggle transparency")},
],
},
{
"label": _("Clipboard"),
"key": "clipboard",
"keys": [
{"key": "clipboard-copy", "label": _("Copy text to clipboard")},
{"key": "clipboard-paste", "label": _("Paste text from clipboard")},
{"key": "select-all", "label": _("Select all")},
],
},
{
"label": _("Extra features"),
"key": "extra",
"keys": [
{"key": "search-on-web", "label": _("Search selected text on web")},
{
"key": "open-link-under-terminal-cursor",
"label": _("Open URL under terminal cursor"),
},
],
},
]
html_escape_table = {
"&": "&",
'"': """,
"'": "'",
">": ">",
"<": "<",
}
HOTKET_MODEL_INDEX_DCONF = 0
HOTKET_MODEL_INDEX_LABEL = 1
HOTKET_MODEL_INDEX_HUMAN_ACCEL = 2
HOTKET_MODEL_INDEX_ACCEL = 3
def html_escape(text):
"""Produce entities within text."""
return "".join(html_escape_table.get(c, c) for c in text)
def refresh_user_start(settings):
if not AUTOSTART_FOLDER or not LOGIN_DESTOP_PATH:
return
if settings.general.get_boolean("start-at-login"):
autostart_path = os.path.expanduser(AUTOSTART_FOLDER)
os.makedirs(autostart_path, exist_ok=True)
shutil.copyfile(
os.path.join(LOGIN_DESTOP_PATH, "autostart-guake.desktop"),
os.path.join(os.path.expanduser(AUTOSTART_FOLDER), "guake.desktop"),
)
else:
desktop_file = os.path.join(os.path.expanduser(AUTOSTART_FOLDER), "guake.desktop")
if os.path.exists(desktop_file):
os.remove(desktop_file)
class PrefsCallbacks:
"""Holds callbacks that will be used in the PrefsDialg class."""
def __init__(self, prefDlg):
self.prefDlg = prefDlg
self.settings = prefDlg.settings
# general tab
def on_restore_tabs_startup_toggled(self, chk):
"""Changes the activity of restore-tabs-startup in dconf"""
self.settings.general.set_boolean("restore-tabs-startup", chk.get_active())
def on_restore_tabs_notify_toggled(self, chk):
"""Changes the activity of restore-tabs-notify in dconf"""
self.settings.general.set_boolean("restore-tabs-notify", chk.get_active())
def on_save_tabs_when_changed_toggled(self, chk):
"""Changes the activity of save-tabs-when-changed in dconf"""
self.settings.general.set_boolean("save-tabs-when-changed", chk.get_active())
def on_load_guake_yml_toggled(self, chk):
"""Changes the activity of load-guake-yml"""
self.settings.general.set_boolean("load-guake-yml", chk.get_active())
def on_default_shell_changed(self, combo):
"""Changes the activity of default_shell in dconf"""
citer = combo.get_active_iter()
if not citer:
return
shell = combo.get_model().get_value(citer, 0)
# we unset the value (restore to default) when user chooses to use
# user shell as guake shell interpreter.
if shell == USER_SHELL_VALUE:
self.settings.general.reset("default-shell")
else:
self.settings.general.set_string("default-shell", shell)
def on_use_login_shell_toggled(self, chk):
"""Changes the activity of use_login_shell in dconf"""
self.settings.general.set_boolean("use-login-shell", chk.get_active())
def on_open_tab_cwd_toggled(self, chk):
"""Changes the activity of open_tab_cwd in dconf"""
self.settings.general.set_boolean("open-tab-cwd", chk.get_active())
def on_use_trayicon_toggled(self, chk):
"""Changes the activity of use_trayicon in dconf"""
self.settings.general.set_boolean("use-trayicon", chk.get_active())
def on_use_popup_toggled(self, chk):
"""Changes the activity of use_popup in dconf"""
self.settings.general.set_boolean("use-popup", chk.get_active())
def on_workspace_specific_tab_sets_toggled(self, chk):
"""Sets the 'workspace-specific-tab-sets' property in dconf"""
self.settings.general.set_boolean("workspace-specific-tab-sets", chk.get_active())
def on_prompt_on_quit_toggled(self, chk):
"""Set the `prompt on quit' property in dconf"""
self.settings.general.set_boolean("prompt-on-quit", chk.get_active())
def on_prompt_on_close_tab_changed(self, combo):
"""Set the `prompt_on_close_tab' property in dconf"""
self.settings.general.set_int("prompt-on-close-tab", combo.get_active())
def on_search_engine_changed(self, combo):
"""
Sets the 'search-engine' value in dnonf.
Also controls the editability of 'custom_search' input
"""
custom_search = self.prefDlg.get_widget("custom_search")
# if 'Custom' is selected make the search engine input editable
if combo.get_active() not in ENGINES:
custom_search.set_sensitive(True)
else:
# make read-only
custom_search.set_sensitive(False)
self.settings.general.set_int("search-engine", combo.get_active())
def on_custom_search_changed(self, edt):
"""Sets the 'custom-search-engine' property in dconf"""
self.settings.general.set_string("custom-search-engine", edt.get_text())
def on_gtk_theme_name_changed(self, combo):
"""Set the `gtk_theme_name' property in dconf"""
citer = combo.get_active_iter()
if not citer:
return
theme_name = combo.get_model().get_value(citer, 0)
self.settings.general.set_string("gtk-theme-name", theme_name)
select_gtk_theme(self.settings)
def on_gtk_prefer_dark_theme_toggled(self, chk):
"""Set the `gtk_prefer_dark_theme' property in dconf"""
self.settings.general.set_boolean("gtk-prefer-dark-theme", chk.get_active())
select_gtk_theme(self.settings)
def on_gtk_use_system_default_theme_toggled(self, chk):
"""Set the `gtk_prefer_dark_theme' property in dconf"""
self.settings.general.set_boolean("gtk-use-system-default-theme", chk.get_active())
select_gtk_theme(self.settings)
def on_window_ontop_toggled(self, chk):
"""Changes the activity of window_ontop in dconf"""
self.settings.general.set_boolean("window-ontop", chk.get_active())
def on_tab_ontop_toggled(self, chk):
"""Changes the activity of tab_ontop in dconf"""
self.settings.general.set_boolean("tab-ontop", chk.get_active())
def on_new_tab_after_toggled(self, chk):
"""Changes the activity of new_tab_after in dconf"""
self.settings.general.set_boolean("new-tab-after", chk.get_active())
def on_quick_open_enable_toggled(self, chk):
"""Changes the activity of quick_open_enable in dconf"""
self.settings.general.set_boolean("quick-open-enable", chk.get_active())
def on_quick_open_in_current_terminal_toggled(self, chk):
self.settings.general.set_boolean("quick-open-in-current-terminal", chk.get_active())
def on_startup_script_changed(self, edt):
self.settings.general.set_string("startup-script", edt.get_text())
def on_window_refocus_toggled(self, chk):
"""Changes the activity of window_refocus in dconf"""
self.settings.general.set_boolean("window-refocus", chk.get_active())
def on_window_losefocus_toggled(self, chk):
"""Changes the activity of window_losefocus in dconf"""
self.settings.general.set_boolean("window-losefocus", chk.get_active())
def on_lazy_lose_focus_toggled(self, chk):
"""Changes the activity of lazy_lose_focus in dconf"""
self.settings.general.set_boolean("lazy-losefocus", chk.get_active())
def on_quick_open_command_line_changed(self, edt):
self.settings.general.set_string("quick-open-command-line", edt.get_text())
def on_hook_show_changed(self, edt):
self.settings.hooks.set_string("show", edt.get_text())
def on_window_tabbar_toggled(self, chk):
"""Changes the activity of window_tabbar in dconf"""
self.settings.general.set_boolean("window-tabbar", chk.get_active())
def on_fullscreen_hide_tabbar_toggled(self, chk):
"""Changes the activity of fullscreen_hide_tabbar in dconf"""
self.settings.general.set_boolean("fullscreen-hide-tabbar", chk.get_active())
def on_hide_tabs_if_one_tab_toggled(self, chk):
"""Changes the activity of hide_tabs_if_one_tab in dconf"""
self.settings.general.set_boolean("hide-tabs-if-one-tab", chk.get_active())
def on_start_fullscreen_toggled(self, chk):
"""Changes the activity of start_fullscreen in dconf"""
self.settings.general.set_boolean("start-fullscreen", chk.get_active())
def on_start_at_login_toggled(self, chk):
"""Changes the activity of start_at_login in dconf"""
self.settings.general.set_boolean("start-at-login", chk.get_active())
refresh_user_start(self.settings)
def on_use_vte_titles_toggled(self, chk):
"""Save `use_vte_titles` property value in dconf"""
self.settings.general.set_boolean("use-vte-titles", chk.get_active())
def on_set_window_title_toggled(self, chk):
"""Save `set_window_title` property value in dconf"""
self.settings.general.set_boolean("set-window-title", chk.get_active())
def on_copy_on_select_toggled(self, chk):
"""Changes the value of copy_on_select in dconf"""
self.settings.general.set_boolean("copy-on-select", chk.get_active())
def on_tab_name_display_changed(self, combo):
"""Save `display-tab-names` property value in dconf"""
self.settings.general.set_int("display-tab-names", combo.get_active())
def on_max_tab_name_length_changed(self, spin):
"""Changes the value of max_tab_name_length in dconf"""
val = int(spin.get_value())
self.settings.general.set_int("max-tab-name-length", val)
self.prefDlg.update_vte_subwidgets_states()
def on_mouse_display_toggled(self, chk):
"""Set the 'appear on mouse display' preference in dconf. This
property supercedes any value stored in display_n.
"""
self.settings.general.set_boolean("mouse-display", chk.get_active())
def on_right_align_toggled(self, chk):
"""set the horizontal alignment setting."""
v = chk.get_active()
self.settings.general.set_int("window-halignment", 1 if v else 0)
def on_bottom_align_toggled(self, chk):
"""set the vertical alignment setting."""
v = chk.get_active()
self.settings.general.set_int("window-valignment", ALIGN_BOTTOM if v else ALIGN_TOP)
def on_display_n_changed(self, combo):
"""Set the destination display in dconf."""
i = combo.get_active_iter()
if not i:
return
model = combo.get_model()
first_item_path = model.get_path(model.get_iter_first())
if model.get_path(i) == first_item_path:
val_int = ALWAYS_ON_PRIMARY
else:
val = model.get_value(i, 0)
val_int = int(val.split()[0]) # extracts 1 from '1' or from '1 (primary)'
self.settings.general.set_int("display-n", val_int)
def on_window_height_value_changed(self, hscale):
"""Changes the value of window_height in dconf"""
val = hscale.get_value()
self.settings.general.set_int("window-height", int(val))
def on_window_width_value_changed(self, wscale):
"""Changes the value of window_width in dconf"""
val = wscale.get_value()
self.settings.general.set_int("window-width", int(val))
def on_window_halign_value_changed(self, halign_button):
"""Changes the value of window_halignment in dconf"""
which_align = {
"radiobutton_align_left": ALIGN_LEFT,
"radiobutton_align_right": ALIGN_RIGHT,
"radiobutton_align_center": ALIGN_CENTER,
}
if halign_button.get_active():
self.settings.general.set_int(
"window-halignment", which_align[halign_button.get_name()]
)
self.prefDlg.get_widget("window_horizontal_displacement").set_sensitive(
which_align[halign_button.get_name()] != ALIGN_CENTER
)
def on_use_audible_bell_toggled(self, chk):
"""Changes the value of use_audible_bell in dconf"""
self.settings.general.set_boolean("use-audible-bell", chk.get_active())
# scrolling tab
def on_use_scrollbar_toggled(self, chk):
"""Changes the activity of use_scrollbar in dconf"""
self.settings.general.set_boolean("use-scrollbar", chk.get_active())
def on_history_size_value_changed(self, spin):
"""Changes the value of history_size in dconf"""
val = int(spin.get_value())
self.settings.general.set_int("history-size", val)
self._update_history_widgets()
def on_infinite_history_toggled(self, chk):
self.settings.general.set_boolean("infinite-history", chk.get_active())
self._update_history_widgets()
def _update_history_widgets(self):
infinite = self.prefDlg.get_widget("infinite_history").get_active()
self.prefDlg.get_widget("history_size").set_sensitive(not infinite)
def on_scroll_output_toggled(self, chk):
"""Changes the activity of scroll_output in dconf"""
self.settings.general.set_boolean("scroll-output", chk.get_active())
def on_scroll_keystroke_toggled(self, chk):
"""Changes the activity of scroll_keystroke in dconf"""
self.settings.general.set_boolean("scroll-keystroke", chk.get_active())
# appearance tab
def on_use_default_font_toggled(self, chk):
"""Changes the activity of use_default_font in dconf"""
self.settings.general.set_boolean("use-default-font", chk.get_active())
def on_allow_bold_toggled(self, chk):
"""Changes the value of allow_bold in dconf"""
self.settings.styleFont.set_boolean("allow-bold", chk.get_active())
def on_bold_is_bright_toggled(self, chk):
"""Changes the value of bold_is_bright in dconf"""
self.settings.styleFont.set_boolean("bold-is-bright", chk.get_active())
def on_cell_height_scale_value_changed(self, scale):
value = scale.get_value()
self.settings.styleFont.set_double("cell-height-scale", value)
def on_cell_width_scale_value_changed(self, scale):
value = scale.get_value()
self.settings.styleFont.set_double("cell-width-scale", value)
def on_font_style_font_set(self, fbtn):
"""Changes the value of font_style in dconf"""
self.settings.styleFont.set_string("style", fbtn.get_font_name())
def on_background_image_file_chooser_file_changed(self, fc):
allowed_extensions = (
".jpg",
".jpeg",
".png",
".gif",
) # only allow files with these extensions
self.settings.general.set_string(
"background-image-file",
fc.get_filename()
if fc.get_filename() and fc.get_filename().endswith(allowed_extensions)
else "",
)
def on_background_image_file_remove_clicked(self, btn):
filechooser = self.prefDlg.get_widget("background_image_filechooser")
filechooser.unselect_all()
self.on_background_image_file_chooser_file_changed(filechooser)
def on_background_image_layout_mode_changed(self, combo):
val = combo.get_active()
self.settings.general.set_int("background-image-layout-mode", val)
def on_transparency_value_changed(self, hscale):
"""Changes the value of background_transparency in dconf"""
value = hscale.get_value()
self.prefDlg.set_colors_from_settings()
self.settings.styleBackground.set_int("transparency", MAX_TRANSPARENCY - int(value))
# compatibility tab
def on_backspace_binding_changed(self, combo):
"""Changes the value of compat_backspace in dconf"""
val = combo.get_active_text()
self.settings.general.set_string("compat-backspace", ERASE_BINDINGS[val])
def on_delete_binding_changed(self, combo):
"""Changes the value of compat_delete in dconf"""
val = combo.get_active_text()
self.settings.general.set_string("compat-delete", ERASE_BINDINGS[val])
def on_custom_command_file_chooser_file_changed(self, filechooser):
self.settings.general.set_string("custom-command-file", filechooser.get_filename())
def toggle_prompt_on_quit_sensitivity(self, combo):
self.prefDlg.toggle_prompt_on_quit_sensitivity(combo)
def toggle_style_sensitivity(self, chk):
self.prefDlg.toggle_style_sensitivity(chk)
def toggle_use_theme_sensitivity(self, chk):
self.prefDlg.toggle_use_theme_sensitivity(chk)
def toggle_use_font_background_sensitivity(self, chk):
self.prefDlg.toggle_use_font_background_sensitivity(chk)
def toggle_display_n_sensitivity(self, chk):
self.prefDlg.toggle_display_n_sensitivity(chk)
def toggle_show_tabbar_sensitivity(self, chk):
self.prefDlg.toggle_show_tabbar_sensitivity(chk)
def toggle_hide_on_lose_focus_sensitivity(self, chk):
self.prefDlg.toggle_hide_on_lose_focus_sensitivity(chk)
def toggle_quick_open_command_line_sensitivity(self, chk):
self.prefDlg.toggle_quick_open_command_line_sensitivity(chk)
def toggle_use_vte_titles(self, chk):
self.prefDlg.toggle_use_vte_titles(chk)
def update_vte_subwidgets_states(self):
self.prefDlg.update_vte_subwidgets_states()
def on_reset_compat_defaults_clicked(self, btn):
self.prefDlg.on_reset_compat_defaults_clicked(btn)
def on_palette_name_changed(self, combo):
self.prefDlg.on_palette_name_changed(combo)
def on_cursor_shape_changed(self, combo):
self.prefDlg.on_cursor_shape_changed(combo)
def on_blink_cursor_toggled(self, chk):
self.prefDlg.on_blink_cursor_toggled(chk)
def on_palette_color_set(self, btn):
self.prefDlg.on_palette_color_set(btn)
def on_window_vertical_displacement_value_changed(self, spin):
"""Changes the value of window-vertical-displacement"""
self.settings.general.set_int("window-vertical-displacement", int(spin.get_value()))
def on_window_horizontal_displacement_value_changed(self, spin):
"""Changes the value of window-horizontal-displacement"""
self.settings.general.set_int("window-horizontal-displacement", int(spin.get_value()))
def reload_erase_combos(self, btn=None):
self.prefDlg.reload_erase_combos(btn)
def gtk_widget_destroy(self, btn):
self.prefDlg.gtk_widget_destroy(btn)
class PrefsDialog(SimpleGladeApp):
"""The Guake Preferences dialog."""
def __init__(self, settings):
"""Setup the preferences dialog interface, loading images,
adding filters to file choosers and connecting some signals.
"""
self.hotkey_alread_used = False
self.store = None
super().__init__(gladefile("prefs.glade"), root="config-window")
style_provider = Gtk.CssProvider()
css_data = dedent(
"""
.monospace{
font-family: monospace;
}
"""
).encode()
style_provider.load_from_data(css_data)
Gtk.StyleContext.add_provider_for_screen(
Gdk.Screen.get_default(),
style_provider,
Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION,
)
self.get_widget("quick_open_command_line").get_style_context().add_class("monospace")
self.get_widget("quick_open_supported_patterns").get_style_context().add_class("monospace")
self.settings = settings
self.add_callbacks(PrefsCallbacks(self))
# window cleanup handler
self.window = self.get_widget("config-window")
self.get_widget("config-window").connect("destroy", self.on_destroy)
# images
ipath = pixmapfile("guake-notification.png")
self.get_widget("image_logo").set_from_file(ipath)
ipath = pixmapfile("quick-open.png")
self.get_widget("image_quick_open").set_from_file(ipath)
# Model format:
# 0: the keybinding path in gsettings (str, hidden),
# 1: label (str)
# 2: human readable accelerator (str)
# 3: gtk accelerator (str, hidden)
self.store = Gtk.TreeStore(str, str, str, str)
treeview = self.get_widget("treeview-keys")
treeview.set_model(self.store)
treeview.set_rules_hint(True)
treeview.connect("button-press-event", self.start_editing)
treeview.set_activate_on_single_click(True)
renderer = Gtk.CellRendererText()
column = Gtk.TreeViewColumn(_("Action"), renderer, text=1)
column.set_property("expand", True)
treeview.append_column(column)
renderer = Gtk.CellRendererAccel()
renderer.set_property("editable", True)
renderer.set_property("accel-mode", 1)
renderer.connect("accel-edited", self.on_accel_edited)
renderer.connect("accel-cleared", self.on_accel_cleared)
column = Gtk.TreeViewColumn(_("Shortcut"), renderer, text=2)
column.pack_start(renderer, True)
column.set_property("expand", False)
column.add_attribute(renderer, "accel-mods", 0)
column.add_attribute(renderer, "accel-key", 1)
treeview.append_column(column)
class fake_guake:
pass
fg = fake_guake()
fg.window = self.window
fg.settings = self.settings
self.demo_terminal = GuakeTerminal(fg)
self.demo_terminal_box = self.get_widget("demo_terminal_box")
self.demo_terminal_box.add(self.demo_terminal)
pid = self.spawn_sync_pid(None, self.demo_terminal)
self.demo_terminal.pid = pid
self.settings.general.bind(
"tab-close-buttons",
self.get_widget("tab-close-buttons"),
"active",
Gio.SettingsBindFlags.DEFAULT,
)
self.populate_shell_combo()
self.populate_keys_tree()
self.populate_display_n()
self.populate_gtk_theme_names()
self.load_configs()
self.get_widget("config-window").hide()
def spawn_sync_pid(self, directory=None, terminal=None):
argv = []
user_shell = self.settings.general.get_string("default-shell")
if user_shell and os.path.exists(user_shell):
argv.append(user_shell)
else:
argv.append(os.environ["SHELL"])
login_shell = self.settings.general.get_boolean("use-login-shell")
if login_shell:
argv.append("--login")
if isinstance(directory, str):
wd = directory
else:
wd = os.environ["HOME"]
pid = terminal.spawn_sync(
Vte.PtyFlags.DEFAULT,
wd,
argv,
[],
GLib.SpawnFlags.DO_NOT_REAP_CHILD,
None,
None,
None,
)
try:
tuple_type = gi._gi.ResultTuple # pylint: disable=c-extension-no-member
except: # pylint: disable=bare-except
tuple_type = tuple
if isinstance(pid, (tuple, tuple_type)):
# Return a tuple in 2.91
# https://lazka.github.io/pgi-docs/Vte-2.91/classes/Terminal.html#Vte.Terminal.spawn_sync
pid = pid[1]
if not isinstance(pid, int):
raise TypeError("pid must be an int")
return pid
def show(self):
"""Calls the main window show_all method and presents the
window in the desktop.
"""
self.get_widget("config-window").show_all()
self.get_widget("config-window").present()
def hide(self):
"""Calls the main window hide function."""
self.get_widget("config-window").hide()
def on_destroy(self, window):
self.demo_terminal.kill()
self.demo_terminal.destroy()
def toggle_prompt_on_quit_sensitivity(self, combo):
"""If toggle_on_close_tabs is set to 2 (Always), prompt_on_quit has no
effect.
"""
self.get_widget("prompt_on_quit").set_sensitive(combo.get_active() != 2)
def toggle_style_sensitivity(self, chk):
"""If the user chooses to use the gnome default font
configuration it means that he will not be able to use the
font selector.
"""
self.get_widget("font_style").set_sensitive(not chk.get_active())
def toggle_use_theme_sensitivity(self, chk):
"""If the user chooses to use the gnome default theme
configuration it means that he will not be able to use the
theme selector.
"""
self.get_widget("gtk_theme_name").set_sensitive(not chk.get_active())
self.get_widget("gtk_prefer_dark_theme").set_sensitive(not chk.get_active())
def toggle_use_font_background_sensitivity(self, chk):
"""If the user chooses to use the gnome default font
configuration it means that he will not be able to use the
font selector.
"""
self.get_widget("palette_16").set_sensitive(chk.get_active())
self.get_widget("palette_17").set_sensitive(chk.get_active())
def toggle_hide_on_lose_focus_sensitivity(self, chk):
"""If the user chooses to not hide Guake on focus loss, lazy hiding on focus
loss will do nothing.
"""
self.get_widget("lazy_lose_focus").set_sensitive(chk.get_active())
def toggle_show_tabbar_sensitivity(self, chk):
"""If the user chooses to not show the tab bar, it means that they
cannot see the tab bar regardless of what other tab bar options say.
"""
self.get_widget("fullscreen_hide_tabbar").set_sensitive(chk.get_active())
self.get_widget("hide_tabs_if_one_tab").set_sensitive(chk.get_active())
def toggle_display_n_sensitivity(self, chk):
"""When the user unchecks 'on mouse display', the option to select an
alternate display should be enabled.
"""
self.get_widget("display_n").set_sensitive(not chk.get_active())
def toggle_quick_open_command_line_sensitivity(self, chk):
"""When the user unchecks 'enable quick open', the command line should be disabled"""
self.get_widget("quick_open_command_line").set_sensitive(chk.get_active())
self.get_widget("quick_open_in_current_terminal").set_sensitive(chk.get_active())
def toggle_use_vte_titles(self, chk):
"""When vte titles aren't used, there is nothing to abbreviate"""
self.update_vte_subwidgets_states()
def update_vte_subwidgets_states(self):
do_use_vte_titles = self.get_widget("use_vte_titles").get_active()
self.get_widget("tab_name_display").set_sensitive(do_use_vte_titles)
self.get_widget("lbl_tab_name_display").set_sensitive(do_use_vte_titles)
self.get_widget("max_tab_name_length").set_sensitive(do_use_vte_titles)
self.get_widget("lbl_max_tab_name_length").set_sensitive(do_use_vte_titles)
def on_reset_compat_defaults_clicked(self, bnt):
"""Reset default values to compat_{backspace,delete} dconf
keys. The default values are retrivied from the guake.schemas
file.
"""
self.settings.general.reset("compat-backspace")
self.settings.general.reset("compat-delete")
self.reload_erase_combos()
def on_palette_name_changed(self, combo):
"""Changes the value of palette in dconf"""
palette_name = combo.get_active_text()
if palette_name not in PALETTES:
return
self.settings.styleFont.set_string("palette", PALETTES[palette_name])
self.settings.styleFont.set_string("palette-name", palette_name)
self.set_palette_colors(PALETTES[palette_name])
self.update_demo_palette(PALETTES[palette_name])
def on_cursor_shape_changed(self, combo):
"""Changes the value of cursor_shape in dconf"""
index = combo.get_active()
self.settings.style.set_int("cursor-shape", index)
def on_blink_cursor_toggled(self, chk):
"""Changes the value of blink_cursor in dconf"""
self.settings.style.set_int("cursor-blink-mode", chk.get_active())
def on_palette_color_set(self, btn):
"""Changes the value of palette in dconf"""
palette = []
for i in range(18):
palette.append(hexify_color(self.get_widget(f"palette_{i}").get_color()))
palette = ":".join(palette)
self.settings.styleFont.set_string("palette", palette)
self.settings.styleFont.set_string("palette-name", _("Custom"))
self.set_palette_name("Custom")
self.update_demo_palette(palette)
# this methods should be moved to the GuakeTerminal class FROM HERE
def set_palette_name(self, palette_name):
"""If the given palette matches an existing one, shows it in the
combobox
"""
combo = self.get_widget("palette_name")
found = False
log.debug("wanting palette: %r", palette_name)
for i in combo.get_model():
if i[0] == palette_name:
combo.set_active_iter(i.iter)
found = True
break
if not found:
combo.set_active(self.custom_palette_index)
def update_demo_palette(self, palette):
self.set_colors_from_settings()
def set_colors_from_settings(self):
transparency = self.settings.styleBackground.get_int("transparency")
colorRGBA = Gdk.RGBA(0, 0, 0, 0)
palette_list = []
for color in self.settings.styleFont.get_string("palette").split(":"):
colorRGBA.parse(color)
palette_list.append(colorRGBA.copy())
if len(palette_list) > 16:
bg_color = palette_list[17]
else:
bg_color = Gdk.RGBA(255, 255, 255, 0)
bg_color.alpha = 1 / 100 * transparency
if len(palette_list) > 16:
font_color = palette_list[16]
else:
font_color = Gdk.RGBA(0, 0, 0, 0)
self.demo_terminal.set_color_foreground(font_color)
self.demo_terminal.set_color_bold(font_color)
self.demo_terminal.set_colors(font_color, bg_color, palette_list[:16])
# TO HERE (see above)
def fill_palette_names(self):
combo = self.get_widget("palette_name")
for palette in sorted(PALETTES):
combo.append_text(palette)
self.custom_palette_index = len(PALETTES)
combo.append_text(_("Custom"))
def set_cursor_shape(self, shape_index):
self.get_widget("cursor_shape").set_active(shape_index)
def set_cursor_blink_mode(self, mode_index):
self.get_widget("cursor_blink_mode").set_active(mode_index)
def set_palette_colors(self, palette):
"""Updates the color buttons with the given palette"""
palette = palette.split(":")
for i, pal in enumerate(palette):
x, color = Gdk.Color.parse(pal)
self.get_widget(f"palette_{i}").set_color(color)
def reload_erase_combos(self, btn=None):
"""Read from dconf the value of compat_{backspace,delete} vars
and select the right option in combos.
"""
# backspace erase binding
combo = self.get_widget("backspace-binding-combobox")
binding = self.settings.general.get_string("compat-backspace")
for i in combo.get_model():
if ERASE_BINDINGS.get(i[0]) == binding:
combo.set_active_iter(i.iter)
break
# delete erase binding
combo = self.get_widget("delete-binding-combobox")
binding = self.settings.general.get_string("compat-delete")
for i in combo.get_model():
if ERASE_BINDINGS.get(i[0]) == binding:
combo.set_active_iter(i.iter)
break
def _load_hooks_settings(self):
"""load hooks settings"""
log.debug("executing _load_hooks_settings")
hook_show_widget = self.get_widget("hook_show")
hook_show_setting = self.settings.hooks.get_string("show")
if None not in (hook_show_widget, hook_show_setting):
hook_show_widget.set_text(hook_show_setting)
def _load_default_shell_settings(self):
combo = self.get_widget("default_shell")
# get the value for defualt shell. If unset, set to USER_SHELL_VALUE.
value = self.settings.general.get_string("default-shell") or USER_SHELL_VALUE
for i in combo.get_model():
if i[0] == value:
combo.set_active_iter(i.iter)
break
def _load_screen_settings(self):
"""Load screen settings"""
# display number / use primary display
combo = self.get_widget("display_n")
dest_screen = self.settings.general.get_int("display-n")
# If Guake is configured to use a screen that is not currently attached,
# default to 'primary display' option.
screen = self.get_widget("config-window").get_screen()
n_screens = screen.get_n_monitors()
if dest_screen > n_screens - 1:
self.settings.general.set_boolean("mouse-display", False)
dest_screen = screen.get_primary_monitor()
self.settings.general.set_int("display-n", dest_screen)
if dest_screen == ALWAYS_ON_PRIMARY:
first_item = combo.get_model().get_iter_first()
combo.set_active_iter(first_item)
else:
seen_first = False # first item "always on primary" is special
for i in combo.get_model():
if seen_first:
i_int = int(i[0].split()[0]) # extracts 1 from '1' or from '1 (primary)'
if i_int == dest_screen:
combo.set_active_iter(i.iter)
else:
seen_first = True
def load_configs(self):
"""Load configurations for all widgets in General, Scrolling
and Appearance tabs from dconf.
"""
self._load_default_shell_settings()
# restore tabs startup
value = self.settings.general.get_boolean("restore-tabs-startup")
self.get_widget("restore-tabs-startup").set_active(value)
# restore tabs notify
value = self.settings.general.get_boolean("restore-tabs-notify")
self.get_widget("restore-tabs-notify").set_active(value)
# save tabs when changed
value = self.settings.general.get_boolean("save-tabs-when-changed")
self.get_widget("save-tabs-when-changed").set_active(value)
# save tabs when changed
value = self.settings.general.get_boolean("load-guake-yml")
self.get_widget("load-guake-yml").set_active(value)
# login shell
value = self.settings.general.get_boolean("use-login-shell")
self.get_widget("use_login_shell").set_active(value)
# tray icon
value = self.settings.general.get_boolean("use-trayicon")
self.get_widget("use_trayicon").set_active(value)
# popup
value = self.settings.general.get_boolean("use-popup")
self.get_widget("use_popup").set_active(value)
# workspace-specific tab sets
value = self.settings.general.get_boolean("workspace-specific-tab-sets")
self.get_widget("workspace-specific-tab-sets").set_active(value)
# prompt on quit
value = self.settings.general.get_boolean("prompt-on-quit")
self.get_widget("prompt_on_quit").set_active(value)
# prompt on close_tab
value = self.settings.general.get_int("prompt-on-close-tab")
self.get_widget("prompt_on_close_tab").set_active(value)
self.get_widget("prompt_on_quit").set_sensitive(value != 2)
# search engine
value = self.settings.general.get_int("search-engine")
custom_search = self.get_widget("custom_search")
custom_search.set_text(self.settings.general.get_string("custom-search-engine"))
self.get_widget("search_engine_select").set_active(value)
# if 'Custom' is selected make the search engine input editable
if value not in ENGINES:
# make read-only
custom_search.set_sensitive(True)
else:
custom_search.set_sensitive(False)
# use system theme
value = self.settings.general.get_boolean("gtk-use-system-default-theme")
self.get_widget("gtk_use_system_default_theme").set_active(value)
# gtk theme name
value = self.settings.general.get_string("gtk-theme-name")
combo = self.get_widget("gtk_theme_name")
for i in combo.get_model():
if i[0] == value:
combo.set_active_iter(i.iter)
break
# prefer gtk dark theme
value = self.settings.general.get_boolean("gtk-prefer-dark-theme")
self.get_widget("gtk_prefer_dark_theme").set_active(value)
# ontop
value = self.settings.general.get_boolean("window-ontop")
self.get_widget("window_ontop").set_active(value)
# tab ontop
value = self.settings.general.get_boolean("tab-ontop")
self.get_widget("tab_ontop").set_active(value)
# refocus
value = self.settings.general.get_boolean("window-refocus")
self.get_widget("window_refocus").set_active(value)
# losefocus
value = self.settings.general.get_boolean("window-losefocus")
self.get_widget("window_losefocus").set_active(value)
# lazy lose focus
value = self.settings.general.get_boolean("lazy-losefocus")
self.get_widget("lazy_lose_focus").set_active(value)
# use VTE titles
value = self.settings.general.get_boolean("use-vte-titles")
self.get_widget("use_vte_titles").set_active(value)
# set window title
value = self.settings.general.get_boolean("set-window-title")
self.get_widget("set_window_title").set_active(value)
# set tab name display method
self.get_widget("tab_name_display").set_sensitive(value)
value = self.settings.general.get_int("display-tab-names")
self.get_widget("tab_name_display").set_active(value)
# max tab name length
value = self.settings.general.get_int("max-tab-name-length")
self.get_widget("max_tab_name_length").set_value(value)
self.update_vte_subwidgets_states()
value = self.settings.general.get_int("window-height")
self.get_widget("window_height").set_value(value)
value = self.settings.general.get_int("window-width")
self.get_widget("window_width").set_value(value)
# window displacements
value = self.settings.general.get_int("window-vertical-displacement")
self.get_widget("window_vertical_displacement").set_value(value)
value = self.settings.general.get_int("window-horizontal-displacement")
self.get_widget("window_horizontal_displacement").set_value(value)
value = self.settings.general.get_int("window-halignment")
which_button = {
ALIGN_RIGHT: "radiobutton_align_right",
ALIGN_LEFT: "radiobutton_align_left",
ALIGN_CENTER: "radiobutton_align_center",
}
self.get_widget(which_button[value]).set_active(True)
self.get_widget("window_horizontal_displacement").set_sensitive(value != ALIGN_CENTER)
value = self.settings.general.get_boolean("open-tab-cwd")
self.get_widget("open_tab_cwd").set_active(value)
# tab bar
value = self.settings.general.get_boolean("window-tabbar")
self.get_widget("window_tabbar").set_active(value)
# fullscreen hide tabbar
value = self.settings.general.get_boolean("fullscreen-hide-tabbar")
self.get_widget("fullscreen_hide_tabbar").set_active(value)
# hide tabbar if only one tab
value = self.settings.general.get_boolean("hide-tabs-if-one-tab")
self.get_widget("hide_tabs_if_one_tab").set_active(value)
# start fullscreen
value = self.settings.general.get_boolean("start-fullscreen")
self.get_widget("start_fullscreen").set_active(value)
# start at GNOME login
value = self.settings.general.get_boolean("start-at-login")
self.get_widget("start_at_login").set_active(value)
# use audible bell
value = self.settings.general.get_boolean("use-audible-bell")
self.get_widget("use_audible_bell").set_active(value)
self._load_screen_settings()
value = self.settings.general.get_boolean("quick-open-enable")
self.get_widget("quick_open_enable").set_active(value)
self.get_widget("quick_open_command_line").set_sensitive(value)
self.get_widget("quick_open_in_current_terminal").set_sensitive(value)
text = Gtk.TextBuffer()
text = self.get_widget("quick_open_supported_patterns").get_buffer()
for title, matcher, _useless in QUICK_OPEN_MATCHERS:
text.insert_at_cursor(f"{title}: {matcher}\n")
self.get_widget("quick_open_supported_patterns").set_buffer(text)
value = self.settings.general.get_string("quick-open-command-line")
if value is None:
value = "subl %(file_path)s:%(line_number)s"
self.get_widget("quick_open_command_line").set_text(value)
value = self.settings.general.get_boolean("quick-open-in-current-terminal")
self.get_widget("quick_open_in_current_terminal").set_active(value)
value = self.settings.general.get_string("startup-script")
if value:
self.get_widget("startup_script").set_text(value)
# use display where the mouse is currently
value = self.settings.general.get_boolean("mouse-display")
self.get_widget("mouse_display").set_active(value)
# scrollbar
value = self.settings.general.get_boolean("use-scrollbar")
self.get_widget("use_scrollbar").set_active(value)
# history size
value = self.settings.general.get_int("history-size")
self.get_widget("history_size").set_value(value)
# infinite history
value = self.settings.general.get_boolean("infinite-history")
self.get_widget("infinite_history").set_active(value)
# scroll output
value = self.settings.general.get_boolean("scroll-output")
self.get_widget("scroll_output").set_active(value)
# scroll keystroke
value = self.settings.general.get_boolean("scroll-keystroke")
self.get_widget("scroll_keystroke").set_active(value)
# default font
value = self.settings.general.get_boolean("use-default-font")
self.get_widget("use_default_font").set_active(value)
self.get_widget("font_style").set_sensitive(not value)
# use copy on select
value = self.settings.general.get_boolean("copy-on-select")
self.get_widget("copy_on_select").set_active(value)
# font
value = self.settings.styleFont.get_string("style")
if value:
self.get_widget("font_style").set_font_name(value)
# allow bold font
value = self.settings.styleFont.get_boolean("allow-bold")
self.get_widget("allow_bold").set_active(value)
# use bold is bright
value = self.settings.styleFont.get_boolean("bold-is-bright")
self.get_widget("bold_is_bright").set_active(value)
# cell height scale
value = self.settings.styleFont.get_double("cell-height-scale")
self.get_widget("cell_height_scale_adjustment").set_value(value)
# cell width scale
value = self.settings.styleFont.get_double("cell-width-scale")
self.get_widget("cell_width_scale_adjustment").set_value(value)
# background image file
filename = self.settings.general.get_string("background-image-file")
if os.path.exists(filename):
self.get_widget("background_image_filechooser").set_filename(filename)
# background image layout mode
value = self.settings.general.get_int("background-image-layout-mode")
self.get_widget("background_image_layout_mode").set_active(value)
# palette
self.fill_palette_names()
value = self.settings.styleFont.get_string("palette-name")
self.set_palette_name(value)
value = self.settings.styleFont.get_string("palette")
self.set_palette_colors(value)
self.update_demo_palette(value)
# cursor shape
value = self.settings.style.get_int("cursor-shape")
self.set_cursor_shape(value)
# cursor blink
value = self.settings.style.get_int("cursor-blink-mode")
self.set_cursor_blink_mode(value)
value = self.settings.styleBackground.get_int("transparency")
self.get_widget("background_transparency").set_value(MAX_TRANSPARENCY - value)
value = self.settings.general.get_int("window-valignment")
self.get_widget("top_align").set_active(value)
# it's a separated method, to be reused.
self.reload_erase_combos()
# custom command context-menu configuration file
custom_command_file = self.settings.general.get_string("custom-command-file")
if custom_command_file:
custom_command_file_name = os.path.expanduser(custom_command_file)
else:
custom_command_file_name = None
custom_cmd_filter = Gtk.FileFilter()
custom_cmd_filter.set_name(_("JSON files"))
custom_cmd_filter.add_pattern("*.json")
self.get_widget("custom_command_file_chooser").add_filter(custom_cmd_filter)
all_files_filter = Gtk.FileFilter()
all_files_filter.set_name(_("All files"))
all_files_filter.add_pattern("*")
self.get_widget("custom_command_file_chooser").add_filter(all_files_filter)
if custom_command_file_name:
self.get_widget("custom_command_file_chooser").set_filename(custom_command_file_name)
# hooks
self._load_hooks_settings()
# -- populate functions --
def populate_shell_combo(self):
"""Read the /etc/shells and looks for installed shells to
fill the default_shell combobox.
"""
cb = self.get_widget("default_shell")
# append user shell as first option
cb.append_text(USER_SHELL_VALUE)
if os.path.exists(SHELLS_FILE):
with open(SHELLS_FILE, encoding="utf-8") as f:
for i in f.readlines():
possible = i.strip()
if possible and not possible.startswith("#") and os.path.exists(possible):
cb.append_text(possible)
for i in get_binaries_from_path(PYTHONS):
cb.append_text(i)
def populate_gtk_theme_names(self):
cb = self.get_widget("gtk_theme_name")
for name in list_all_themes():
name = name.strip()
cb.append_text(name)
def populate_keys_tree(self):
"""Reads the HOTKEYS global variable and insert all data in
the TreeStore used by the preferences window treeview.
"""
for group in HOTKEYS:
parent = self.store.append(None, [None, group["label"], None, None])
for item in group["keys"]:
if item["key"] in ("show-hide", "show-focus"):
accel = self.settings.keybindingsGlobal.get_string(item["key"])
else:
accel = self.settings.keybindingsLocal.get_string(item["key"])
gsettings_path = item["key"]
keycode, mask = Gtk.accelerator_parse(accel)
keylabel = Gtk.accelerator_get_label(keycode, mask)
self.store.append(parent, [gsettings_path, item["label"], keylabel, accel])
self.get_widget("treeview-keys").expand_all()
def populate_display_n(self):
"""Get the number of displays and populate this drop-down box
with them all. Prepend the "always on primary" option.
"""
cb = self.get_widget("display_n")
screen = self.get_widget("config-window").get_screen()
cb.append_text("always on primary")
for m in range(0, int(screen.get_n_monitors())):
if m == int(screen.get_primary_monitor()):
# TODO l10n
cb.append_text(str(m) + " " + "(primary)")
else:
cb.append_text(str(m))
# -- key handling --
def on_accel_edited(self, cellrendereraccel, path, key, mods, hwcode):
"""Callback that handles key edition in cellrenderer. It makes
some tests to validate the key, like looking for already in
use keys and look for [A-Z][a-z][0-9] to avoid problems with
these common keys. If all tests are ok, the value will be
stored in dconf.
"""
accelerator = Gtk.accelerator_name(key, mods)
dconf_path = self.store[path][HOTKET_MODEL_INDEX_DCONF]
old_accel = self.store[path][HOTKET_MODEL_INDEX_HUMAN_ACCEL]
keylabel = Gtk.accelerator_get_label(key, mods)
# we needn't to change anything, the user is trying to set the
# same key that is already set.
if old_accel == accelerator:
return False
self.hotkey_alread_used = False
# looking for already used keybindings
def each_key(model, path, subiter):
keyentry = model.get_value(subiter, HOTKET_MODEL_INDEX_ACCEL)
if keyentry and keyentry == accelerator:
self.hotkey_alread_used = True
msg = _('The shortcut "%s" is already in use.') % html_escape(accelerator)
ShowableError(self.window, _("Error setting keybinding."), msg, -1)
raise Exception("This is ok, we just use it to break the foreach loop!")
self.store.foreach(each_key)
if self.hotkey_alread_used:
return False
# avoiding problems with common keys
if (mods == 0 and key != 0) and (
(ord("a") <= key <= ord("z"))
or (ord("A") <= key <= ord("Z"))
or (ord("0") <= key <= ord("9"))
):
dialog = Gtk.MessageDialog(
self.get_widget("config-window"),
Gtk.DialogFlags.MODAL | Gtk.DialogFlags.DESTROY_WITH_PARENT,
Gtk.MessageType.WARNING,
Gtk.ButtonsType.OK,
_(
'The shortcut "%s" cannot be used '
"because it will become impossible to "
"type using this key.\n\n"
"Please try with a key such as "
"Control, Alt or Shift at the same "
"time.\n"
)
% html_escape(chr(key)),
)
dialog.run()
dialog.destroy()
return False
self.store[path][HOTKET_MODEL_INDEX_HUMAN_ACCEL] = keylabel
if dconf_path in ("show-hide", "show-focus"):
self.settings.keybindingsGlobal.set_string(dconf_path, accelerator)
else:
self.settings.keybindingsLocal.set_string(dconf_path, accelerator)
self.store[path][HOTKET_MODEL_INDEX_ACCEL] = accelerator
def on_accel_cleared(self, cellrendereraccel, path):
"""If the user tries to clear a keybinding with the backspace
key this callback will be called and it just fill the model
with an empty key and set the 'disabled' string in dconf path.
"""
dconf_path = self.store[path][HOTKET_MODEL_INDEX_DCONF]
self.store[path][HOTKET_MODEL_INDEX_HUMAN_ACCEL] = ""
self.store[path][HOTKET_MODEL_INDEX_ACCEL] = "None"
if dconf_path in ("show-focus", "show-hide"):
self.settings.keybindingsGlobal.set_string(dconf_path, "disabled")
else:
self.settings.keybindingsLocal.set_string(dconf_path, "disabled")
def start_editing(self, treeview, event):
"""Make the treeview grab the focus and start editing the cell
that the user has clicked to avoid confusion with two or three
clicks before editing a keybinding.
Thanks to gnome-keybinding-properties.c =)
"""
x, y = int(event.x), int(event.y)
ret = treeview.get_path_at_pos(x, y)
if not ret:
return False
path, column, cellx, celly = ret
treeview.row_activated(path, Gtk.TreeViewColumn(None))
treeview.set_cursor(path)
return False
class KeyEntry:
def __init__(self, keycode, mask):
self.keycode = keycode
self.mask = mask
def __repr__(self):
return f"KeyEntry({self.keycode}, {self.mask})"
def __eq__(self, rval):
return self.keycode == rval.keycode and self.mask == rval.mask
def setup_standalone_signals(instance):
"""Called when prefs dialog is running in standalone mode. It
makes the delete event of dialog and click on close button finish
the application.
"""
window = instance.get_widget("config-window")
window.connect("delete-event", Gtk.main_quit)
# We need to block the execution of the already associated
# callback before connecting the new handler.
button = instance.get_widget("button1")
button.handler_block_by_func(instance.gtk_widget_destroy)
button.connect("clicked", Gtk.main_quit)
return instance
if __name__ == "__main__":
import builtins
from locale import gettext
from guake.globals import bindtextdomain
builtins.__dict__["_"] = gettext
bindtextdomain(NAME, LOCALE_DIR)
setup_standalone_signals(PrefsDialog(None)).show()
Gtk.main()
| 61,113
|
Python
|
.py
| 1,246
| 39.886035
| 101
| 0.635447
|
Guake/guake
| 4,406
| 575
| 405
|
GPL-2.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,059
|
utils.py
|
Guake_guake/guake/utils.py
|
# -*- coding: utf-8; -*-
"""
Copyright (C) 2018 Mario Aichinger <aichingm@gmail.com>
Copyright (C) 2007-2012 Lincoln de Sousa <lincoln@minaslivre.org>
Copyright (C) 2007 Gabriel Falc√£o <gabrielteratos@gmail.com>
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 enum
import logging
import os
import re
import subprocess
import time
import yaml
import cairo
import gi
gi.require_version("Gtk", "3.0")
gi.require_version("Gdk", "3.0")
from gi.repository import Gdk
from gi.repository import Gtk
from guake.globals import ALIGN_BOTTOM
from guake.globals import ALIGN_CENTER
from guake.globals import ALIGN_LEFT
from guake.globals import ALIGN_RIGHT
from guake.globals import ALIGN_TOP
try:
from gi.repository import GdkX11
except ImportError:
GdkX11 = False
log = logging.getLogger(__name__)
def gdk_is_x11_display(instance):
if GdkX11:
return isinstance(instance, GdkX11.X11Display)
return False
def get_server_time(widget):
try:
return GdkX11.x11_get_server_time(widget.get_window())
except (TypeError, AttributeError):
# Issue: https://github.com/Guake/guake/issues/1071
# Wayland does not seem to like `x11_get_server_time`.
# Use local timestamp instead
ts = time.time()
return ts
# Decorator for save-tabs-when-changed
def save_tabs_when_changed(func):
"""Decorator for save-tabs-when-changed"""
def wrapper(*args, **kwargs):
# Find me the Guake!
clsname = args[0].__class__.__name__
g = None
if clsname == "Guake":
g = args[0]
elif getattr(args[0], "get_guake", None):
g = args[0].get_guake()
elif getattr(args[0], "get_notebook", None):
g = args[0].get_notebook().guake
elif getattr(args[0], "guake", None):
g = args[0].guake
elif getattr(args[0], "notebook", None):
g = args[0].notebook.guake
func(*args, **kwargs)
log.debug("mom, I've been called: %s %s", func.__name__, func)
# Tada!
if g and g.settings.general.get_boolean("save-tabs-when-changed"):
g.save_tabs()
return wrapper
def save_preferences(filename):
# XXX: Hardcode?
prefs = subprocess.check_output(["dconf", "dump", "/org/guake/"])
with open(filename, "wb") as f:
f.write(prefs)
def restore_preferences(filename):
# XXX: Hardcode?
with open(filename, "rb") as f:
prefs = f.read()
with subprocess.Popen(["dconf", "load", "/org/guake/"], stdin=subprocess.PIPE) as p:
p.communicate(input=prefs)
class FileManager:
def __init__(self, delta=1.0):
self._cache = {}
self._delta = max(0.0, delta)
def clear(self):
self._cache.clear()
def read_yaml(self, filename: str):
content = None
try:
content = self.read(filename)
except PermissionError:
log.debug("PermissionError while reading %s.", filename)
except FileNotFoundError:
log.debug("File %s does not exists.", filename)
except UnicodeDecodeError:
log.debug("Encoding error %s (we assume is utf-8).", filename)
if content is not None:
try:
content = yaml.safe_load(content)
except yaml.YAMLError:
log.debug("YAMLError reading %s.", filename)
content = None
return content
def read(self, filename: str) -> str:
# Return the content of a file from the fs or from cache.
if (
filename not in self._cache
or self._cache[filename]["time"] + self._delta < time.monotonic()
):
with open(filename, mode="r", encoding="utf-8") as fd:
self._cache[filename] = {"time": time.monotonic(), "content": fd.read()}
return self._cache[filename]["content"]
class TabNameUtils:
@classmethod
def shorten(cls, text, settings):
use_vte_titles = settings.general.get_boolean("use-vte-titles")
if not use_vte_titles:
return text
max_name_length = settings.general.get_int("max-tab-name-length")
if max_name_length != 0 and len(text) > max_name_length:
text = "..." + text[-max_name_length:]
return text
class HidePrevention:
def __init__(self, window):
"""Create a new HidePrevention object like `HidePrevention(window)`"""
if not isinstance(window, Gtk.Window):
raise ValueError(f"window must be of type Gtk.Window, not of type {type(window)}")
self.window = window
def may_hide(self):
"""returns True if the window is allowed to hide and
False if `prevent()` is called from some where
"""
return getattr(self.window, "can_hide", True)
def prevent(self):
"""sets a flag on the window object which indicates to
may_hide that the window is NOT allowed to be hidden.
"""
setattr(self.window, "can_hide", False)
def allow(self):
"""sets the flag so that it indicates to may_hide that the window is allowed to be hidden"""
setattr(self.window, "can_hide", True)
class FullscreenManager:
FULLSCREEN_ATTR = "is_fullscreen"
def __init__(self, settings, window, guake=None):
self.settings = settings
self.window = window
self.guake = guake
self.window_state = None
def is_fullscreen(self):
return getattr(self.window, self.FULLSCREEN_ATTR, False)
def set_window_state(self, window_state):
self.window_state = window_state
setattr(
self.window,
self.FULLSCREEN_ATTR,
bool(window_state & Gdk.WindowState.FULLSCREEN),
)
if not window_state & Gdk.WindowState.WITHDRAWN:
if self.is_fullscreen():
self.fullscreen()
elif window_state & Gdk.WindowState.FOCUSED and self.guake.hidden:
self.unfullscreen()
def fullscreen(self):
self.window.fullscreen()
setattr(self.window, self.FULLSCREEN_ATTR, True)
self.toggle_fullscreen_hide_tabbar()
def unfullscreen(self):
self.window.unfullscreen()
setattr(self.window, self.FULLSCREEN_ATTR, False)
self.toggle_fullscreen_hide_tabbar()
# FIX to unfullscreen after show, fullscreen, hide, unfullscreen
# (unfullscreen breaks/does not shrink window size)
RectCalculator.set_final_window_rect(self.settings, self.window)
def toggle(self):
if self.is_fullscreen():
self.unfullscreen()
else:
self.fullscreen()
def toggle_fullscreen_hide_tabbar(self):
if self.is_fullscreen():
if (
self.settings.general.get_boolean("fullscreen-hide-tabbar")
and self.guake
and self.guake.notebook_manager
):
self.guake.notebook_manager.set_notebooks_tabbar_visible(False)
else:
if self.guake and self.guake.notebook_manager:
v = self.settings.general.get_boolean("window-tabbar")
self.guake.notebook_manager.set_notebooks_tabbar_visible(v)
class RectCalculator:
@classmethod
def set_final_window_rect(cls, settings, window):
"""Sets the final size and location of the main window of guake. The height
is the window_height property, width is window_width and the
horizontal alignment is given by window_alignment.
"""
# fetch settings
height_percents = settings.general.get_int("window-height")
width_percents = settings.general.get_int("window-width")
halignment = settings.general.get_int("window-halignment")
valignment = settings.general.get_int("window-valignment")
vdisplacement = settings.general.get_int("window-vertical-displacement")
hdisplacement = settings.general.get_int("window-horizontal-displacement")
log.debug("set_final_window_rect")
log.debug(" height_percents = %s", height_percents)
log.debug(" width_percents = %s", width_percents)
log.debug(" halignment = %s", halignment)
log.debug(" valignment = %s", valignment)
log.debug(" hdisplacement = %s", hdisplacement)
log.debug(" vdisplacement = %s", vdisplacement)
# get the rectangle just from the destination monitor
monitor = cls.get_final_window_monitor(settings, window)
window_rect = monitor.get_workarea()
log.debug("Current monitor geometry")
log.debug(" window_rect.x: %s", window_rect.x)
log.debug(" window_rect.y: %s", window_rect.y)
log.debug(" window_rect.height: %s", window_rect.height)
log.debug(" window_rect.width: %s", window_rect.width)
total_height = window_rect.height
total_width = window_rect.width
if halignment == ALIGN_CENTER:
log.debug("aligning to center!")
window_rect.width = int(float(total_width) * float(width_percents) / 100.0)
window_rect.x += (total_width - window_rect.width) / 2
elif halignment == ALIGN_LEFT:
log.debug("aligning to left!")
window_rect.width = int(
float(total_width - hdisplacement) * float(width_percents) / 100.0
)
window_rect.x += hdisplacement
elif halignment == ALIGN_RIGHT:
log.debug("aligning to right!")
window_rect.width = int(
float(total_width - hdisplacement) * float(width_percents) / 100.0
)
window_rect.x += total_width - window_rect.width - hdisplacement
window_rect.height = int(float(total_height) * float(height_percents) / 100.0)
if valignment == ALIGN_TOP:
window_rect.y += vdisplacement
elif valignment == ALIGN_BOTTOM:
window_rect.y += total_height - window_rect.height - vdisplacement
if width_percents == 100 and height_percents == 100:
log.debug("MAXIMIZING MAIN WINDOW")
window.move(window_rect.x, window_rect.y)
window.maximize()
elif not FullscreenManager(settings, window).is_fullscreen():
log.debug("RESIZING MAIN WINDOW TO THE FOLLOWING VALUES:")
window.unmaximize()
log.debug(" window_rect.x: %s", window_rect.x)
log.debug(" window_rect.y: %s", window_rect.y)
log.debug(" window_rect.height: %s", window_rect.height)
log.debug(" window_rect.width: %s", window_rect.width)
# Note: move_resize is only on GTK3
window.resize(window_rect.width, window_rect.height)
window.move(window_rect.x, window_rect.y)
log.debug("Updated window position: %r", window.get_position())
return window_rect
@classmethod
def get_final_window_monitor(cls, settings, window):
"""Gets the final monitor for the main window of guake."""
display = window.get_display()
# fetch settings
use_mouse = settings.general.get_boolean("mouse-display")
num_monitor = settings.general.get_int("display-n")
if use_mouse:
pointer = display.get_default_seat().get_pointer()
if pointer is None:
monitor = display.get_primary_monitor()
else:
_, x, y = pointer.get_position()
monitor = display.get_monitor_at_point(x, y)
else:
monitor = display.get_monitor(num_monitor)
if monitor is None:
# monitor not found or num_monitor is wrong
# by default we use the primary monitor
monitor = display.get_primary_monitor()
return monitor
class ImageLayoutMode(enum.IntEnum):
SCALE = 0
TILE = 1
CENTER = 2
STRETCH = 3
class BackgroundImageManager:
def __init__(self, window, filename=None, layout_mode=ImageLayoutMode.SCALE):
self.window = window
self.filename = ""
self.bg_surface = self.load_from_file(filename) if filename else None
self.target_surface = None
self.target_info = (-1, -1, -1) # (width, height, model)
self._layout_mode = layout_mode
@property
def layout_mode(self):
return self._layout_mode
@layout_mode.setter
def layout_mode(self, mode):
mode = ImageLayoutMode(mode)
if mode not in ImageLayoutMode:
raise ValueError("Unknown layout mode")
self._layout_mode = mode
self.window.queue_draw()
def load_from_file(self, filename):
if not filename:
# Clear the background image
self.bg_surface = None
self.window.queue_draw()
return
if not os.path.exists(filename):
raise FileNotFoundError(f"Background file not found: {filename}")
if self.filename:
# Cached rendered surface
if os.path.samefile(self.filename, filename):
return self.bg_surface
self.filename = filename
img = Gtk.Image.new_from_file(filename)
pixbuf = img.get_pixbuf()
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, pixbuf.get_width(), pixbuf.get_height())
cr = cairo.Context(surface)
Gdk.cairo_set_source_pixbuf(cr, pixbuf, 0, 0)
cr.set_operator(cairo.OPERATOR_SOURCE)
cr.paint()
self.bg_surface = surface
self.target_info = (-1, -1, -1)
self.window.queue_draw()
return surface
def render_target(self, width, height, mode, scale_mode=cairo.FILTER_BILINEAR):
"""Paint bacground image to the specific size target surface with different layout mode"""
if not self.bg_surface:
return None
# Check if target surface has been rendered
if self.target_info == (width, height, mode):
return self.target_surface
# Render new target
self.target_info = (width, height, mode)
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
cr = cairo.Context(surface)
cr.set_operator(cairo.OPERATOR_SOURCE)
xscale = width / self.bg_surface.get_width()
yscale = height / self.bg_surface.get_height()
if mode == ImageLayoutMode.SCALE:
ratio = max(xscale, yscale)
xoffset = (width - (self.bg_surface.get_width() * ratio)) / 2.0
yoffset = (height - (self.bg_surface.get_height() * ratio)) / 2.0
cr.translate(xoffset, yoffset)
cr.scale(ratio, ratio)
cr.set_source_surface(self.bg_surface, 0, 0)
cr.get_source().set_filter(scale_mode)
elif mode == ImageLayoutMode.TILE:
cr.set_source_surface(self.bg_surface, 0, 0)
cr.get_source().set_extend(cairo.EXTEND_REPEAT)
elif mode == ImageLayoutMode.CENTER:
x = (width - self.bg_surface.get_width()) / 2.0
y = (height - self.bg_surface.get_height()) / 2.0
cr.translate(x, y)
cr.set_source_surface(self.bg_surface, 0, 0)
elif mode == ImageLayoutMode.STRETCH:
cr.scale(xscale, yscale)
cr.set_source_surface(self.bg_surface, 0, 0)
cr.get_source().set_filter(scale_mode)
cr.paint()
self.target_surface = surface
return surface
def draw(self, widget, cr):
if not self.bg_surface:
return
# Step 1. Get target surface
# (paint background image into widget size surface by layout mode)
surface = self.render_target(
widget.get_allocated_width(),
widget.get_allocated_height(),
self.layout_mode,
)
cr.save()
# Step 2. Paint target surface to context (in our case, the RootTerminalBox)
#
# At this step, RootTerminalBox will be painted to our background image,
# and all the draw done by VTE has been overlapped.
#
cr.set_source_surface(surface, 0, 0)
cr.paint()
# Step 3. Re-paint child draw result to a new surface
#
# We need to re-paint what we overlapped in previous step,
# so we paint our child (again, in lifecycle view) into a similar surface.
#
child = widget.get_child()
child_surface = cr.get_target().create_similar(
cairo.CONTENT_COLOR_ALPHA,
child.get_allocated_width(),
child.get_allocated_height(),
)
child_cr = cairo.Context(child_surface)
# Re-paint child draw into child context (which using child_surface as target)
widget.propagate_draw(child, child_cr)
# Step 3.1 Re-paint search revealer
child_sr_surface = None
if getattr(widget, "search_revealer", None):
child_sr = widget.search_revealer
child_sr_surface = cr.get_target().create_similar(
cairo.CONTENT_COLOR_ALPHA,
child_sr.get_allocated_width(),
child_sr.get_allocated_height(),
)
child_sr_cr = cairo.Context(child_surface)
# Re-paint child draw into child context (which using child_surface as target)
widget.propagate_draw(child_sr, child_sr_cr)
# Step 4. Paint child surface into our context (RootTerminalBox)
#
# Before this step, we have two important context/surface
# 1. cr / RootTerminalBox
# 2. child_cr / child (RootTerminalBox's child)
# And current context have these draw:
# 1. cr - background image
# 2. child_cr - child re-paint (split terminal, VTE draw ...etc)
# In this step, we are going to paint child_cr result back to cr,
# so in the end, we will get background image + other child stuff
#
# DEBUG: If you don't believe, use cairo.Surface.wrte_to_png(filename) to check what is
# inside the surface.
#
cr.set_source_surface(child_surface, 0, 0)
cr.set_operator(cairo.OPERATOR_OVER)
cr.paint()
# Paint search revealer
if child_sr_surface:
cr.set_source_surface(child_sr_surface, 0, 0)
cr.set_operator(cairo.OPERATOR_OVER)
cr.paint()
cr.restore()
def get_process_name(pid):
stat_file = f"/proc/{pid}/stat"
try:
with open(stat_file, "r", encoding="utf-8") as fp:
status = fp.read()
except IOError as ex:
log.debug("Unable to read %s: %s", stat_file, ex)
status = ""
match = re.match(r"\d+ \(([^)]+)\)", status)
return match.group(1) if match else None
| 19,578
|
Python
|
.py
| 448
| 34.584821
| 100
| 0.619918
|
Guake/guake
| 4,406
| 575
| 405
|
GPL-2.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,060
|
__init__.py
|
Guake_guake/guake/__init__.py
|
# -*- coding: utf-8; -*-
"""
Copyright (C) 2007-2013 Guake authors
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
"""
# pylint: disable=import-outside-toplevel
def guake_version():
from ._version import version
return version
def vte_version():
import gi
gi.require_version("Vte", "2.91")
from gi.repository import Vte
s = f"{Vte.MAJOR_VERSION}.{Vte.MINOR_VERSION}.{Vte.MICRO_VERSION}"
return s
def vte_runtime_version():
import gi
gi.require_version("Vte", "2.91")
from gi.repository import Vte
return f"{Vte.get_major_version()}.{Vte.get_minor_version()}.{Vte.get_micro_version()}"
def gtk_version():
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk
return f"{Gtk.MAJOR_VERSION}.{Gtk.MINOR_VERSION}.{Gtk.MICRO_VERSION}"
| 1,457
|
Python
|
.py
| 36
| 37.222222
| 91
| 0.747143
|
Guake/guake
| 4,406
| 575
| 405
|
GPL-2.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,061
|
keybindings.py
|
Guake_guake/guake/keybindings.py
|
# -*- coding: utf-8; -*-
"""
Copyright (C) 2007-2013 Guake authors
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 collections import defaultdict
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gdk
from gi.repository import Gtk
from guake import notifier
from guake.common import pixmapfile
from guake.split_utils import FocusMover
from guake.split_utils import SplitMover
log = logging.getLogger(__name__)
class Keybindings:
"""Handles changes in keyboard shortcuts."""
def __init__(self, guake):
"""Constructor of Keyboard, only receives the guake instance
to be used in internal methods.
"""
self.guake = guake
self.accel_group = None # see reload_accelerators
self._lookup = None
self._masks = None
self.keymap = Gdk.Keymap.get_for_display(Gdk.Display.get_default())
# Setup global keys
self.globalhotkeys = {}
globalkeys = ["show-hide", "show-focus"]
for key in globalkeys:
guake.settings.keybindingsGlobal.onChangedValue(key, self.reload_global)
guake.settings.keybindingsGlobal.triggerOnChangedValue(
guake.settings.keybindingsGlobal, key, None
)
def x(*args):
prompt_cfg = self.guake.settings.general.get_int("prompt-on-close-tab")
self.guake.get_notebook().delete_page_current(prompt=prompt_cfg)
# Setup local keys
self.keys = [
("toggle-fullscreen", self.guake.accel_toggle_fullscreen),
("new-tab", self.guake.accel_add),
("new-tab-home", self.guake.accel_add_home),
("new-tab-cwd", self.guake.accel_add_cwd),
("close-tab", x),
("rename-current-tab", self.guake.accel_rename_current_tab),
("previous-tab", self.guake.accel_prev),
("previous-tab-alt", self.guake.accel_prev),
("next-tab", self.guake.accel_next),
("next-tab-alt", self.guake.accel_next),
("clipboard-copy", self.guake.accel_copy_clipboard),
("clipboard-paste", self.guake.accel_paste_clipboard),
("select-all", self.guake.accel_select_all),
("quit", self.guake.accel_quit),
("zoom-in", self.guake.accel_zoom_in),
("zoom-in-alt", self.guake.accel_zoom_in),
("zoom-out", self.guake.accel_zoom_out),
("increase-height", self.guake.accel_increase_height),
("decrease-height", self.guake.accel_decrease_height),
("increase-transparency", self.guake.accel_increase_transparency),
("decrease-transparency", self.guake.accel_decrease_transparency),
("toggle-transparency", self.guake.accel_toggle_transparency),
("search-on-web", self.guake.search_on_web),
("open-link-under-terminal-cursor", self.guake.open_link_under_terminal_cursor),
("move-tab-left", self.guake.accel_move_tab_left),
("move-tab-right", self.guake.accel_move_tab_right),
("switch-tab1", self.guake.gen_accel_switch_tabN(0)),
("switch-tab2", self.guake.gen_accel_switch_tabN(1)),
("switch-tab3", self.guake.gen_accel_switch_tabN(2)),
("switch-tab4", self.guake.gen_accel_switch_tabN(3)),
("switch-tab5", self.guake.gen_accel_switch_tabN(4)),
("switch-tab6", self.guake.gen_accel_switch_tabN(5)),
("switch-tab7", self.guake.gen_accel_switch_tabN(6)),
("switch-tab8", self.guake.gen_accel_switch_tabN(7)),
("switch-tab9", self.guake.gen_accel_switch_tabN(8)),
("switch-tab10", self.guake.gen_accel_switch_tabN(9)),
("switch-tab-last", self.guake.accel_switch_tab_last),
("reset-terminal", self.guake.accel_reset_terminal),
(
"split-tab-vertical",
lambda *args: self.guake.get_notebook()
.get_current_terminal()
.get_parent()
.split_v()
or True,
),
(
"split-tab-horizontal",
lambda *args: self.guake.get_notebook()
.get_current_terminal()
.get_parent()
.split_h()
or True,
),
(
"close-terminal",
lambda *args: self.guake.get_notebook().get_current_terminal().kill() or True,
),
(
"focus-terminal-up",
(
lambda *args: FocusMover(self.guake.window).move_up(
self.guake.get_notebook().get_current_terminal()
)
or True
),
),
(
"focus-terminal-down",
(
lambda *args: FocusMover(self.guake.window).move_down(
self.guake.get_notebook().get_current_terminal()
)
or True
),
),
(
"focus-terminal-right",
(
lambda *args: FocusMover(self.guake.window).move_right(
self.guake.get_notebook().get_current_terminal()
)
or True
),
),
(
"focus-terminal-left",
(
lambda *args: FocusMover(self.guake.window).move_left(
self.guake.get_notebook().get_current_terminal()
)
or True
),
),
(
"move-terminal-split-up",
(
lambda *args: SplitMover.move_up( # keep make style from concat this lines
self.guake.get_notebook().get_current_terminal()
)
or True
),
),
(
"move-terminal-split-down",
(
lambda *args: SplitMover.move_down( # keep make style from concat this lines
self.guake.get_notebook().get_current_terminal()
)
or True
),
),
(
"move-terminal-split-left",
(
lambda *args: SplitMover.move_left( # keep make style from concat this lines
self.guake.get_notebook().get_current_terminal()
)
or True
),
),
(
"move-terminal-split-right",
(
lambda *args: SplitMover.move_right( # keep make style from concat this lines
self.guake.get_notebook().get_current_terminal()
)
or True
),
),
("search-terminal", self.guake.accel_search_terminal),
("toggle-hide-on-lose-focus", self.guake.accel_toggle_hide_on_lose_focus),
]
for key, _ in self.keys:
guake.settings.keybindingsLocal.onChangedValue(key, self.reload_accelerators)
self.reload_accelerators()
def reload_global(self, settings, key, user_data):
value = settings.get_string(key)
if value == "disabled":
return
try:
self.guake.hotkeys.unbind(self.globalhotkeys[key])
except BaseException:
pass
self.globalhotkeys[key] = value
if key == "show-hide":
log.debug("reload_global: %r", value)
if not self.guake.hotkeys.bind(value, self.guake.show_hide):
keyval, mask = Gtk.accelerator_parse(value)
label = Gtk.accelerator_get_label(keyval, mask)
filename = pixmapfile("guake-notification.png")
notifier.showMessage(
_("Guake Terminal"),
_(
"A problem happened when binding <b>%s</b> key.\n"
"Please use Guake Preferences dialog to choose another "
"key"
)
% label,
filename,
)
elif key == "show-focus" and not self.guake.hotkeys.bind(value, self.guake.show_focus):
log.warning("can't bind show-focus key")
def activate(self, window, event):
"""If keystroke matches a key binding, activate keybinding. Otherwise, allow
keystroke to pass through."""
key = event.keyval
mod = event.state
# Set keyval to the first available English keyboard value if character is non-latin
# and a english keyval is found
if event.keyval > 126:
for i in self.keymap.get_entries_for_keycode(event.hardware_keycode)[2]:
if 0 < i <= 126:
key = i
break
if mod & Gdk.ModifierType.SHIFT_MASK:
if key == Gdk.KEY_ISO_Left_Tab:
key = Gdk.KEY_Tab
else:
key = Gdk.keyval_to_lower(key)
else:
keys = Gdk.keyval_convert_case(key)
if key != keys[1]:
key = keys[0]
mod &= ~Gdk.ModifierType.SHIFT_MASK
mask = mod & self._masks
func = self._lookup[mask].get(key, None)
if func:
func()
return True
return False
def reload_accelerators(self, *args):
"""Reassign an accel_group to guake main window and guake
context menu and calls the load_accelerators method.
"""
self._lookup = defaultdict(dict)
self._masks = 0
self.load_accelerators()
self.guake.accel_group = self
def load_accelerators(self):
"""Reads all gconf paths under /org/guake/keybindings/local
and adds to the _lookup.
"""
for binding, action in self.keys:
key, mask = Gtk.accelerator_parse(
self.guake.settings.keybindingsLocal.get_string(binding)
)
if key > 0:
self._lookup[mask][key] = action
self._masks |= mask
| 11,039
|
Python
|
.py
| 261
| 29.157088
| 98
| 0.541023
|
Guake/guake
| 4,406
| 575
| 405
|
GPL-2.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,062
|
menus.py
|
Guake_guake/guake/menus.py
|
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk
from guake.customcommands import CustomCommands
import logging
log = logging.getLogger(__name__)
def mk_tab_context_menu(callback_object):
"""Create the context menu for a notebook tab"""
# Store the menu in a temp variable in terminal so that popup() is happy. See:
# https://stackoverflow.com/questions/28465956/
callback_object.context_menu = Gtk.Menu()
menu = callback_object.context_menu
mi_new_tab = Gtk.MenuItem(_("New Tab"))
mi_new_tab.connect("activate", callback_object.on_new_tab)
menu.add(mi_new_tab)
mi_rename = Gtk.MenuItem(_("Rename"))
mi_rename.connect("activate", callback_object.on_rename)
menu.add(mi_rename)
mi_reset_custom_colors = Gtk.MenuItem(_("Reset custom colors"))
mi_reset_custom_colors.connect("activate", callback_object.on_reset_custom_colors)
menu.add(mi_reset_custom_colors)
mi_close = Gtk.MenuItem(_("Close"))
mi_close.connect("activate", callback_object.on_close)
menu.add(mi_close)
menu.show_all()
return menu
def mk_notebook_context_menu(callback_object):
"""Create the context menu for the notebook"""
callback_object.context_menu = Gtk.Menu()
menu = callback_object.context_menu
mi = Gtk.MenuItem(_("New Tab"))
mi.connect("activate", callback_object.on_new_tab)
menu.add(mi)
menu.add(Gtk.SeparatorMenuItem())
mi = Gtk.MenuItem(_("Save Tabs"))
mi.connect("activate", callback_object.on_save_tabs)
menu.add(mi)
mi = Gtk.MenuItem(_("Restore Tabs"))
mi.connect("activate", callback_object.on_restore_tabs_with_dialog)
menu.add(mi)
menu.add(Gtk.SeparatorMenuItem())
mi = Gtk.ImageMenuItem("gtk-preferences")
mi.set_use_stock(True)
mi.connect("activate", callback_object.on_show_preferences)
menu.add(mi)
mi = Gtk.ImageMenuItem("gtk-about")
mi.set_use_stock(True)
mi.connect("activate", callback_object.on_show_about)
menu.add(mi)
menu.add(Gtk.SeparatorMenuItem())
mi = Gtk.MenuItem(_("Quit"))
mi.connect("activate", callback_object.on_quit)
menu.add(mi)
menu.show_all()
return menu
SEARCH_SELECTION_LENGTH = 20
FILE_SELECTION_LENGTH = 30
def mk_terminal_context_menu(terminal, window, settings, callback_object):
"""Create the context menu for a terminal."""
# Store the menu in a temp variable in terminal so that popup() is happy. See:
# https://stackoverflow.com/questions/28465956/
terminal.context_menu = Gtk.Menu()
menu = terminal.context_menu
mi = Gtk.MenuItem(_("Copy"))
mi.connect("activate", callback_object.on_copy_clipboard)
menu.add(mi)
if get_link_under_cursor(terminal) is not None:
mi = Gtk.MenuItem(_("Copy URL"))
mi.connect("activate", callback_object.on_copy_url_clipboard)
menu.add(mi)
mi = Gtk.MenuItem(_("Paste"))
mi.connect("activate", callback_object.on_paste_clipboard)
# check if clipboard has text, if not disable the paste menuitem
clipboard = Gtk.Clipboard.get_default(window.get_display())
mi.set_sensitive(clipboard.wait_is_text_available())
menu.add(mi)
menu.add(Gtk.SeparatorMenuItem())
mi = Gtk.MenuItem(_("Toggle Fullscreen"))
mi.connect("activate", callback_object.on_toggle_fullscreen)
menu.add(mi)
menu.add(Gtk.SeparatorMenuItem())
mi = Gtk.MenuItem(_("Split ―"))
mi.connect("activate", callback_object.on_split_horizontal)
menu.add(mi)
mi = Gtk.MenuItem(_("Split |"))
mi.connect("activate", callback_object.on_split_vertical)
menu.add(mi)
mi = Gtk.MenuItem(_("Close terminal"))
mi.connect("activate", callback_object.on_close_terminal)
menu.add(mi)
menu.add(Gtk.SeparatorMenuItem())
mi = Gtk.MenuItem(_("Save content..."))
mi.connect("activate", callback_object.on_save_to_file)
menu.add(mi)
mi = Gtk.MenuItem(_("Reset terminal"))
mi.connect("activate", callback_object.on_reset_terminal)
menu.add(mi)
# TODO SEARCH uncomment menu.add()
mi = Gtk.MenuItem(_("Find..."))
mi.connect("activate", callback_object.on_find)
# menu.add(mi)
menu.add(Gtk.SeparatorMenuItem())
mi = Gtk.MenuItem(_("Open link..."))
mi.connect("activate", callback_object.on_open_link)
link = get_link_under_cursor(terminal)
# TODO CONTEXTMENU this is a mess Quick open should also be sensible
# if the text in the selection is a url the current terminal
# implementation does not support this at the moment
if link:
if len(link) >= FILE_SELECTION_LENGTH:
mi.set_label(_("Open Link: {!s}...").format(link[: FILE_SELECTION_LENGTH - 3]))
else:
mi.set_label(_("Open Link: {!s}").format(link))
mi.set_sensitive(True)
else:
mi.set_sensitive(False)
menu.add(mi)
mi = Gtk.MenuItem(_("Search on Web"))
mi.connect("activate", callback_object.on_search_on_web)
selection = get_current_selection(terminal, window)
if selection:
search_text = selection.rstrip()
if len(search_text) > SEARCH_SELECTION_LENGTH:
search_text = search_text[: SEARCH_SELECTION_LENGTH - 3] + "..."
mi.set_label(_("Search on Web: '%s'") % search_text)
mi.set_sensitive(True)
else:
mi.set_sensitive(False)
menu.add(mi)
mi = Gtk.MenuItem(_("Quick Open..."))
mi.connect("activate", callback_object.on_quick_open)
if selection:
filename = get_filename_under_cursor(terminal, selection)
if filename:
filename_str = str(filename)
if len(filename_str) > FILE_SELECTION_LENGTH:
mi.set_label(
_("Quick Open: {!s}...").format(filename_str[: FILE_SELECTION_LENGTH - 3])
)
else:
mi.set_label(_("Quick Open: {!s}").format(filename_str))
mi.set_sensitive(True)
else:
mi.set_sensitive(False)
else:
mi.set_sensitive(False)
menu.add(mi)
customcommands = CustomCommands(settings, callback_object)
if customcommands.should_load():
submen = customcommands.build_menu()
if submen:
menu.add(Gtk.SeparatorMenuItem())
mi = Gtk.MenuItem(_("Custom Commands"))
mi.set_submenu(submen)
menu.add(mi)
menu.add(Gtk.SeparatorMenuItem())
mi = Gtk.ImageMenuItem("gtk-preferences")
mi.set_use_stock(True)
mi.connect("activate", callback_object.on_show_preferences)
menu.add(mi)
mi = Gtk.ImageMenuItem("gtk-about")
mi.set_use_stock(True)
mi.connect("activate", callback_object.on_show_about)
menu.add(mi)
menu.add(Gtk.SeparatorMenuItem())
mi = Gtk.ImageMenuItem(_("Quit"))
mi.connect("activate", callback_object.on_quit)
menu.add(mi)
menu.show_all()
return menu
def get_current_selection(terminal, window):
if terminal.get_has_selection():
terminal.copy_clipboard()
clipboard = Gtk.Clipboard.get_default(window.get_display())
return clipboard.wait_for_text()
return None
def get_filename_under_cursor(terminal, selection):
filename, _1, _2 = terminal.is_file_on_local_server(selection)
log.info("Current filename under cursor: %s", filename)
if filename:
return filename
return None
def get_link_under_cursor(terminal):
link = terminal.found_link
log.info("Current link under cursor: %s", link)
if link:
return link
return None
| 7,530
|
Python
|
.py
| 188
| 33.978723
| 94
| 0.667668
|
Guake/guake
| 4,406
| 575
| 405
|
GPL-2.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,063
|
guake_app.py
|
Guake_guake/guake/guake_app.py
|
# -*- coding: utf-8; -*-
"""
Copyright (C) 2007-2012 Lincoln de Sousa <lincoln@minaslivre.org>
Copyright (C) 2007 Gabriel Falc√£o <gabrielteratos@gmail.com>
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 json
import logging
import os
import shutil
import subprocess
import time as pytime
import traceback
import uuid
from pathlib import Path
from threading import Thread
from time import sleep
from urllib.parse import quote_plus
from xml.sax.saxutils import escape as xml_escape
import gi
gi.require_version("Gtk", "3.0")
gi.require_version("Gdk", "3.0")
gi.require_version("Keybinder", "3.0")
from gi.repository import GLib
from gi.repository import Gdk
from gi.repository import Gio
from gi.repository import Gtk
from gi.repository import Keybinder
from guake import gtk_version
from guake import guake_version
from guake import notifier
from guake import vte_version
from guake.about import AboutDialog
from guake.common import gladefile
from guake.common import pixmapfile
from guake.dialogs import PromptQuitDialog
from guake.globals import MAX_TRANSPARENCY
from guake.globals import NAME
from guake.globals import PROMPT_ALWAYS
from guake.globals import PROMPT_PROCESSES
from guake.globals import TABS_SESSION_SCHEMA_VERSION
from guake.gsettings import GSettingHandler
from guake.keybindings import Keybindings
from guake.notebook import NotebookManager
from guake.palettes import PALETTES
from guake.paths import LOCALE_DIR
from guake.paths import SCHEMA_DIR
from guake.paths import try_to_compile_glib_schemas
from guake.prefs import PrefsDialog
from guake.prefs import refresh_user_start
from guake.settings import Settings
from guake.simplegladeapp import SimpleGladeApp
from guake.theme import patch_gtk_theme
from guake.theme import select_gtk_theme
from guake.utils import BackgroundImageManager
from guake.utils import FileManager
from guake.utils import FullscreenManager
from guake.utils import HidePrevention
from guake.utils import RectCalculator
from guake.utils import TabNameUtils
from guake.utils import get_server_time
from guake.utils import save_tabs_when_changed
log = logging.getLogger(__name__)
instance = None
RESPONSE_FORWARD = 0
RESPONSE_BACKWARD = 1
# Disable find feature until python-vte hasn't been updated
enable_find = False
# Setting gobject program name
GLib.set_prgname(NAME)
GDK_WINDOW_STATE_WITHDRAWN = 1
GDK_WINDOW_STATE_ICONIFIED = 2
GDK_WINDOW_STATE_STICKY = 8
GDK_WINDOW_STATE_ABOVE = 32
class Guake(SimpleGladeApp):
"""Guake main class. Handles specialy the main window."""
def __init__(self):
def load_schema():
log.info("Loading Gnome schema from: %s", SCHEMA_DIR)
return Gio.SettingsSchemaSource.new_from_directory(
SCHEMA_DIR, Gio.SettingsSchemaSource.get_default(), False
)
try:
schema_source = load_schema()
except GLib.Error: # pylint: disable=catching-non-exception
log.exception("Unable to load the GLib schema, try to compile it")
try_to_compile_glib_schemas()
schema_source = load_schema()
self.settings = Settings(schema_source)
self.accel_group = None
if (
"schema-version" not in self.settings.general.keys()
or self.settings.general.get_string("schema-version") != guake_version()
):
log.exception("Schema from old guake version detected, regenerating schema")
try:
try_to_compile_glib_schemas()
except subprocess.CalledProcessError:
log.exception("Schema in non user-editable location, attempting to continue")
schema_source = load_schema()
self.settings = Settings(schema_source)
self.settings.general.set_string("schema-version", guake_version())
log.info("Language previously loaded from: %s", LOCALE_DIR)
super().__init__(gladefile("guake.glade"))
select_gtk_theme(self.settings)
patch_gtk_theme(self.get_widget("window-root").get_style_context(), self.settings)
self.add_callbacks(self)
log.info("Guake Terminal %s", guake_version())
log.info("VTE %s", vte_version())
log.info("Gtk %s", gtk_version())
self.hidden = True
self.forceHide = False
# trayicon! Using SVG handles better different OS trays
# img = pixmapfile('guake-tray.svg')
# trayicon!
img = pixmapfile("guake-tray.png")
try:
try:
gi.require_version("AyatanaAppIndicator3", "0.1")
from gi.repository import ( # pylint: disable=import-outside-toplevel
AyatanaAppIndicator3 as appindicator,
)
except (ValueError, ImportError):
gi.require_version("AppIndicator3", "0.1")
from gi.repository import ( # pylint: disable=import-outside-toplevel
AppIndicator3 as appindicator,
)
except (ValueError, ImportError):
self.tray_icon = Gtk.StatusIcon()
self.tray_icon.set_from_file(img)
self.tray_icon.set_tooltip_text(_("Guake Terminal"))
self.tray_icon.connect("popup-menu", self.show_menu)
self.tray_icon.connect("activate", self.show_hide)
else:
# TODO PORT test this on a system with app indicator
self.tray_icon = appindicator.Indicator.new(
"guake-indicator", "guake-tray", appindicator.IndicatorCategory.APPLICATION_STATUS
)
self.tray_icon.set_icon_full("guake-tray", _("Guake Terminal"))
self.tray_icon.set_status(appindicator.IndicatorStatus.ACTIVE)
menu = self.get_widget("tray-menu")
show = Gtk.MenuItem(_("Show"))
show.set_sensitive(True)
show.connect("activate", self.show_hide)
show.show()
menu.prepend(show)
self.tray_icon.set_menu(menu)
self.display_tab_names = 0
# important widgets
self.window = self.get_widget("window-root")
self.window.set_name("guake-terminal")
self.window.set_keep_above(True)
self.mainframe = self.get_widget("mainframe")
self.mainframe.remove(self.get_widget("notebook-teminals"))
# Pending restore for terminal split after show-up
# [(RootTerminalBox, TerminaBox, panes), ...]
self.pending_restore_page_split = []
self._failed_restore_page_split = []
# BackgroundImageManager
self.background_image_manager = BackgroundImageManager(self.window)
# FullscreenManager
self.fullscreen_manager = FullscreenManager(self.settings, self.window, self)
# Start the file manager (only used by guake.yml so far).
self.fm = FileManager()
# Workspace tracking
self.notebook_manager = NotebookManager(
self.window,
self.mainframe,
self.settings.general.get_boolean("workspace-specific-tab-sets"),
self.terminal_spawned,
self.page_deleted,
)
self.notebook_manager.connect("notebook-created", self.notebook_created)
self.notebook_manager.set_workspace(0)
self.set_tab_position()
# check and set ARGB for real transparency
self.update_visual()
self.window.get_screen().connect("composited-changed", self.update_visual)
# Debounce accel_search_terminal
self.prev_accel_search_terminal_time = 0.0
# holds the timestamp of the losefocus event
self.losefocus_time = 0
# holds the timestamp of the previous show/hide action
self.prev_showhide_time = 0
# Controls the transparency state needed for function accel_toggle_transparency
self.transparency_toggled = False
# store the default window title to reset it when update is not wanted
self.default_window_title = self.window.get_title()
self.window.connect("focus-out-event", self.on_window_losefocus)
self.window.connect("focus-in-event", self.on_window_takefocus)
# Handling the delete-event of the main window to avoid
# problems when closing it.
def destroy(*args):
self.hide()
return True
def window_event(*args):
return self.window_event(*args)
self.window.connect("delete-event", destroy)
self.window.connect("window-state-event", window_event)
# this line is important to resize the main window and make it
# smaller.
# TODO PORT do we still need this?
# self.window.set_geometry_hints(min_width=1, min_height=1)
# special trick to avoid the "lost guake on Ubuntu 'Show Desktop'" problem.
# DOCK makes the window foundable after having being "lost" after "Show
# Desktop"
self.window.set_type_hint(Gdk.WindowTypeHint.DOCK)
# Restore back to normal behavior
self.window.set_type_hint(Gdk.WindowTypeHint.NORMAL)
# loading and setting up configuration stuff
GSettingHandler(self)
Keybinder.init()
self.hotkeys = Keybinder
Keybindings(self)
self.load_config()
if self.settings.general.get_boolean("start-fullscreen"):
self.fullscreen()
refresh_user_start(self.settings)
# Restore tabs when startup
if self.settings.general.get_boolean("restore-tabs-startup"):
self.restore_tabs(suppress_notify=True)
# Pop-up that shows that guake is working properly (if not
# unset in the preferences windows)
if self.settings.general.get_boolean("use-popup"):
key = self.settings.keybindingsGlobal.get_string("show-hide")
keyval, mask = Gtk.accelerator_parse(key)
label = Gtk.accelerator_get_label(keyval, mask)
filename = pixmapfile("guake-notification.png")
notifier.showMessage(
_("Guake Terminal"),
_("Guake is now running,\n" "press <b>{!s}</b> to use it.").format(
xml_escape(label)
),
filename,
)
log.info("Guake initialized")
def get_notebook(self):
return self.notebook_manager.get_current_notebook()
def notebook_created(self, nm, notebook, key):
notebook.attach_guake(self)
# Tracking when reorder page
notebook.connect("page-reordered", self.on_page_reorder)
def update_visual(self, user_data=None):
screen = self.window.get_screen()
visual = screen.get_rgba_visual()
if visual and screen.is_composited():
# NOTE: We should re-realize window when update window visual
# Otherwise it may failed, when the Guake it start without compositor
self.window.unrealize()
self.window.set_visual(visual)
self.window.set_app_paintable(True)
self.window.transparency = True
self.window.realize()
if self.window.get_property("visible"):
self.hide()
self.show()
else:
log.warning("System doesn't support transparency")
self.window.transparency = False
self.window.set_visual(screen.get_system_visual())
# new color methods should be moved to the GuakeTerminal class
def _load_palette(self):
colorRGBA = Gdk.RGBA(0, 0, 0, 0)
paletteList = []
for color in self.settings.styleFont.get_string("palette").split(":"):
colorRGBA.parse(color)
paletteList.append(colorRGBA.copy())
return paletteList
def _get_background_color(self, palette_list):
if len(palette_list) > 16:
bg_color = palette_list[17]
else:
bg_color = Gdk.RGBA(0, 0, 0, 0.9)
return self._apply_transparency_to_color(bg_color)
def _apply_transparency_to_color(self, bg_color):
transparency = self.settings.styleBackground.get_int("transparency")
if not self.transparency_toggled:
bg_color.alpha = 1 / 100 * transparency
else:
bg_color.alpha = 1
return bg_color
def set_background_color_from_settings(self, terminal_uuid=None):
self.set_colors_from_settings(terminal_uuid)
def get_bgcolor(self):
palette_list = self._load_palette()
return self._get_background_color(palette_list)
def get_fgcolor(self):
palette_list = self._load_palette()
if len(palette_list) > 16:
font_color = palette_list[16]
else:
font_color = Gdk.RGBA(0, 0, 0, 0)
return font_color
def set_colors_from_settings(self, terminal_uuid=None):
bg_color = self.get_bgcolor()
font_color = self.get_fgcolor()
palette_list = self._load_palette()
terminals = self.get_notebook().iter_terminals()
if terminal_uuid:
terminals = [t for t in terminals if t.uuid == terminal_uuid]
for i in terminals:
i.set_color_foreground(font_color)
i.set_color_bold(font_color)
i.set_colors(font_color, bg_color, palette_list[:16])
def set_colors_from_settings_on_page(self, current_terminal_only=False, page_num=None):
"""If page_num is None, sets colors on the current page."""
bg_color = self.get_bgcolor()
font_color = self.get_fgcolor()
palette_list = self._load_palette()
if current_terminal_only:
terminal = self.get_notebook().get_current_terminal()
terminal.set_color_foreground(font_color)
terminal.set_color_bold(font_color)
terminal.set_colors(font_color, bg_color, palette_list[:16])
else:
if page_num is None:
page_num = self.get_notebook().get_current_page()
for terminal in self.get_notebook().get_nth_page(page_num).iter_terminals():
terminal.set_color_foreground(font_color)
terminal.set_color_bold(font_color)
terminal.set_colors(font_color, bg_color, palette_list[:16])
def reset_terminal_custom_colors(
self, current_terminal=False, current_page=False, terminal_uuid=None
):
"""Resets terminal(s) colors to the settings colors.
If current_terminal == False and current_page == False and terminal_uuid is None,
resets colors of all terminals.
"""
terminals = []
if current_terminal:
terminals.append(self.get_notebook().get_current_terminal())
if current_page:
page_num = self.get_notebook().get_current_page()
for t in self.get_notebook().get_nth_page(page_num).iter_terminals():
terminals.append(t)
if terminal_uuid:
for t in self.get_notebook().iter_terminals():
if t.uuid == terminal_uuid:
terminals.append(t)
if not current_terminal and not current_page and not terminal_uuid:
terminals = list(self.get_notebook().iter_terminals())
for i in terminals:
i.reset_custom_colors()
def set_bgcolor(self, bgcolor, current_terminal_only=False):
if isinstance(bgcolor, str):
c = Gdk.RGBA(0, 0, 0, 0)
log.debug("Building Gdk Color from: %r", bgcolor)
c.parse("#" + bgcolor)
bgcolor = c
if not isinstance(bgcolor, Gdk.RGBA):
raise TypeError(f"color should be Gdk.RGBA, is: {bgcolor}")
bgcolor = self._apply_transparency_to_color(bgcolor)
log.debug("setting background color to: %r", bgcolor)
if current_terminal_only:
self.get_notebook().get_current_terminal().set_color_background_custom(bgcolor)
else:
page_num = self.get_notebook().get_current_page()
for terminal in self.get_notebook().get_nth_page(page_num).iter_terminals():
terminal.set_color_background_custom(bgcolor)
def set_fgcolor(self, fgcolor, current_terminal_only=False):
if isinstance(fgcolor, str):
c = Gdk.RGBA(0, 0, 0, 0)
log.debug("Building Gdk Color from: %r", fgcolor)
c.parse("#" + fgcolor)
fgcolor = c
if not isinstance(fgcolor, Gdk.RGBA):
raise TypeError(f"color should be Gdk.RGBA, is: {fgcolor}")
log.debug("setting background color to: %r", fgcolor)
if current_terminal_only:
self.get_notebook().get_current_terminal().set_color_foreground_custom(fgcolor)
else:
page_num = self.get_notebook().get_current_page()
for terminal in self.get_notebook().get_nth_page(page_num).iter_terminals():
terminal.set_color_foreground_custom(fgcolor)
def change_palette_name(self, palette_name):
if isinstance(palette_name, str):
if palette_name not in PALETTES:
log.info("Palette name %s not found", palette_name)
return
log.debug("Settings palette name to %s", palette_name)
self.settings.styleFont.set_string("palette", PALETTES[palette_name])
self.settings.styleFont.set_string("palette-name", palette_name)
self.set_colors_from_settings()
def execute_command(self, command, tab=None):
"""Execute the `command' in the `tab'. If tab is None, the
command will be executed in the currently selected
tab. Command should end with '\n', otherwise it will be
appended to the string.
"""
if not self.get_notebook().has_page():
self.add_tab()
if command[-1] != "\n":
command += "\n"
terminal = self.get_notebook().get_current_terminal()
terminal.feed_child(command)
def execute_command_by_uuid(self, tab_uuid, command):
"""Execute the `command' in the tab whose terminal has the `tab_uuid' uuid"""
if command[-1] != "\n":
command += "\n"
try:
tab_uuid = uuid.UUID(tab_uuid)
(page_index,) = (
index
for index, t in enumerate(self.get_notebook().iter_terminals())
if t.get_uuid() == tab_uuid
)
except ValueError:
pass
else:
terminals = self.get_notebook().get_terminals_for_page(page_index)
for current_vte in terminals:
current_vte.feed_child(command)
def on_window_losefocus(self, window, event):
"""Hides terminal main window when it loses the focus and if
the window_losefocus gconf variable is True.
"""
if not HidePrevention(self.window).may_hide():
return
def hide_window_callback():
value = self.settings.general.get_boolean("window-losefocus")
visible = window.get_property("visible")
self.losefocus_time = get_server_time(self.window)
if visible and value:
log.info("Hiding on focus lose")
self.hide()
def losefocus_callback(sleep_time):
sleep(sleep_time)
if (
self.window.get_property("has-toplevel-focus")
and (self.takefocus_time - self.lazy_losefocus_time) > 0
):
log.debug("Short term losefocus detected. Skip the hidding")
return
if self.window.get_property("visible"):
GLib.idle_add(hide_window_callback)
if self.settings.general.get_boolean("lazy-losefocus"):
self.lazy_losefocus_time = get_server_time(self.window)
thread = Thread(target=losefocus_callback, args=(0.3,))
thread.daemon = True
thread.start()
log.debug("Lazy losefocus check at %s", self.lazy_losefocus_time)
else:
hide_window_callback()
def on_window_takefocus(self, window, event):
self.takefocus_time = get_server_time(self.window)
def show_menu(self, status_icon, button, activate_time):
"""Show the tray icon menu."""
menu = self.get_widget("tray-menu")
menu.popup(None, None, None, Gtk.StatusIcon.position_menu, button, activate_time)
def show_about(self, *args):
# TODO DBUS ONLY
# TODO TRAY ONLY
"""Hides the main window and creates an instance of the About
Dialog.
"""
self.hide()
AboutDialog()
def show_prefs(self, *args):
# TODO DBUS ONLY
# TODO TRAY ONLY
"""Hides the main window and creates an instance of the
Preferences window.
"""
self.hide()
PrefsDialog(self.settings).show()
def is_iconified(self):
# TODO this is "dead" code only gets called to log output or in out commented code
if self.window:
cur_state = int(self.window.get_state())
return bool(cur_state & GDK_WINDOW_STATE_ICONIFIED)
return False
def window_event(self, window, event):
window_state = event.new_window_state
self.fullscreen_manager.set_window_state(window_state)
log.debug("Received window state event: %s", window_state)
def show_hide(self, *args):
"""Toggles the main window visibility"""
log.debug("Show_hide called")
if self.forceHide:
self.forceHide = False
return
if not HidePrevention(self.window).may_hide():
return
if not self.win_prepare():
return
if not self.window.get_property("visible"):
log.debug("Showing the terminal")
self.show()
server_time = get_server_time(self.window)
self.window.get_window().focus(server_time)
self.set_terminal_focus()
return
should_refocus = self.settings.general.get_boolean("window-refocus")
has_focus = self.window.get_window().get_state() & Gdk.WindowState.FOCUSED
if should_refocus and not has_focus:
log.debug("Refocussing the terminal")
server_time = get_server_time(self.window)
self.window.get_window().focus(server_time)
self.set_terminal_focus()
else:
log.debug("Hiding the terminal")
self.hide()
def get_visibility(self):
if self.hidden:
return 0
return 1
def show_focus(self, *args):
self.win_prepare()
self.show()
self.set_terminal_focus()
def win_prepare(self, *args):
event_time = self.hotkeys.get_current_event_time()
if (
not self.settings.general.get_boolean("window-refocus")
and self.window.get_window()
and self.window.get_property("visible")
):
pass
elif (
self.losefocus_time
and not self.settings.general.get_boolean("window-losefocus")
and self.losefocus_time < event_time
):
if (
self.window.get_window()
and self.window.get_property("visible")
and not self.window.get_window().get_state() & Gdk.WindowState.FOCUSED
):
log.debug("DBG: Restoring the focus to the terminal")
self.window.get_window().focus(event_time)
self.set_terminal_focus()
self.losefocus_time = 0
return False
elif (
self.losefocus_time
and self.settings.general.get_boolean("window-losefocus")
and self.losefocus_time >= event_time
and (self.losefocus_time - event_time) < 10
):
self.losefocus_time = 0
return False
# limit rate at which the visibility can be toggled.
if self.prev_showhide_time and event_time and (event_time - self.prev_showhide_time) < 65:
return False
self.prev_showhide_time = event_time
log.debug("")
log.debug("=" * 80)
log.debug("Window display")
if self.window:
cur_state = int(self.window.get_state())
is_sticky = bool(cur_state & GDK_WINDOW_STATE_STICKY)
is_withdrawn = bool(cur_state & GDK_WINDOW_STATE_WITHDRAWN)
is_above = bool(cur_state & GDK_WINDOW_STATE_ABOVE)
is_iconified = self.is_iconified()
log.debug("gtk.gdk.WindowState = %s", cur_state)
log.debug("GDK_WINDOW_STATE_STICKY? %s", is_sticky)
log.debug("GDK_WINDOW_STATE_WITHDRAWN? %s", is_withdrawn)
log.debug("GDK_WINDOW_STATE_ABOVE? %s", is_above)
log.debug("GDK_WINDOW_STATE_ICONIFIED? %s", is_iconified)
return True
return False
def restore_pending_terminal_split(self):
# Restore pending terminal split
# XXX: Consider refactor how to handle failed restore page split
self.pending_restore_page_split = self._failed_restore_page_split
self._failed_restore_page_split = []
for root, box, panes in self.pending_restore_page_split:
if (
self.window.get_property("visible")
and root.get_notebook() == self.notebook_manager.get_current_notebook()
):
root.restore_box_layout(box, panes)
else:
# Consider failed if the window is not visible
self._failed_restore_page_split.append((root, box, panes))
def show(self):
"""Shows the main window and grabs the focus on it."""
self.hidden = False
# setting window in all desktops
window_rect = RectCalculator.set_final_window_rect(self.settings, self.window)
self.window.stick()
# add tab must be called before window.show to avoid a
# blank screen before adding the tab.
if not self.get_notebook().has_page():
self.add_tab()
self.window.set_keep_below(False)
# move the window even when in fullscreen-mode
log.debug("Moving window to: %r", window_rect)
self.window.move(window_rect.x, window_rect.y)
# this works around an issue in fluxbox
if not self.fullscreen_manager.is_fullscreen():
self.settings.general.triggerOnChangedValue(self.settings.general, "window-height")
time = get_server_time(self.window)
# TODO PORT this
# When minized, the window manager seems to refuse to resume
# log.debug("self.window: %s. Dir=%s", type(self.window), dir(self.window))
# is_iconified = self.is_iconified()
# if is_iconified:
# log.debug("Is iconified. Ubuntu Trick => "
# "removing skip_taskbar_hint and skip_pager_hint "
# "so deiconify can work!")
# self.get_widget('window-root').set_skip_taskbar_hint(False)
# self.get_widget('window-root').set_skip_pager_hint(False)
# self.get_widget('window-root').set_urgency_hint(False)
# log.debug("get_skip_taskbar_hint: {}".format(
# self.get_widget('window-root').get_skip_taskbar_hint()))
# log.debug("get_skip_pager_hint: {}".format(
# self.get_widget('window-root').get_skip_pager_hint()))
# log.debug("get_urgency_hint: {}".format(
# self.get_widget('window-root').get_urgency_hint()))
# glib.timeout_add_seconds(1, lambda: self.timeout_restore(time))
#
log.debug("order to present and deiconify")
self.window.present()
self.window.deiconify()
self.window.show()
self.window.get_window().focus(time)
self.window.set_type_hint(Gdk.WindowTypeHint.DOCK)
self.window.set_type_hint(Gdk.WindowTypeHint.NORMAL)
# This is here because vte color configuration works only after the
# widget is shown.
self.settings.styleFont.triggerOnChangedValue(self.settings.styleFont, "color")
self.settings.styleBackground.triggerOnChangedValue(self.settings.styleBackground, "color")
log.debug("Current window position: %r", self.window.get_position())
self.restore_pending_terminal_split()
self.execute_hook("show")
def hide_from_remote(self):
"""
Hides the main window of the terminal and sets the visible
flag to False.
"""
log.debug("hide from remote")
self.forceHide = True
self.hide()
def show_from_remote(self):
"""Show the main window of the terminal and sets the visible
flag to False.
"""
log.debug("show from remote")
self.forceHide = True
self.show()
def hide(self):
"""Hides the main window of the terminal and sets the visible
flag to False.
"""
if not HidePrevention(self.window).may_hide():
return
self.hidden = True
self.get_widget("window-root").unstick()
self.window.hide() # Don't use hide_all here!
# Hide popover
self.notebook_manager.get_current_notebook().popover.hide()
def force_move_if_shown(self):
if not self.hidden:
# when displayed, GTK might refuse to move the window (X or Y position). Just hide and
# redisplay it so the final position is correct
log.debug("FORCING HIDE")
self.hide()
log.debug("FORCING SHOW")
self.show()
# -- configuration --
def load_config(self, terminal_uuid=None):
""" "Just a proxy for all the configuration stuff."""
user_data = {}
if terminal_uuid:
user_data["terminal_uuid"] = terminal_uuid
self.settings.general.triggerOnChangedValue(
self.settings.general, "use-trayicon", user_data=user_data
)
self.settings.general.triggerOnChangedValue(
self.settings.general, "prompt-on-quit", user_data=user_data
)
self.settings.general.triggerOnChangedValue(
self.settings.general, "prompt-on-close-tab", user_data=user_data
)
self.settings.general.triggerOnChangedValue(
self.settings.general, "window-tabbar", user_data=user_data
)
self.settings.general.triggerOnChangedValue(
self.settings.general, "fullscreen-hide-tabbar", user_data=user_data
)
self.settings.general.triggerOnChangedValue(
self.settings.general, "mouse-display", user_data=user_data
)
self.settings.general.triggerOnChangedValue(
self.settings.general, "display-n", user_data=user_data
)
self.settings.general.triggerOnChangedValue(
self.settings.general, "window-ontop", user_data=user_data
)
if not self.fullscreen_manager.is_fullscreen():
self.settings.general.triggerOnChangedValue(
self.settings.general, "window-height", user_data=user_data
)
self.settings.general.triggerOnChangedValue(
self.settings.general, "window-width", user_data=user_data
)
self.settings.general.triggerOnChangedValue(
self.settings.general, "use-scrollbar", user_data=user_data
)
self.settings.general.triggerOnChangedValue(
self.settings.general, "history-size", user_data=user_data
)
self.settings.general.triggerOnChangedValue(
self.settings.general, "infinite-history", user_data=user_data
)
self.settings.general.triggerOnChangedValue(
self.settings.general, "use-vte-titles", user_data=user_data
)
self.settings.general.triggerOnChangedValue(
self.settings.general, "set-window-title", user_data=user_data
)
self.settings.general.triggerOnChangedValue(
self.settings.general, "display-tab-names", user_data=user_data
)
self.settings.general.triggerOnChangedValue(
self.settings.general, "max-tab-name-length", user_data=user_data
)
self.settings.general.triggerOnChangedValue(
self.settings.general, "quick-open-enable", user_data=user_data
)
self.settings.general.triggerOnChangedValue(
self.settings.general, "quick-open-command-line", user_data=user_data
)
self.settings.style.triggerOnChangedValue(
self.settings.style, "cursor-shape", user_data=user_data
)
self.settings.styleFont.triggerOnChangedValue(
self.settings.styleFont, "style", user_data=user_data
)
self.settings.styleFont.triggerOnChangedValue(
self.settings.styleFont, "palette", user_data=user_data
)
self.settings.styleFont.triggerOnChangedValue(
self.settings.styleFont, "palette-name", user_data=user_data
)
self.settings.styleFont.triggerOnChangedValue(
self.settings.styleFont, "allow-bold", user_data=user_data
)
self.settings.general.triggerOnChangedValue(self.settings.general, "background-image-file")
self.settings.general.triggerOnChangedValue(
self.settings.general, "background-image-layout-mode"
)
self.settings.style.triggerOnChangedValue(self.settings.style, "cursor-shape")
self.settings.styleFont.triggerOnChangedValue(self.settings.styleFont, "style")
self.settings.styleFont.triggerOnChangedValue(self.settings.styleFont, "palette")
self.settings.styleFont.triggerOnChangedValue(self.settings.styleFont, "palette-name")
self.settings.styleFont.triggerOnChangedValue(self.settings.styleFont, "allow-bold")
self.settings.styleBackground.triggerOnChangedValue(
self.settings.styleBackground, "transparency", user_data=user_data
)
self.settings.general.triggerOnChangedValue(
self.settings.general, "use-default-font", user_data=user_data
)
self.settings.general.triggerOnChangedValue(
self.settings.general, "compat-backspace", user_data=user_data
)
self.settings.general.triggerOnChangedValue(
self.settings.general, "compat-delete", user_data=user_data
)
def accel_search_terminal(self, *args):
nb = self.get_notebook()
term = nb.get_current_terminal()
box = nb.get_nth_page(nb.find_page_index_by_terminal(term))
# Debounce it
current_time = pytime.time()
if current_time - self.prev_accel_search_terminal_time < 0.3:
return
self.prev_accel_search_terminal_time = current_time
if box.search_revealer.get_reveal_child():
if box.search_entry.has_focus():
box.hide_search_box()
else:
# The box was showed, but out of focus
# Don't hide it, re-grab the focus to search entry
box.search_entry.grab_focus()
else:
box.show_search_box()
def accel_quit(self, *args):
"""Callback to prompt the user whether to quit Guake or not."""
procs = self.notebook_manager.get_running_fg_processes()
tabs = self.notebook_manager.get_n_pages()
notebooks = self.notebook_manager.get_n_notebooks()
prompt_cfg = self.settings.general.get_boolean("prompt-on-quit")
prompt_tab_cfg = self.settings.general.get_int("prompt-on-close-tab")
# "Prompt on tab close" config overrides "prompt on quit" config
if (
prompt_cfg
or (prompt_tab_cfg == PROMPT_PROCESSES and procs)
or (prompt_tab_cfg == PROMPT_ALWAYS)
):
log.debug("Remaining procs=%r", procs)
if PromptQuitDialog(self.window, procs, tabs, notebooks).quit():
log.info("Quitting Guake")
Gtk.main_quit()
else:
log.info("Quitting Guake")
Gtk.main_quit()
def accel_reset_terminal(self, *args):
# TODO KEYBINDINGS ONLY
"""Callback to reset and clean the terminal"""
HidePrevention(self.window).prevent()
current_term = self.get_notebook().get_current_terminal()
current_term.reset(True, True)
HidePrevention(self.window).allow()
return True
def accel_zoom_in(self, *args):
"""Callback to zoom in."""
font = " ".join(self.settings.styleFont.get_string("style").split(" ")[:-1])
new_size = int(self.settings.styleFont.get_string("style").split(" ")[-1]) + 1
self.settings.styleFont.set_string("style", f"{font} {new_size}")
for term in self.get_notebook().iter_terminals():
term.set_font_scale(new_size / (new_size - 1))
return True
def accel_zoom_out(self, *args):
"""Callback to zoom out."""
font = " ".join(self.settings.styleFont.get_string("style").split(" ")[:-1])
new_size = int(self.settings.styleFont.get_string("style").split(" ")[-1]) - 1
self.settings.styleFont.set_string("style", f"{font} {new_size}")
for term in self.get_notebook().iter_terminals():
term.set_font_scale((new_size - 1) / new_size)
return True
def accel_increase_height(self, *args):
"""Callback to increase height."""
height = self.settings.general.get_int("window-height")
self.settings.general.set_int("window-height", min(height + 2, 100))
return True
def accel_decrease_height(self, *args):
"""Callback to decrease height."""
height = self.settings.general.get_int("window-height")
self.settings.general.set_int("window-height", max(height - 2, 0))
return True
def accel_increase_transparency(self, *args):
"""Callback to increase transparency."""
transparency = self.settings.styleBackground.get_int("transparency")
if int(transparency) > 0:
self.settings.styleBackground.set_int("transparency", int(transparency) - 2)
return True
def accel_decrease_transparency(self, *args):
"""Callback to decrease transparency."""
transparency = self.settings.styleBackground.get_int("transparency")
if int(transparency) < MAX_TRANSPARENCY:
self.settings.styleBackground.set_int("transparency", int(transparency) + 2)
return True
def accel_toggle_transparency(self, *args):
"""Callback to toggle transparency."""
self.transparency_toggled = not self.transparency_toggled
self.settings.styleBackground.triggerOnChangedValue(
self.settings.styleBackground, "transparency"
)
return True
def accel_add(self, *args):
"""Callback to add a new tab. Called by the accel key."""
self.add_tab()
return True
def accel_add_home(self, *args):
"""Callback to add a new tab in home directory. Called by the accel key."""
self.add_tab(os.environ["HOME"])
return True
def accel_add_cwd(self, *args):
"""Callback to add a new tab in current directory. Called by the accel key."""
self.add_tab(open_tab_cwd=True)
return True
def accel_prev(self, *args):
"""Callback to go to the previous tab. Called by the accel key."""
if self.get_notebook().get_current_page() == 0:
self.get_notebook().set_current_page(self.get_notebook().get_n_pages() - 1)
else:
self.get_notebook().prev_page()
return True
def accel_next(self, *args):
"""Callback to go to the next tab. Called by the accel key."""
if self.get_notebook().get_current_page() + 1 == self.get_notebook().get_n_pages():
self.get_notebook().set_current_page(0)
else:
self.get_notebook().next_page()
return True
def accel_move_tab_left(self, *args):
# TODO KEYBINDINGS ONLY
"""Callback to move a tab to the left"""
pos = self.get_notebook().get_current_page()
if pos != 0:
self.move_tab(pos, pos - 1)
return True
def accel_move_tab_right(self, *args):
# TODO KEYBINDINGS ONLY
"""Callback to move a tab to the right"""
pos = self.get_notebook().get_current_page()
if pos != self.get_notebook().get_n_pages() - 1:
self.move_tab(pos, pos + 1)
return True
def move_tab(self, old_tab_pos, new_tab_pos):
self.get_notebook().reorder_child(
self.get_notebook().get_nth_page(old_tab_pos), new_tab_pos
)
self.get_notebook().set_current_page(new_tab_pos)
def gen_accel_switch_tabN(self, N):
"""Generates callback (which called by accel key) to go to the Nth tab."""
def callback(*args):
if 0 <= N < self.get_notebook().get_n_pages():
self.get_notebook().set_current_page(N)
return True
return callback
def accel_switch_tab_last(self, *args):
last_tab = self.get_notebook().get_n_pages() - 1
self.get_notebook().set_current_page(last_tab)
return True
def accel_rename_current_tab(self, *args):
"""Callback to show the rename tab dialog. Called by the accel
key.
"""
page_num = self.get_notebook().get_current_page()
page = self.get_notebook().get_nth_page(page_num)
self.get_notebook().get_tab_label(page).on_rename(None)
return True
def accel_copy_clipboard(self, *args):
# TODO KEYBINDINGS ONLY
"""Callback to copy text in the shown terminal. Called by the
accel key.
"""
self.get_notebook().get_current_terminal().copy_clipboard()
return True
def accel_paste_clipboard(self, *args):
# TODO KEYBINDINGS ONLY
"""Callback to paste text in the shown terminal. Called by the
accel key.
"""
self.get_notebook().get_current_terminal().paste_clipboard()
return True
def accel_select_all(self, *args):
self.get_notebook().get_current_terminal().select_all()
return True
def accel_toggle_hide_on_lose_focus(self, *args):
"""Callback toggle whether the window should hide when it loses
focus. Called by the accel key.
"""
if self.settings.general.get_boolean("window-losefocus"):
self.settings.general.set_boolean("window-losefocus", False)
else:
self.settings.general.set_boolean("window-losefocus", True)
return True
def accel_toggle_fullscreen(self, *args):
self.fullscreen_manager.toggle()
return True
def fullscreen(self):
self.fullscreen_manager.fullscreen()
def unfullscreen(self):
self.fullscreen_manager.unfullscreen()
# -- callbacks --
def recompute_tabs_titles(self):
"""Updates labels on all tabs. This is required when `self.display_tab_names`
changes
"""
use_vte_titles = self.settings.general.get_boolean("use-vte-titles")
if not use_vte_titles:
return
# TODO NOTEBOOK this code only works if there is only one terminal in a
# page, this need to be rewritten
for terminal in self.get_notebook().iter_terminals():
page_num = self.get_notebook().page_num(terminal.get_parent())
self.get_notebook().rename_page(page_num, self.compute_tab_title(terminal), False)
def load_cwd_guake_yaml(self, vte) -> dict:
# Read the content of .guake.yml in cwd
if not self.settings.general.get_boolean("load-guake-yml"):
return {}
cwd = Path(vte.get_current_directory())
filename = str(cwd.joinpath(".guake.yml"))
try:
content = self.fm.read_yaml(filename)
except Exception:
log.debug("Unexpected error reading %s.", filename, exc_info=True)
content = {}
if not isinstance(content, dict):
content = {}
return content
def compute_tab_title(self, vte):
"""Compute the tab title"""
guake_yml = self.load_cwd_guake_yaml(vte)
if "title" in guake_yml:
return guake_yml["title"]
vte_title = vte.get_window_title() or _("Terminal")
try:
current_directory = vte.get_current_directory()
if self.display_tab_names == 1 and vte_title.endswith(current_directory):
parts = current_directory.split("/")
parts = [s[:1] for s in parts[:-1]] + [parts[-1]]
vte_title = vte_title[: len(vte_title) - len(current_directory)] + "/".join(parts)
if self.display_tab_names == 2:
vte_title = current_directory.split("/")[-1]
if not vte_title:
vte_title = "(root)"
except OSError:
pass
return TabNameUtils.shorten(vte_title, self.settings)
def check_if_terminal_directory_changed(self, term):
@save_tabs_when_changed
def terminal_directory_changed(self):
# Yep, just used for save tabs when changed
pass
current_directory = term.get_current_directory()
if current_directory != term.directory:
term.directory = current_directory
terminal_directory_changed(self)
def on_terminal_title_changed(self, vte, term):
# box must be a page
if not term.get_parent():
return
# Check if terminal directory has changed
self.check_if_terminal_directory_changed(term)
box = term.get_parent().get_root_box()
use_vte_titles = self.settings.general.get_boolean("use-vte-titles")
if not use_vte_titles:
return
# NOTE: Try our best to find the page_num inside all notebooks
# this may return -1, should be checked ;)
nb = self.get_notebook()
page_num = nb.page_num(box)
for nb in self.notebook_manager.iter_notebooks():
page_num = nb.page_num(box)
if page_num != -1:
break
# if tab has been renamed by user, don't override.
if not getattr(box, "custom_label_set", False):
title = self.compute_tab_title(vte)
nb.rename_page(page_num, title, False)
self.update_window_title(title)
else:
text = nb.get_tab_text_page(box)
if text:
self.update_window_title(text)
def update_window_title(self, title):
if self.settings.general.get_boolean("set-window-title") is True:
self.window.set_title(title)
else:
self.window.set_title(self.default_window_title)
# TODO PORT reimplement drag and drop text on terminal
# -- tab related functions --
def close_tab(self, *args):
"""Closes the current tab."""
prompt_cfg = self.settings.general.get_int("prompt-on-close-tab")
self.get_notebook().delete_page_current(prompt=prompt_cfg)
def rename_tab_uuid(self, term_uuid, new_text, user_set=True):
"""Rename an already added tab by its UUID"""
term_uuid = uuid.UUID(term_uuid)
(page_index,) = (
index
for index, t in enumerate(self.get_notebook().iter_terminals())
if t.get_uuid() == term_uuid
)
self.get_notebook().rename_page(page_index, new_text, user_set)
def get_index_from_uuid(self, term_uuid):
term_uuid = uuid.UUID(term_uuid)
for index, t in enumerate(self.get_notebook().iter_terminals()):
if t.get_uuid() == term_uuid:
return index
return -1
def rename_current_tab(self, new_text, user_set=False):
page_num = self.get_notebook().get_current_page()
self.get_notebook().rename_page(page_num, new_text, user_set)
def terminal_spawned(self, notebook, terminal, pid):
self.load_config(terminal_uuid=terminal.uuid)
terminal.handler_ids.append(
terminal.connect("window-title-changed", self.on_terminal_title_changed, terminal)
)
# Use to detect if directory has changed
terminal.directory = terminal.get_current_directory()
@save_tabs_when_changed
def add_tab(self, directory=None, open_tab_cwd=False):
"""Adds a new tab to the terminal notebook."""
position = None
if self.settings.general.get_boolean("new-tab-after"):
position = 1 + self.get_notebook().get_current_page()
self.get_notebook().new_page_with_focus(
directory, position=position, open_tab_cwd=open_tab_cwd
)
def find_tab(self, directory=None):
log.debug("find")
# TODO SEARCH
HidePrevention(self.window).prevent()
search_text = Gtk.TextView()
dialog = Gtk.Dialog(
_("Find"),
self.window,
Gtk.DialogFlags.DESTROY_WITH_PARENT,
(
_("Forward"),
RESPONSE_FORWARD,
_("Backward"),
RESPONSE_BACKWARD,
Gtk.STOCK_CANCEL,
Gtk.ResponseType.NONE,
),
)
dialog.vbox.pack_end(search_text, True, True, 0)
dialog.buffer = search_text.get_buffer()
dialog.connect("response", self._dialog_response_callback)
search_text.show()
search_text.grab_focus()
dialog.show_all()
# Note: beware to reset preventHide when closing the find dialog
def _dialog_response_callback(self, dialog, response_id):
if response_id not in (RESPONSE_FORWARD, RESPONSE_BACKWARD):
dialog.destroy()
HidePrevention(self.window).allow()
return
start, end = dialog.buffer.get_bounds()
search_string = start.get_text(end)
log.debug(
"Searching for %r %s\n",
search_string,
"forward" if response_id == RESPONSE_FORWARD else "backward",
)
current_term = self.get_notebook().get_current_terminal()
log.debug("type: %r", type(current_term))
log.debug("dir: %r", dir(current_term))
current_term.search_set_gregex()
current_term.search_get_gregex()
def page_deleted(self, *args):
if not self.get_notebook().has_page():
self.hide()
# avoiding the delay on next Guake show request
self.add_tab()
else:
self.set_terminal_focus()
self.was_deleted_tab = True
self.display_tab_names = self.settings.general.get_int("display-tab-names")
self.recompute_tabs_titles()
def set_terminal_focus(self):
"""Grabs the focus on the current tab."""
self.get_notebook().set_current_page(self.get_notebook().get_current_page())
def get_selected_uuidtab(self):
# TODO DBUS ONLY
"""Returns the uuid of the current selected terminal"""
page_num = self.get_notebook().get_current_page()
terminals = self.get_notebook().get_terminals_for_page(page_num)
return str(terminals[0].get_uuid())
def open_link_under_terminal_cursor(self, *args):
current_term = self.get_notebook().get_current_terminal()
if current_term is None:
return
url = current_term.get_link_under_terminal_cursor()
current_term.browse_link_under_cursor(url)
def search_on_web(self, *args):
"""Search for the selected text on the web"""
# TODO KEYBINDINGS ONLY
current_term = self.get_notebook().get_current_terminal()
if current_term.get_has_selection():
current_term.copy_clipboard()
guake_clipboard = Gtk.Clipboard.get_default(self.window.get_display())
search_query = guake_clipboard.wait_for_text()
search_query = quote_plus(search_query)
if search_query:
# TODO: search provider should be selectable.
search_url = f"https://www.google.com/search?q={search_query}&safe=off"
Gtk.show_uri(self.window.get_screen(), search_url, get_server_time(self.window))
return True
def set_tab_position(self, *args):
if self.settings.general.get_boolean("tab-ontop"):
self.get_notebook().set_tab_pos(Gtk.PositionType.TOP)
else:
self.get_notebook().set_tab_pos(Gtk.PositionType.BOTTOM)
def execute_hook(self, event_name):
"""Execute shell commands related to current event_name"""
hook = self.settings.hooks.get_string(f"{event_name}")
if hook is not None and hook != "":
hook = hook.split()
try:
with subprocess.Popen(hook):
pass
except OSError as oserr:
if oserr.errno == 8:
log.error(
"Hook execution failed! Check shebang at first line of %s!",
hook,
)
log.debug(traceback.format_exc())
else:
log.error(str(oserr))
except Exception as e:
log.error("hook execution failed! %s", e)
log.debug(traceback.format_exc())
else:
log.debug("hook on event %s has been executed", event_name)
@save_tabs_when_changed
def on_page_reorder(self, notebook, child, page_num):
# Yep, just used for save tabs when changed
pass
def get_xdg_config_directory(self):
xdg_config_home = os.environ.get("XDG_CONFIG_HOME", "~/.config")
return Path(xdg_config_home, "guake").expanduser()
def save_tabs(self, filename="session.json"):
config = {
"schema_version": TABS_SESSION_SCHEMA_VERSION,
"timestamp": int(pytime.time()),
"workspace": {},
}
for key, nb in self.notebook_manager.get_notebooks().items():
tabs = []
for index in range(nb.get_n_pages()):
try:
page = nb.get_nth_page(index)
panes = []
page.save_box_layout(page.child, panes)
tabs.append(
{
"panes": panes,
"label": nb.get_tab_text_index(index),
"custom_label_set": getattr(page, "custom_label_set", False),
}
)
except FileNotFoundError:
# discard same broken tabs
pass
# NOTE: Maybe we will have frame inside the workspace in future
# So lets use list to store the tabs (as for each frame)
config["workspace"][key] = [tabs]
if not self.get_xdg_config_directory().exists():
self.get_xdg_config_directory().mkdir(parents=True)
session_file = self.get_xdg_config_directory() / filename
with session_file.open("w", encoding="utf-8") as f:
json.dump(config, f, ensure_ascii=False, indent=4)
log.info("Guake tabs saved to %s", session_file)
def restore_tabs(self, filename="session.json", suppress_notify=False):
session_file = self.get_xdg_config_directory() / filename
if not session_file.exists():
log.info("Cannot find session.json file")
return
with session_file.open(encoding="utf-8") as f:
try:
config = json.load(f)
except Exception:
log.warning("%s is broken", session_file)
shutil.copy(
session_file,
self.get_xdg_config_directory() / f"{filename}.bak",
)
img_filename = pixmapfile("guake-notification.png")
notifier.showMessage(
_("Guake Terminal"),
_(
"Your {session_filename} file is broken, backup to {session_filename}.bak"
).format(session_filename=filename),
img_filename,
)
return
# Check schema_version exist
if "schema_version" not in config:
img_filename = pixmapfile("guake-notification.png")
notifier.showMessage(
_("Guake Terminal"),
_(
"Tabs session restore abort.\n"
"Your session file ({session_filename}) missing schema_version as key"
).format(session_filename=session_file),
img_filename,
)
return
# Check schema version is not higher than current version
if config["schema_version"] > TABS_SESSION_SCHEMA_VERSION:
img_filename = pixmapfile("guake-notification.png")
notifier.showMessage(
_("Guake Terminal"),
_(
"Tabs session restore abort.\n"
"Your session file schema version is higher than current version "
"({session_file_schema_version} > {current_schema_version})."
).format(
session_file_schema_version=config["schema_version"],
current_schema_version=TABS_SESSION_SCHEMA_VERSION,
),
img_filename,
)
return
# Disable auto save tabs
v = self.settings.general.get_boolean("save-tabs-when-changed")
self.settings.general.set_boolean("save-tabs-when-changed", False)
# Restore all tabs for all workspaces
self.pending_restore_page_split = []
self._failed_restore_page_split = []
try:
for key, frames in config["workspace"].items():
nb = self.notebook_manager.get_notebook(int(key))
current_pages = nb.get_n_pages()
# Restore each frames' tabs from config
# NOTE: If frame implement in future, we will need to update this code
for tabs in frames:
for index, tab in enumerate(tabs):
if tab.get("panes", False):
box, page_num, term = nb.new_page_with_focus(
label=tab["label"], user_set=tab["custom_label_set"], empty=True
)
box.restore_box_layout(box.child, tab["panes"])
else:
directory = (
tab["panes"][0]["directory"]
if len(tab.get("panes", [])) == 1
else tab.get("directory", None)
)
nb.new_page_with_focus(directory, tab["label"], tab["custom_label_set"])
# Remove original pages in notebook
for i in range(current_pages):
nb.delete_page(0)
except KeyError:
log.warning("%s schema is broken", session_file)
shutil.copy(
session_file,
self.get_xdg_config_directory() / f"{filename}.bak",
)
with (self.get_xdg_config_directory() / f"{filename}.log.err").open(
"w", encoding="utf-8"
) as f:
traceback.print_exc(file=f)
img_filename = pixmapfile("guake-notification.png")
notifier.showMessage(
_("Guake Terminal"),
_(
"Your {session_filename} schema is broken, backup to {session_filename}.bak, "
"and error message has been saved to {session_filename}.log.err.".format(
session_filename=filename
)
),
img_filename,
)
# Reset auto save tabs
self.settings.general.set_boolean("save-tabs-when-changed", v)
# Notify the user
if self.settings.general.get_boolean("restore-tabs-notify") and not suppress_notify:
filename = pixmapfile("guake-notification.png")
notifier.showMessage(_("Guake Terminal"), _("Your tabs has been restored!"), filename)
log.info("Guake tabs restored from %s", session_file)
def load_background_image(self, filename):
self.background_image_manager.load_from_file(filename)
| 61,498
|
Python
|
.py
| 1,343
| 35.102755
| 100
| 0.611872
|
Guake/guake
| 4,406
| 575
| 405
|
GPL-2.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,064
|
gsettings.py
|
Guake_guake/guake/gsettings.py
|
# -*- coding: utf-8; -*-
"""
Copyright (C) 2007-2013 Guake authors
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
import os
import gi
gi.require_version("Vte", "2.91") # vte-0.38
from gi.repository import Gio
from gi.repository import Pango
from gi.repository import Vte
from guake.utils import RectCalculator
log = logging.getLogger(__name__)
class GSettingHandler:
"""Handles gconf changes, if any gconf variable is changed, a
different method is called to handle this change.
"""
def __init__(self, guake_inst):
"""Constructor of GConfHandler, just add the guake dir to the
gconf client and bind the keys to its handler methods.
"""
self.guake = guake_inst
self.settings = guake_inst.settings
settings = self.settings
# Notification is not required for mouse_display/display-n because
# set_final_window_rect polls gconf and is called whenever Guake is
# shown or resized
settings.general.onChangedValue("use-trayicon", self.trayicon_toggled)
settings.general.onChangedValue("window-ontop", self.ontop_toggled)
settings.general.onChangedValue("tab-ontop", self.tab_ontop_toggled)
settings.general.onChangedValue("window-tabbar", self.tabbar_toggled)
settings.general.onChangedValue(
"fullscreen-hide-tabbar", self.fullscreen_hide_tabbar_toggled
)
settings.general.onChangedValue("window-height", self.size_changed)
settings.general.onChangedValue("window-width", self.size_changed)
settings.general.onChangedValue("window-valignment", self.alignment_changed)
settings.general.onChangedValue("window-halignment", self.alignment_changed)
settings.general.onChangedValue("window-vertical-displacement", self.alignment_changed)
settings.general.onChangedValue("window-horizontal-displacement", self.alignment_changed)
settings.style.onChangedValue("cursor-blink-mode", self.cursor_blink_mode_changed)
settings.style.onChangedValue("cursor-shape", self.cursor_shape_changed)
settings.general.onChangedValue("background-image-file", self.background_image_file_changed)
settings.general.onChangedValue(
"background-image-layout-mode", self.background_image_layout_mode_changed
)
settings.general.onChangedValue("use-scrollbar", self.scrollbar_toggled)
settings.general.onChangedValue("history-size", self.history_size_changed)
settings.general.onChangedValue("infinite-history", self.infinite_history_changed)
settings.general.onChangedValue("scroll-output", self.keystroke_output)
settings.general.onChangedValue("scroll-keystroke", self.keystroke_toggled)
settings.general.onChangedValue("use-default-font", self.default_font_toggled)
settings.styleFont.onChangedValue("style", self.fstyle_changed)
settings.styleFont.onChangedValue("palette", self.fpalette_changed)
settings.styleFont.onChangedValue("allow-bold", self.allow_bold_toggled)
settings.styleFont.onChangedValue("bold-is-bright", self.bold_is_bright_toggled)
settings.styleFont.onChangedValue("cell-height-scale", self.cell_height_scale_value_changed)
settings.styleFont.onChangedValue("cell-width-scale", self.cell_width_scale_value_changed)
settings.styleBackground.onChangedValue("transparency", self.bgtransparency_changed)
settings.general.onChangedValue("compat-backspace", self.backspace_changed)
settings.general.onChangedValue("compat-delete", self.delete_changed)
settings.general.onChangedValue("custom-command_file", self.custom_command_file_changed)
settings.general.onChangedValue("max-tab-name-length", self.max_tab_name_length_changed)
settings.general.onChangedValue("display-tab-names", self.display_tab_names_changed)
settings.general.onChangedValue("hide-tabs-if-one-tab", self.hide_tabs_if_one_tab_changed)
def custom_command_file_changed(self, settings, key, user_data):
self.guake.load_custom_commands()
def trayicon_toggled(self, settings, key, user_data):
"""If the gconf var use_trayicon be changed, this method will
be called and will show/hide the trayicon.
"""
if hasattr(self.guake.tray_icon, "set_status"):
self.guake.tray_icon.set_status(settings.get_boolean(key))
else:
self.guake.tray_icon.set_visible(settings.get_boolean(key))
def ontop_toggled(self, settings, key, user_data):
"""If the gconf var window_ontop be changed, this method will
be called and will set the keep_above attribute in guake's
main window.
"""
self.guake.window.set_keep_above(settings.get_boolean(key))
def tab_ontop_toggled(self, settings, key, user_data):
"""tab_ontop changed"""
self.guake.set_tab_position()
def tabbar_toggled(self, settings, key, user_data):
"""If the gconf var use_tabbar be changed, this method will be
called and will show/hide the tabbar.
"""
if settings.get_boolean(key):
if settings.get_boolean(key):
self.guake.get_notebook().hide_tabbar_if_one_tab()
else:
self.guake.notebook_manager.set_notebooks_tabbar_visible(True)
else:
self.guake.notebook_manager.set_notebooks_tabbar_visible(False)
def fullscreen_hide_tabbar_toggled(self, settings, key, user_data):
"""If the gconf var fullscreen_hide_tabbar be changed, this method will be
called and will show/hide the tabbar when fullscreen.
"""
if not self.guake.fullscreen_manager.is_fullscreen():
return
if settings.get_boolean(key):
self.guake.notebook_manager.set_notebooks_tabbar_visible(False)
else:
if settings.get_boolean(key):
self.guake.get_notebook().hide_tabbar_if_one_tab()
else:
self.guake.notebook_manager.set_notebooks_tabbar_visible(True)
def alignment_changed(self, settings, key, user_data):
"""If the gconf var window_halignment be changed, this method will
be called and will call the move function in guake.
"""
RectCalculator.set_final_window_rect(self.settings, self.guake.window)
self.guake.set_tab_position()
self.guake.force_move_if_shown()
def size_changed(self, settings, key, user_data):
"""If the gconf var window_height or window_width are changed,
this method will be called and will call the resize function
in guake.
"""
RectCalculator.set_final_window_rect(self.settings, self.guake.window)
def cursor_blink_mode_changed(self, settings, key, user_data):
"""Called when cursor blink mode settings has been changed"""
terminal = (
self.guake.notebook_manager.get_terminal_by_uuid(user_data.get("terminal_uuid"))
if user_data
else None
)
terminals = (terminal,) if terminal else self.guake.notebook_manager.iter_terminals()
for term in terminals:
term.set_property("cursor-blink-mode", settings.get_int(key))
def cursor_shape_changed(self, settings, key, user_data):
"""Called when the cursor shape settings has been changed"""
terminal = (
self.guake.notebook_manager.get_terminal_by_uuid(user_data.get("terminal_uuid"))
if user_data
else None
)
terminals = (terminal,) if terminal else self.guake.notebook_manager.iter_terminals()
for term in terminals:
term.set_property("cursor-shape", settings.get_int(key))
def background_image_file_changed(self, settings, key, user_data):
"""Called when the background image file settings has been changed"""
filename = settings.get_string(key)
if not filename or os.path.exists(filename):
self.guake.background_image_manager.load_from_file(settings.get_string(key))
def background_image_layout_mode_changed(self, settings, key, user_data):
"""Called when the background image layout mode settings has been changed"""
self.guake.background_image_manager.layout_mode = settings.get_int(key)
def scrollbar_toggled(self, settings, key, user_data):
"""If the gconf var use_scrollbar be changed, this method will
be called and will show/hide scrollbars of all terminals open.
"""
terminal = (
self.guake.notebook_manager.get_terminal_by_uuid(user_data.get("terminal_uuid"))
if user_data
else None
)
terminals = (terminal,) if terminal else self.guake.notebook_manager.iter_terminals()
for term in terminals:
# There is an hbox in each tab of the main notebook and it
# contains a Terminal and a Scrollbar. Since only have the
# Terminal here, we're going to use this to get the
# scrollbar and hide/show it.
hbox = term.get_parent()
if hbox is None:
continue
terminal, scrollbar = hbox.get_children()
if settings.get_boolean(key):
scrollbar.show()
else:
scrollbar.hide()
def history_size_changed(self, settings, key, user_data):
"""If the gconf var history_size be changed, this method will
be called and will set the scrollback_lines property of all
terminals open.
"""
lines = settings.get_int(key)
terminal = (
self.guake.notebook_manager.get_terminal_by_uuid(user_data.get("terminal_uuid"))
if user_data
else None
)
terminals = (terminal,) if terminal else self.guake.notebook_manager.iter_terminals()
for i in terminals:
i.set_scrollback_lines(lines)
def infinite_history_changed(self, settings, key, user_data):
if settings.get_boolean(key):
lines = -1
else:
lines = self.settings.general.get_int("history-size")
terminal = (
self.guake.notebook_manager.get_terminal_by_uuid(user_data.get("terminal_uuid"))
if user_data
else None
)
terminals = (terminal,) if terminal else self.guake.notebook_manager.iter_terminals()
for i in terminals:
i.set_scrollback_lines(lines)
def keystroke_output(self, settings, key, user_data):
"""If the gconf var scroll_output be changed, this method will
be called and will set the scroll_on_output in all terminals
open.
"""
terminal = (
self.guake.notebook_manager.get_terminal_by_uuid(user_data.get("terminal_uuid"))
if user_data
else None
)
terminals = (terminal,) if terminal else self.guake.notebook_manager.iter_terminals()
for i in terminals:
i.set_scroll_on_output(settings.get_boolean(key))
def keystroke_toggled(self, settings, key, user_data):
"""If the gconf var scroll_keystroke be changed, this method
will be called and will set the scroll_on_keystroke in all
terminals open.
"""
terminal = (
self.guake.notebook_manager.get_terminal_by_uuid(user_data.get("terminal_uuid"))
if user_data
else None
)
terminals = (terminal,) if terminal else self.guake.notebook_manager.iter_terminals()
for i in terminals:
i.set_scroll_on_keystroke(settings.get_boolean(key))
def default_font_toggled(self, settings, key, user_data):
"""If the gconf var use_default_font be changed, this method
will be called and will change the font style to the gnome
default or to the chosen font in style/font/style in all
terminals open.
"""
font_name = None
if settings.get_boolean(key):
gio_settings = Gio.Settings(schema="org.gnome.desktop.interface")
font_name = gio_settings.get_string("monospace-font-name")
else:
font_name = self.settings.styleFont.get_string("style")
if not font_name:
log.error("Error: unable to find font name (%s)", font_name)
return
font = Pango.FontDescription(font_name)
if not font:
log.error("Error: unable to load font (%s)", font_name)
return
terminal = (
self.guake.notebook_manager.get_terminal_by_uuid(user_data.get("terminal_uuid"))
if user_data
else None
)
terminals = (terminal,) if terminal else self.guake.notebook_manager.iter_terminals()
for i in terminals:
i.set_font(font)
def allow_bold_toggled(self, settings, key, user_data):
"""If the gconf var allow_bold is changed, this method will be called
and will change the VTE terminal o.
displaying characters in bold font.
"""
terminal = (
self.guake.notebook_manager.get_terminal_by_uuid(user_data.get("terminal_uuid"))
if user_data
else None
)
terminals = (terminal,) if terminal else self.guake.notebook_manager.iter_terminals()
for term in terminals:
term.set_allow_bold(settings.get_boolean(key))
def bold_is_bright_toggled(self, settings, key, user_data):
"""If the dconf var bold_is_bright is changed, this method will be called
and will change the VTE terminal to toggle auto-brightened bold text.
"""
try:
terminal = self.guake.notebook_manager.get_terminal_by_uuid(
user_data.get("terminal_uuid") if user_data else None
)
terminals = (terminal,) if terminal else self.guake.notebook_manager.iter_terminals()
for term in terminals:
term.set_bold_is_bright(settings.get_boolean(key))
except: # pylint: disable=bare-except
log.error("set_bold_is_bright not supported by your version of VTE")
def cell_height_scale_value_changed(self, settings, key, user_data):
"""If the gconf var style/font/cell-height-scale be changed, this
method will be called and will set terminal height scale properties
in all terminals.
"""
height_scale = settings.get_double(key)
try:
terminal = self.guake.notebook_manager.get_terminal_by_uuid(
user_data.get("terminal_uuid") if user_data else None
)
terminals = (terminal,) if terminal else self.guake.notebook_manager.iter_terminals()
for term in terminals:
term.set_cell_height_scale(height_scale)
except: # pylint: disable=bare-except
log.error("set_cell_height_scale not supported by your version of VTE")
def cell_width_scale_value_changed(self, settings, key, user_data):
"""If the gconf var style/font/cell-width-scale be changed, this
method will be called and will set terminal width scale properties
in all terminals.
"""
width_scale = settings.get_double(key)
try:
terminal = self.guake.notebook_manager.get_terminal_by_uuid(
user_data.get("terminal_uuid") if user_data else None
)
terminals = (terminal,) if terminal else self.guake.notebook_manager.iter_terminals()
for term in terminals:
term.set_cell_width_scale(width_scale)
except: # pylint: disable=bare-except
log.error("set_cell_width_scale not supported by your version of VTE")
def palette_font_and_background_color_toggled(self, settings, key, user_data):
"""If the gconf var use_palette_font_and_background_color be changed, this method
will be called and will change the font color and the background color to the color
defined in the palette.
"""
self.settings.styleFont.triggerOnChangedValue(self.settings.styleFont, "palette")
def fstyle_changed(self, settings, key, user_data):
"""If the gconf var style/font/style be changed, this method
will be called and will change the font style in all terminals
open.
"""
terminal_uuid = user_data.get("terminal_uuid") if user_data else None
if terminal_uuid:
terminal = self.guake.notebook_manager.get_terminal_by_uuid(terminal_uuid)
terminals = (terminal,) if terminal else ()
else:
terminals = self.guake.notebook_manager.iter_terminals()
if self.settings.general.get_boolean("use-default-font"):
gio_settings = Gio.Settings(schema="org.gnome.desktop.interface")
font_name = gio_settings.get_string("monospace-font-name")
else:
font_name = settings.get_string(key)
font = Pango.FontDescription(font_name)
for i in terminals:
i.set_font(font)
def fpalette_changed(self, settings, key, user_data):
"""If the gconf var style/font/palette be changed, this method
will be called and will change the color scheme in all terminals
open.
"""
self.guake.set_colors_from_settings(
terminal_uuid=user_data.get("terminal_uuid") if user_data else None
)
def bgtransparency_changed(self, settings, key, user_data):
"""If the gconf var style/background/transparency be changed, this
method will be called and will set the saturation and transparency
properties in all terminals open.
"""
self.guake.set_background_color_from_settings(
terminal_uuid=user_data.get("terminal_uuid") if user_data else None
)
def getEraseBinding(self, str):
if str == "auto":
return Vte.EraseBinding(0)
if str == "ascii-backspace":
return Vte.EraseBinding(1)
if str == "ascii-delete":
return Vte.EraseBinding(2)
if str == "delete-sequence":
return Vte.EraseBinding(3)
if str == "tty":
return Vte.EraseBinding(4)
def backspace_changed(self, settings, key, user_data):
"""If the gconf var compat_backspace be changed, this method
will be called and will change the binding configuration in
all terminals open.
"""
terminal = (
self.guake.notebook_manager.get_terminal_by_uuid(user_data.get("terminal_uuid"))
if user_data
else None
)
terminals = (terminal,) if terminal else self.guake.notebook_manager.iter_terminals()
for i in terminals:
i.set_backspace_binding(self.getEraseBinding(settings.get_string(key)))
def delete_changed(self, settings, key, user_data):
"""If the gconf var compat_delete be changed, this method
will be called and will change the binding configuration in
all terminals open.
"""
terminal = (
self.guake.notebook_manager.get_terminal_by_uuid(user_data.get("terminal_uuid"))
if user_data
else None
)
terminals = (terminal,) if terminal else self.guake.notebook_manager.iter_terminals()
for i in terminals:
i.set_delete_binding(self.getEraseBinding(settings.get_string(key)))
def max_tab_name_length_changed(self, settings, key, user_data):
"""If the gconf var max_tab_name_length be changed, this method will
be called and will set the tab name length limit.
"""
# avoid get window title before terminal is ready
if self.guake.notebook_manager.get_current_notebook().get_current_terminal() is None:
return
# avoid get window title before terminal is ready
if (
self.guake.notebook_manager.get_current_notebook()
.get_current_terminal()
.get_window_title()
is None
):
return
self.guake.recompute_tabs_titles()
def display_tab_names_changed(self, settings, key, user_data):
"""If the gconf var display-tab-names was changed, this method will
be called and will update tab names.
"""
self.guake.display_tab_names = settings.get_int("display-tab-names")
self.guake.recompute_tabs_titles()
def hide_tabs_if_one_tab_changed(self, settings, key, user_data):
"""If the gconf var hide-tabs-if-one-tab was changed, this method will
be called and will show/hide the tab bar if necessary
"""
self.guake.get_notebook().hide_tabbar_if_one_tab()
| 21,496
|
Python
|
.py
| 425
| 41.021176
| 100
| 0.661481
|
Guake/guake
| 4,406
| 575
| 405
|
GPL-2.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,065
|
theme.py
|
Guake_guake/guake/theme.py
|
import itertools
import logging
import os
from pathlib import Path
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import GLib
from gi.repository import Gdk
from gi.repository import Gtk
from textwrap import dedent
from guake.paths import GUAKE_THEME_DIR
log = logging.getLogger(__name__)
# Reference:
# https://gitlab.gnome.org/GNOME/gnome-tweaks/blob/master/gtweak/utils.py (GPL)
def get_resource_dirs(resource):
"""Returns a list of all known resource dirs for a given resource.
:param str resource:
Name of the resource (e.g. "themes")
:return:
A list of resource dirs
"""
dirs = [
os.path.join(dir, resource)
for dir in itertools.chain(
GLib.get_system_data_dirs(), GUAKE_THEME_DIR, GLib.get_user_data_dir()
)
]
dirs += [os.path.join(os.path.expanduser("~"), f".{resource}")]
return [Path(dir) for dir in dirs if os.path.isdir(dir)]
def list_all_themes():
return sorted(
{
x.name
for theme_dir in get_resource_dirs("themes")
for x in theme_dir.iterdir()
if x.is_dir()
}
)
def select_gtk_theme(settings):
gtk_settings = Gtk.Settings.get_default()
if settings.general.get_boolean("gtk-use-system-default-theme"):
log.debug("Using system default theme")
gtk_settings.reset_property("gtk-theme-name")
gtk_settings.set_property("gtk-application-prefer-dark-theme", False)
return
gtk_theme_name = settings.general.get_string("gtk-theme-name")
log.debug("Wanted GTK theme: %r", gtk_theme_name)
gtk_settings.set_property("gtk-theme-name", gtk_theme_name)
prefer_dark_theme = settings.general.get_boolean("gtk-prefer-dark-theme")
log.debug("Prefer dark theme: %r", prefer_dark_theme)
gtk_settings.set_property("gtk-application-prefer-dark-theme", prefer_dark_theme)
def get_gtk_theme(settings):
gtk_theme_name = settings.general.get_string("gtk-theme-name")
prefer_dark_theme = settings.general.get_boolean("gtk-prefer-dark-theme")
return (gtk_theme_name, "dark" if prefer_dark_theme else None)
def patch_gtk_theme(style_context, settings):
theme_name, variant = get_gtk_theme(settings)
def rgba_to_hex(color):
return f"#{''.join(f'{int(i*255):02x}' for i in (color.red, color.green, color.blue))}"
selected_fg_color = rgba_to_hex(style_context.lookup_color("theme_selected_fg_color")[1])
selected_bg_color = rgba_to_hex(style_context.lookup_color("theme_selected_bg_color")[1])
log.debug(
"Patching theme '%s' (prefer dark = '%r'), overriding tab 'checked' state': "
"foreground: %r, background: %r",
theme_name,
"yes" if variant == "dark" else "no",
selected_fg_color,
selected_bg_color,
)
css_data = dedent(
f"""
.custom_tab:checked {{
color: {selected_fg_color};
background: {selected_bg_color};
}}
"""
).encode()
style_provider = Gtk.CssProvider()
style_provider.load_from_data(css_data)
Gtk.StyleContext.add_provider_for_screen(
Gdk.Screen.get_default(),
style_provider,
Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION,
)
| 3,268
|
Python
|
.py
| 84
| 32.690476
| 95
| 0.662872
|
Guake/guake
| 4,406
| 575
| 405
|
GPL-2.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,066
|
support.py
|
Guake_guake/guake/support.py
|
# -*- coding: utf-8 -*-
import os
import gi
gi.require_version("Gdk", "3.0")
from gi.repository import Gdk
from guake import gtk_version
from guake import guake_version
from guake import vte_runtime_version
from guake import vte_version
def horizonal_line():
print("-" * 50)
def populate_display(display):
screen = display.get_default_screen()
print(f"Display: {display.get_name()}")
print()
# pylint: disable=R1719
print(f"RGBA visual: {True if screen.get_rgba_visual() else False}")
print()
print(f"Composited: {screen.is_composited()}")
print()
n_monitors = display.get_n_monitors()
for i in range(n_monitors):
monitor = display.get_monitor(i)
v = " ".join(j for j in (monitor.get_manufacturer(), monitor.get_model()) if j)
print(f"* Monitor: {i} - {v}")
# Geometry
rect = monitor.get_geometry()
scale = monitor.get_scale_factor()
v = f"{rect.width} x {rect.height}{' % 2' if scale == 2 else ''} at {rect.x}, {rect.y}"
print(f" * Geometry:\t\t{v}")
# Size
v = f"{monitor.get_width_mm()} x {monitor.get_height_mm()} mm²"
print(f" * Size:\t\t{v}")
# Primary
print(f" * Primary:\t\t{monitor.is_primary()}")
# Refresh rate
if monitor.get_refresh_rate():
v = f"{0.001 * monitor.get_refresh_rate()} Hz"
else:
v = "unknown"
print(f" * Refresh rate:\t{v}")
# Subpixel layout
print(f" * Subpixel layout:\t{monitor.get_subpixel_layout().value_nick}")
def get_version():
display = Gdk.Display.get_default()
print(f"Guake Version:\t\t{guake_version()}")
print()
print(f"Vte Version:\t\t{vte_version()}")
print()
print(f"Vte Runtime Version:\t{vte_runtime_version()}")
print()
horizonal_line()
print(f"GTK+ Version:\t\t{gtk_version()}")
print()
print(f"GDK Backend:\t\t{str(display).split(' ', maxsplit=1)[0]}")
print()
horizonal_line()
def get_desktop_session():
print(f"Desktop Session: {os.environ.get('DESKTOP_SESSION')}")
print()
horizonal_line()
def get_display():
display = Gdk.Display.get_default()
populate_display(display)
def print_support():
print("<details><summary>$ guake --support</summary>")
print()
get_version()
get_desktop_session()
get_display()
| 2,409
|
Python
|
.py
| 70
| 28.614286
| 95
| 0.615551
|
Guake/guake
| 4,406
| 575
| 405
|
GPL-2.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,067
|
main.py
|
Guake_guake/guake/main.py
|
# -*- coding: utf-8; -*-
"""
Copyright (C) 2007-2013 Guake authors
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
"""
# You can put calls to p() everywhere in this page to inspect timing
#
# import inspect
# import time
# g_start = time.time()
# def p():
# print(time.time() - g_start, __file__, inspect.currentframe().f_back.f_lineno)
import builtins
import logging
import os
import signal
import subprocess
import sys
import uuid
from locale import gettext
builtins.__dict__["_"] = gettext
from argparse import ArgumentParser
log = logging.getLogger(__name__)
# Force use X11 backend under wayland before any import of GDK through dependencies.
# This could fix weird problems under Wayland.
# But if user set the environment variable GUAKE_ENABLE_WAYLAND, then force
# use Wayland backend.
os.environ["GDK_BACKEND"] = "x11"
if "GUAKE_ENABLE_WAYLAND" in os.environ:
os.environ["GDK_BACKEND"] = "wayland"
from guake.globals import NAME
from guake.globals import bindtextdomain
from guake.support import print_support
from guake.utils import restore_preferences
from guake.utils import save_preferences
# When we are in the document generation on readthedocs,
# we do not have paths.py generated
try:
from guake.paths import LOCALE_DIR
bindtextdomain(NAME, LOCALE_DIR)
except: # pylint: disable=bare-except
pass
# pylint: disable=import-outside-toplevel
def main():
"""Parses the command line parameters and decide if dbus methods
should be called or not. If there is already a guake instance
running it will be used and a True value will be returned,
otherwise, false will be returned.
"""
# Force to xterm-256 colors for compatibility with some old command line programs
os.environ["TERM"] = "xterm-256color"
os.environ["TERM_PROGRAM"] = "guake"
# do not use version keywords here, pbr might be slow to find the version of Guake module
parser = ArgumentParser()
parser.add_argument(
"path",
nargs="?",
help="Add a new tab at designated path when a path is provided and no other options",
)
parser.add_argument(
"-V",
"--version",
dest="version",
action="store_true",
default=False,
help=_("Show Guake version number and exit"),
)
parser.add_argument(
"-v",
"--verbose",
dest="verbose",
action="store_true",
default=False,
help=_("Enable verbose logging"),
)
parser.add_argument(
"-f",
"--fullscreen",
dest="fullscreen",
action="store_true",
default=False,
help=_("Put Guake in fullscreen mode"),
)
parser.add_argument(
"--unfullscreen",
dest="unfullscreen",
action="store_true",
default=False,
help=_("Put Guake out from fullscreen mode"),
)
parser.add_argument(
"-t",
"--toggle-visibility",
dest="show_hide",
action="store_true",
default=False,
help=_("Toggles the visibility of the terminal window"),
)
parser.add_argument(
"--is-visible",
dest="is_visible",
action="store_true",
default=False,
help=_("Return 1 if Guake is visible, 0 otherwise"),
)
parser.add_argument(
"--show",
dest="show",
action="store_true",
default=False,
help=_("Shows Guake main window"),
)
parser.add_argument(
"--hide",
dest="hide",
action="store_true",
default=False,
help=_("Hides Guake main window"),
)
parser.add_argument(
"-p",
"--preferences",
dest="show_preferences",
action="store_true",
default=False,
help=_("Shows Guake preference window"),
)
parser.add_argument(
"-a",
"--about",
dest="show_about",
action="store_true",
default=False,
help=_("Shows Guake's about info"),
)
parser.add_argument(
"-n",
"--new-tab",
dest="new_tab",
action="store",
default="",
help=_("Add a new tab (with current directory set to NEW_TAB)"),
)
parser.add_argument(
"-s",
"--select-tab",
dest="select_tab",
action="store",
default="",
help=_("Select a tab (SELECT_TAB is the index of the tab)"),
)
parser.add_argument(
"-g",
"--selected-tab",
dest="selected_tab",
action="store_true",
default=False,
help=_("Return the selected tab index."),
)
parser.add_argument(
"-x",
"--uuid-index",
dest="uuid_index",
action="store",
default="",
help=_("Return the index of the tab with the given terminal UUID, -1 if not found"),
)
parser.add_argument(
"-l",
"--selected-tablabel",
dest="selected_tablabel",
action="store_true",
default=False,
help=_("Return the selected tab label."),
)
parser.add_argument(
"-S",
"--select-terminal",
dest="select_terminal",
metavar="TERMINAL_INDEX",
action="store",
default="",
help=_(
"Select a specific terminal in a split tab. "
+ "Only useful with split terminals (TERMINAL_INDEX is the index of the tab)"
),
)
parser.add_argument(
"--selected-terminal",
dest="selected_terminal",
action="store_true",
default=False,
help=_("Return the selected terminal index."),
)
parser.add_argument(
"--split-vertical",
dest="split_vertical",
metavar="SPLIT_PERCENTAGE",
action="store",
type=int,
nargs="?",
const=50,
default=None,
choices=range(1, 100),
help=_("Split the selected tab vertically. Optional input split percentage for the width."),
)
parser.add_argument(
"--split-horizontal",
dest="split_horizontal",
metavar="SPLIT_PERCENTAGE",
action="store",
type=int,
nargs="?",
const=50,
default=None,
choices=range(1, 100),
help=_(
"Split the selected tab horizontally. Optional input split percentage for the height."
),
)
parser.add_argument(
"-e",
"--execute-command",
dest="command",
action="store",
default="",
help=_("Execute an arbitrary command in a new tab."),
)
parser.add_argument(
"-i",
"--tab-index",
dest="tab_index",
action="store",
default="0",
help=_("Specify the tab to rename. Default is 0. Can be used to select tab by UUID."),
)
parser.add_argument(
"--bgcolor",
dest="bgcolor",
action="store",
default="",
help=_("Set the hexadecimal (#rrggbb) background color of " "the selected tab."),
)
parser.add_argument(
"--fgcolor",
dest="fgcolor",
action="store",
default="",
help=_("Set the hexadecimal (#rrggbb) foreground color of the " "selected tab."),
)
parser.add_argument(
"--bgcolor-current",
dest="bgcolor_current",
action="store",
default="",
help=_("Set the hexadecimal (#rrggbb) background color of " "the current terminal."),
)
parser.add_argument(
"--fgcolor-current",
dest="fgcolor_current",
action="store",
default="",
help=_("Set the hexadecimal (#rrggbb) foreground color of " "the current terminal."),
)
parser.add_argument(
"--change-palette",
dest="palette_name",
action="store",
default="",
help=_("Change Guake palette scheme"),
)
parser.add_argument(
"--reset-colors",
dest="reset_colors",
action="store_true",
default=False,
help=_("Set colors from settings."),
)
parser.add_argument(
"--reset-colors-current",
dest="reset_colors_current",
action="store_true",
default=False,
help=_("Set colors of the current terminal from settings."),
)
parser.add_argument(
"--rename-tab",
dest="rename_tab",
metavar="TITLE",
action="store",
default="",
help=_(
"Rename the specified tab by --tab-index. Reset to default if TITLE is "
'a single dash "-".'
),
)
parser.add_argument(
"-r",
"--rename-current-tab",
dest="rename_current_tab",
metavar="TITLE",
action="store",
default="",
help=_("Rename the current tab. Reset to default if TITLE is a " 'single dash "-".'),
)
parser.add_argument(
"-q",
"--quit",
dest="quit",
action="store_true",
default=False,
help=_("Says to Guake go away =("),
)
parser.add_argument(
"-u",
"--no-startup-script",
dest="execute_startup_script",
action="store_false",
default=True,
help=_("Do not execute the start up script"),
)
parser.add_argument(
"--save-preferences",
dest="save_preferences",
action="store",
default=None,
help=_("Save Guake preferences to this filename"),
)
parser.add_argument(
"--restore-preferences",
dest="restore_preferences",
action="store",
default=None,
help=_("Restore Guake preferences from this file"),
)
parser.add_argument(
"--support",
dest="support",
action="store_true",
default=False,
help=_("Show support information"),
)
# checking mandatory dependencies
missing_deps = False
try:
import gi
gi.require_version("Gtk", "3.0")
gi.require_version("Gdk", "3.0")
except ValueError:
print("[ERROR] missing mandatory dependency: GtK 3.0")
missing_deps = True
try:
gi.require_version("Vte", "2.91") # vte-0.42
except ValueError:
print("[ERROR] missing mandatory dependency: Vte >= 0.42")
missing_deps = True
try:
gi.require_version("Keybinder", "3.0")
except ValueError:
print("[ERROR] missing mandatory dependency: Keybinder 3")
missing_deps = True
if missing_deps:
print(
"[ERROR] missing at least one system dependencies. "
"You need to install additional packages for Guake to run"
)
print(
"[ERROR] On Debian/Ubuntu you need to install the following libraries:\n"
" sudo apt-get install -y --no-install-recommends \\\n"
" gir1.2-keybinder-3.0 \\\n"
" gir1.2-notify-0.7 \\\n"
" gir1.2-vte-2.91 \\\n"
" gir1.2-wnck-3.0 \\\n"
" libkeybinder-3.0-0 \\\n"
" libutempter0 \\\n"
" python3 \\\n"
" python3-dbus \\\n"
" python3-gi \\\n"
" python3-pip"
)
sys.exit(1)
options = parser.parse_args()
if options.version:
from guake import gtk_version
from guake import guake_version
from guake import vte_version
from guake import vte_runtime_version
print(f"Guake Terminal: {guake_version()}")
print(f"VTE: {vte_version()}")
print(f"VTE runtime: {vte_runtime_version()}")
print(f"Gtk: {gtk_version()}")
sys.exit(0)
if options.save_preferences and options.restore_preferences:
parser.error("options --save-preferences and --restore-preferences are mutually exclusive")
if options.save_preferences:
save_preferences(options.save_preferences)
sys.exit(0)
elif options.restore_preferences:
restore_preferences(options.restore_preferences)
sys.exit(0)
if options.support:
print_support()
sys.exit(0)
import dbus
from guake.dbusiface import DBUS_NAME
from guake.dbusiface import DBUS_PATH
from guake.dbusiface import DbusManager
from guake.guake_logging import setupLogging
instance = None
# Trying to get an already running instance of guake. If it is not
# possible, lets create a new instance. This function will return
# a boolean value depending on this decision.
try:
bus = dbus.SessionBus()
remote_object = bus.get_object(DBUS_NAME, DBUS_PATH)
already_running = True
except dbus.DBusException:
# can now configure the logging
setupLogging(options.verbose)
# COLORTERM is an environment variable set by some terminal emulators such as
# gnome-terminal.
# To avoid confusing applications running inside Guake, clean up COLORTERM at startup.
if "COLORTERM" in os.environ:
del os.environ["COLORTERM"]
log.info("Guake not running, starting it")
# late loading of the Guake object, to speed up dbus comm
from guake.guake_app import Guake
instance = Guake()
remote_object = DbusManager(instance)
already_running = False
only_show_hide = True
if options.fullscreen:
remote_object.fullscreen()
if options.unfullscreen:
remote_object.unfullscreen()
if options.show:
remote_object.show_from_remote()
if options.hide:
remote_object.hide_from_remote()
if options.is_visible:
visibility = remote_object.get_visibility()
sys.stdout.write(f"{visibility}\n")
only_show_hide = options.show
if options.show_preferences:
remote_object.show_prefs()
only_show_hide = options.show
if options.new_tab and not options.command:
remote_object.add_tab(options.new_tab)
only_show_hide = options.show
if options.path and len(sys.argv) == 2:
remote_object.add_tab(os.path.abspath(options.path))
only_show_hide = options.show
if options.select_tab:
selected = int(options.select_tab)
tab_count = int(remote_object.get_tab_count())
if 0 <= selected < tab_count:
remote_object.select_tab(selected)
else:
sys.stderr.write(f"invalid index: {selected}\n")
only_show_hide = options.show
if options.selected_tab:
selected = remote_object.get_selected_tab()
sys.stdout.write(f"{selected}\n")
only_show_hide = options.show
if options.selected_tablabel:
selectedlabel = remote_object.get_selected_tablabel()
sys.stdout.write(f"{selectedlabel}\n")
only_show_hide = options.show
if options.uuid_index:
selectedIndex = remote_object.get_index_from_uuid(options.uuid_index)
sys.stdout.write(f"{selectedIndex}\n")
only_show_hide = options.show
if options.split_vertical:
if options.command:
remote_object.v_split_current_terminal_with_command(
options.command, options.split_vertical
)
else:
remote_object.v_split_current_terminal(options.split_vertical)
only_show_hide = options.show
if options.split_horizontal:
if options.command:
remote_object.h_split_current_terminal_with_command(
options.command, options.split_horizontal
)
else:
remote_object.h_split_current_terminal(options.split_horizontal)
only_show_hide = options.show
if options.selected_terminal:
selected = remote_object.get_selected_terminal()
sys.stdout.write(f"{selected}\n")
only_show_hide = options.show
if options.select_terminal:
selected = int(options.select_terminal)
term_count = int(remote_object.get_term_count())
if 0 <= selected < term_count:
remote_object.select_terminal(selected)
else:
sys.stderr.write(f"invalid index: {selected}\n")
only_show_hide = options.show
if options.command and not (options.split_vertical or options.split_horizontal):
remote_object.execute_command(options.command)
only_show_hide = options.show
if options.tab_index and options.rename_tab:
try:
remote_object.rename_tab_uuid(str(uuid.UUID(options.tab_index)), options.rename_tab)
except ValueError:
remote_object.rename_tab(int(options.tab_index), options.rename_tab)
only_show_hide = options.show
if options.bgcolor:
remote_object.set_bgcolor(options.bgcolor)
only_show_hide = options.show
if options.fgcolor:
remote_object.set_fgcolor(options.fgcolor)
only_show_hide = options.show
if options.bgcolor_current:
remote_object.set_bgcolor_current_terminal(options.bgcolor_current)
only_show_hide = options.show
if options.fgcolor_current:
remote_object.set_fgcolor_current_terminal(options.fgcolor_current)
only_show_hide = options.show
if options.palette_name:
remote_object.change_palette_name(options.palette_name)
only_show_hide = options.show
if options.reset_colors:
remote_object.reset_colors()
only_show_hide = options.show
if options.reset_colors_current:
remote_object.reset_colors_current()
only_show_hide = options.show
if options.rename_current_tab:
remote_object.rename_current_tab(options.rename_current_tab)
only_show_hide = options.show
if options.show_about:
remote_object.show_about()
only_show_hide = options.show
if options.quit:
try:
remote_object.quit()
return True
except dbus.DBusException:
return True
if already_running and only_show_hide:
# here we know that guake was called without any parameter and
# it is already running, so, lets toggle its visibility.
remote_object.show_hide()
if options.execute_startup_script:
if not already_running:
startup_script = instance.settings.general.get_string("startup-script")
if startup_script:
log.info("Calling startup script: %s", startup_script)
pid = subprocess.Popen( # pylint: disable=consider-using-with
[startup_script],
shell=False,
stdin=None,
stdout=None,
stderr=None,
close_fds=True,
)
log.info("Startup script started with pid: %s", pid)
# Please ensure this is the last line !!!!
else:
log.info("--no-startup-script argument defined, so don't execute the startup script")
if already_running:
log.info("Guake is already running")
return already_running
def exec_main():
if not main():
log.debug("Running main gtk loop")
signal.signal(signal.SIGINT, signal.SIG_DFL)
# Load gi pretty late, to speed up as much as possible the parsing of the option for DBus
# comm through command line
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk
Gtk.main()
if __name__ == "__main__":
exec_main()
| 20,165
|
Python
|
.py
| 589
| 26.314092
| 100
| 0.61209
|
Guake/guake
| 4,406
| 575
| 405
|
GPL-2.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,068
|
paths.py.in
|
Guake_guake/guake/paths.py.in
|
# -*- coding: utf-8; -*-
"""
Copyright (C) 2007-2013 Guake authors
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 guake
import logging
import os
import subprocess
import sys
log = logging.getLogger(__name__)
def get_default_package_root():
packagedir = guake.__path__[0]
dirname = os.path.join(os.path.dirname(packagedir))
return os.path.abspath(dirname)
def get_data_files_dir():
d = os.path.dirname(sys.modules["guake"].__file__)
p = os.path.basename(os.path.abspath(os.path.join(os.path.dirname(d), "..")))
if p in ["site-packages", "dist-packages"]:
# current "guake" package has been installed in a prefix structure (/usr, /usr/local or
# ~/.local/)
loc_dir = os.path.abspath(os.path.join(d, "..", "..", "..", ".."))
loc_dir = os.path.join(loc_dir, "share", "guake")
if os.path.exists(loc_dir):
return loc_dir
return d
def get_default_data_dir():
d = os.path.join(get_data_files_dir(), "data")
log.debug("Using guake data directory: %s", d)
return d
def get_default_locale_dir():
d = os.path.join(get_data_files_dir(), "po")
log.debug("Using guake image directory: %s", d)
return d
def get_default_image_dir():
d = os.path.join(get_default_data_dir(), 'pixmaps')
log.debug("Using guake image directory: %s", d)
return d
def get_default_glade_dir():
d = get_default_data_dir()
log.debug("Using guake glade directory: %s", d)
return d
def get_default_schema_dir():
d = get_default_data_dir()
log.debug("Using guake scheme directory: %s", d)
return d
def get_default_theme_dir():
d = os.path.join(get_default_data_dir(), 'theme')
log.debug("Using guake theme directory: %s", d)
return d
LOCALE_DIR = {{ LOCALE_DIR }}
IMAGE_DIR = {{ IMAGE_DIR }}
GLADE_DIR = {{ GLADE_DIR }}
SCHEMA_DIR = {{ SCHEMA_DIR }}
GUAKE_THEME_DIR = {{ GUAKE_THEME_DIR }}
LOGIN_DESTOP_PATH = {{ LOGIN_DESTOP_PATH }}
AUTOSTART_FOLDER = {{ AUTOSTART_FOLDER }}
def try_to_compile_glib_schemas():
log.info("Compiling schema: %s", SCHEMA_DIR)
subprocess.check_call(["glib-compile-schemas", "--strict", SCHEMA_DIR])
| 2,809
|
Python
|
.py
| 71
| 35.957746
| 95
| 0.691485
|
Guake/guake
| 4,406
| 575
| 405
|
GPL-2.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,069
|
callbacks.py
|
Guake_guake/guake/callbacks.py
|
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gdk
from gi.repository import Gtk
from guake.about import AboutDialog
from guake.dialogs import SaveTerminalDialog
from guake.globals import ENGINES
from guake.prefs import PrefsDialog
from guake.utils import FullscreenManager
from guake.utils import HidePrevention
from guake.utils import get_server_time
from urllib.parse import quote_plus
class TerminalContextMenuCallbacks:
def __init__(self, terminal, window, settings, notebook):
self.terminal = terminal
self.window = window
self.settings = settings
self.notebook = notebook
def on_copy_clipboard(self, *args):
self.terminal.copy_clipboard()
def on_copy_url_clipboard(self, *args):
url = self.terminal.get_link_under_cursor()
if url is not None:
clipboard = Gtk.Clipboard.get_default(self.window.get_display())
clipboard.set_text(url, len(url))
def on_paste_clipboard(self, *args):
self.terminal.paste_clipboard()
def on_toggle_fullscreen(self, *args):
FullscreenManager(self.settings, self.window).toggle()
def on_save_to_file(self, *args):
SaveTerminalDialog(self.terminal, self.window).run()
def on_reset_terminal(self, *args):
self.terminal.reset(True, True)
def on_find(self):
# this is not implemented yet
pass
def on_open_link(self, *args):
self.terminal.browse_link_under_cursor()
def on_search_on_web(self, *args):
if self.terminal.get_has_selection():
self.terminal.copy_clipboard()
clipboard = Gtk.Clipboard.get_default(self.window.get_display())
query = clipboard.wait_for_text()
query = quote_plus(query)
# nothing selected
if not query:
return
selected = self.settings.general.get_int("search-engine")
# if custom search is selected, get the engine from the 'custom-search-engine' setting
if selected not in ENGINES:
engine = self.settings.general.get_string("custom-search-engine")
else:
engine = ENGINES[selected]
# put the query at the end of the url
search_url = "https://" + engine + query
Gtk.show_uri(self.window.get_screen(), search_url, get_server_time(self.window))
def on_quick_open(self, *args):
if self.terminal.get_has_selection():
self.terminal.quick_open()
def on_command_selected(self, command):
self.terminal.execute_command(command)
def on_show_preferences(self, *args):
self.notebook.guake.hide()
PrefsDialog(self.settings).show()
def on_show_about(self, *args):
self.notebook.guake.hide()
AboutDialog()
def on_quit(self, *args):
self.notebook.guake.accel_quit()
def on_split_vertical(self, *args):
self.terminal.get_parent().split_v(50)
def on_split_horizontal(self, *args):
self.terminal.get_parent().split_h(50)
def on_close_terminal(self, *args):
self.terminal.kill()
class NotebookScrollCallback:
def __init__(self, notebook):
self.notebook = notebook
def on_scroll(self, widget, event):
direction = event.get_scroll_direction().direction
if direction is Gdk.ScrollDirection.DOWN or direction is Gdk.ScrollDirection.RIGHT:
self.notebook.next_page()
else:
self.notebook.prev_page()
# important to return True to stop propagation of the event
# from the label up to the notebook
return True
class MenuHideCallback:
def __init__(self, window):
self.window = window
def on_hide(self, *args):
HidePrevention(self.window).allow()
| 3,841
|
Python
|
.py
| 92
| 33.663043
| 98
| 0.661113
|
Guake/guake
| 4,406
| 575
| 405
|
GPL-2.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,070
|
common.py
|
Guake_guake/guake/common.py
|
# -*- coding: utf-8; -*-
"""
Copyright (C) 2007-2013 Guake authors
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
import os
import gi
gi.require_version("Gtk", "3.0")
gi.require_version("Vte", "2.91") # vte-0.38
from gi.repository import Gtk
from guake.paths import GLADE_DIR
from guake.paths import IMAGE_DIR
log = logging.getLogger(__name__)
__all__ = [
"get_binaries_from_path",
"gladefile",
"hexify_color",
"pixmapfile",
"ShowableError",
]
def ShowableError(parent, title, msg, exit_code=1):
d = Gtk.MessageDialog(
parent,
Gtk.DialogFlags.MODAL | Gtk.DialogFlags.DESTROY_WITH_PARENT,
Gtk.MessageType.WARNING,
Gtk.ButtonsType.CLOSE,
)
d.set_markup(f"<b><big>{title}</big></b>")
d.format_secondary_markup(msg)
d.run()
d.destroy()
def pixmapfile(x):
f = os.path.join(IMAGE_DIR, x)
if not os.path.exists(f):
raise IOError(f"No such file or directory: {f}")
return os.path.abspath(f)
def gladefile(x):
f = os.path.join(GLADE_DIR, x)
if not os.path.exists(f):
raise IOError(f"No such file or directory: {f}")
return os.path.abspath(f)
def hexify_color(c):
def h(x):
return hex(x).replace("0x", "").zfill(4)
return f"#{h(c.red)}{h(c.green)}{h(c.blue)}"
def get_binaries_from_path(compiled_re):
ret = []
for i in os.environ.get("PATH", "").split(os.pathsep):
if os.path.isdir(i):
for j in os.listdir(i):
if compiled_re.match(j):
ret.append(os.path.join(i, j))
return ret
def shell_quote(text):
"""quote text (filename) for inserting into a shell"""
return r"\'".join(f"'{p}'" for p in text.split("'"))
def clamp(value, lower, upper):
return max(min(value, upper), lower)
| 2,453
|
Python
|
.py
| 70
| 30.671429
| 68
| 0.682069
|
Guake/guake
| 4,406
| 575
| 405
|
GPL-2.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,071
|
simplegladeapp.py
|
Guake_guake/guake/simplegladeapp.py
|
# -*- coding: utf-8; -*-
"""
Copyright (C) 2007-2013 Guake authors
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 os
import re
import sys
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk
import tokenize
class SimpleGladeApp:
def __init__(self, path, root=None, domain=None):
"""
Load a glade file specified by glade_filename, using root as
root widget and domain as the domain for translations.
If it receives extra named arguments (argname=value), then they are used
as attributes of the instance.
path:
path to a glade filename.
If glade_filename cannot be found, then it will be searched in the
same directory of the program (sys.argv[0])
root:
the name of the widget that is the root of the user interface,
usually a window or dialog (a top level widget).
If None or ommited, the full user interface is loaded.
domain:
A domain to use for loading translations.
If None or ommited, no translation is loaded.
"""
if os.path.isfile(path):
self.glade_path = path
else:
glade_dir = os.path.dirname(sys.argv[0])
self.glade_path = os.path.join(glade_dir, path)
self.glade = None
self.builder = Gtk.Builder()
self.builder.add_from_file(self.glade_path)
if root:
self.main_widget = self.builder.get_object(root)
self.main_widget.show_all()
else:
self.main_widget = None
self.normalize_names()
# Widgets are loaded and can be refered as self.widget_name
def __repr__(self):
class_name = self.__class__.__name__
if self.main_widget:
root = Gtk.Widget.get_name(self.main_widget)
return f'{class_name}(path="{self.glade_path}", root="{root}")'
return f'{class_name}(path="{self.glade_path}")'
def add_callbacks(self, callbacks_proxy):
"""
It uses the methods of callbacks_proxy as callbacks.
The callbacks are specified by using:
Properties window -> Signals tab
in glade-2 (or any other gui designer like gazpacho).
Methods of classes inheriting from SimpleGladeApp are used as
callbacks automatically.
callbacks_proxy:
an instance with methods as code of callbacks.
It means it has methods like on_button1_clicked, on_entry1_activate, etc.
"""
self.builder.connect_signals(callbacks_proxy)
def normalize_names(self):
"""
It is internally used to normalize the name of the widgets.
It means a widget named foo:vbox-dialog in glade
is refered self.vbox_dialog in the code.
It also sets a data "prefixes" with the list of
prefixes a widget has for each widget.
"""
for widget in self.get_widgets():
if isinstance(widget, Gtk.Buildable):
widget_name = Gtk.Buildable.get_name(widget)
prefixes_name_l = widget_name.split(":")
prefixes = prefixes_name_l[:-1]
widget_api_name = prefixes_name_l[-1]
widget_api_name = "_".join(re.findall(tokenize.Name, widget_api_name))
widget_name = Gtk.Buildable.set_name(widget, widget_api_name)
if hasattr(self, widget_api_name):
raise AttributeError(
f"instance {self} already has an attribute {widget_api_name}"
)
setattr(self, widget_api_name, widget)
if prefixes:
# TODO is is a guess
Gtk.Buildable.set_data(widget, "prefixes", prefixes)
def custom_handler(self, glade, function_name, widget_name, str1, str2, int1, int2):
"""
Generic handler for creating custom widgets, internally used to
enable custom widgets (custom widgets of glade).
The custom widgets have a creation function specified in design time.
Those creation functions are always called with str1,str2,int1,int2 as
arguments, that are values specified in design time.
Methods of classes inheriting from SimpleGladeApp are used as
creation functions automatically.
If a custom widget has create_foo as creation function, then the
method named create_foo is called with str1,str2,int1,int2 as arguments.
"""
try:
handler = getattr(self, function_name)
return handler(str1, str2, int1, int2)
except AttributeError:
return None
def gtk_widget_show(self, widget, *args):
"""
Predefined callback.
The widget is showed.
Equivalent to widget.show()
"""
widget.show()
def gtk_widget_hide(self, widget, *args):
"""
Predefined callback.
The widget is hidden.
Equivalent to widget.hide()
"""
widget.hide()
return True
def gtk_widget_grab_focus(self, widget, *args):
"""
Predefined callback.
The widget grabs the focus.
Equivalent to widget.grab_focus()
"""
widget.grab_focus()
def gtk_widget_destroy(self, widget, *args):
"""
Predefined callback.
The widget is destroyed.
Equivalent to widget.destroy()
"""
widget.destroy()
def gtk_window_activate_default(self, widget, *args):
"""
Predefined callback.
The default widget of the window is activated.
Equivalent to window.activate_default()
"""
widget.activate_default()
def gtk_true(self, *args):
"""
Predefined callback.
Equivalent to return True in a callback.
Useful for stopping propagation of signals.
"""
return True
def gtk_false(self, *args):
"""
Predefined callback.
Equivalent to return False in a callback.
"""
return False
def gtk_main_quit(self, *args):
"""
Predefined callback.
Equivalent to self.quit()
"""
self.quit()
def main(self):
"""
Starts the main loop of processing events.
The default implementation calls gtk.main()
Useful for applications that needs a non gtk main loop.
For example, applications based on gstreamer needs to override
this method with gst.main()
Do not directly call this method in your programs.
Use the method run() instead.
"""
Gtk.main()
def quit(self, *args):
"""
Quit processing events.
The default implementation calls gtk.main_quit()
Useful for applications that needs a non gtk main loop.
For example, applications based on gstreamer needs to override
this method with gst.main_quit()
"""
Gtk.main_quit()
def run(self):
"""
Starts the main loop of processing events checking for Control-C.
The default implementation checks wheter a Control-C is pressed,
then calls on_keyboard_interrupt().
Use this method for starting programs.
"""
try:
self.main()
except KeyboardInterrupt:
sys.exit()
def get_widget(self, widget_name):
return self.builder.get_object(widget_name)
def get_widgets(self):
return self.builder.get_objects()
| 8,245
|
Python
|
.py
| 207
| 30.7343
| 88
| 0.627596
|
Guake/guake
| 4,406
| 575
| 405
|
GPL-2.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,072
|
split_utils.py
|
Guake_guake/guake/split_utils.py
|
# -*- coding: utf-8; -*-
"""
Copyright (C) 2018 Mario Aichinger <aichingm@gmail.com>
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 gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk
from guake.boxes import DualTerminalBox
from guake.boxes import RootTerminalBox
class FocusMover:
THRESHOLD = 10
BORDER_THICKNESS = 2
def __init__(self, window):
self.window = window
def move_right(self, terminal):
window_width, window_height = self.window.get_size()
tx, ty, tw, th = self.list_allocation(terminal)
if tx + tw == window_width:
return
search_x = tx + tw + FocusMover.THRESHOLD
search_y = ty + (th / 2) - FocusMover.BORDER_THICKNESS
for term in terminal.get_parent().get_root_box().iter_terminals():
sx, sy, sw, sh = self.list_allocation(term)
if sx <= search_x <= sx + sw and sy <= search_y <= sy + sh:
term.grab_focus()
def move_left(self, terminal):
window_width, window_height = self.window.get_size()
tx, ty, tw, th = self.list_allocation(terminal)
if tx == 0:
return
search_x = tx - FocusMover.THRESHOLD
search_y = ty + (th / 2) - FocusMover.BORDER_THICKNESS
for term in terminal.get_parent().get_root_box().iter_terminals():
sx, sy, sw, sh = self.list_allocation(term)
if sx <= search_x <= sx + sw and sy <= search_y <= sy + sh:
term.grab_focus()
def move_up(self, terminal):
window_width, window_height = self.window.get_size()
tx, ty, tw, th = self.list_allocation(terminal)
if ty == 0:
return
search_x = tx + (tw / 2) - FocusMover.BORDER_THICKNESS
search_y = ty - FocusMover.THRESHOLD
for term in terminal.get_parent().get_root_box().iter_terminals():
sx, sy, sw, sh = self.list_allocation(term)
if sx <= search_x <= sx + sw and sy <= search_y <= sy + sh:
term.grab_focus()
def move_down(self, terminal):
window_width, window_height = self.window.get_size()
tx, ty, tw, th = self.list_allocation(terminal)
if ty + th == window_height:
return
search_x = tx + (tw / 2) - FocusMover.BORDER_THICKNESS
search_y = ty + th + FocusMover.THRESHOLD
for term in terminal.get_parent().get_root_box().iter_terminals():
sx, sy, sw, sh = self.list_allocation(term)
if sx <= search_x <= sx + sw and sy <= search_y <= sy + sh:
term.grab_focus()
def list_allocation(self, terminal):
terminal_rect = terminal.get_parent().get_allocation()
x, y = terminal.get_parent().translate_coordinates(self.window, 0, 0)
return x, y, terminal_rect.width, terminal_rect.height
class SplitMover:
THRESHOLD = 35
STEP = 10
@classmethod
def move_up(cls, terminal):
box = terminal.get_parent()
while not isinstance(box, RootTerminalBox):
box = box.get_parent()
if (
isinstance(box, DualTerminalBox)
and box.get_orientation() == Gtk.Orientation.VERTICAL
):
_, __, p = cls.list_allocation(box)
if p - SplitMover.STEP > SplitMover.THRESHOLD:
box.set_position(p - SplitMover.STEP)
else:
box.set_position(SplitMover.THRESHOLD)
break
@classmethod
def move_down(cls, terminal):
box = terminal.get_parent()
while not isinstance(box, RootTerminalBox):
box = box.get_parent()
if (
isinstance(box, DualTerminalBox)
and box.get_orientation() == Gtk.Orientation.VERTICAL
):
_, y, p = cls.list_allocation(box)
if p + SplitMover.STEP < y - SplitMover.THRESHOLD:
box.set_position(p + SplitMover.STEP)
else:
box.set_position(y - SplitMover.THRESHOLD)
break
@classmethod
def move_right(cls, terminal):
box = terminal.get_parent()
while not isinstance(box, RootTerminalBox):
box = box.get_parent()
if (
isinstance(box, DualTerminalBox)
and box.get_orientation() == Gtk.Orientation.HORIZONTAL
):
x, _, p = cls.list_allocation(box)
if p + SplitMover.STEP < x - SplitMover.THRESHOLD:
box.set_position(p + SplitMover.STEP)
else:
box.set_position(x - SplitMover.THRESHOLD)
break
@classmethod
def move_left(cls, terminal):
box = terminal.get_parent()
while not isinstance(box, RootTerminalBox):
box = box.get_parent()
if (
isinstance(box, DualTerminalBox)
and box.get_orientation() == Gtk.Orientation.HORIZONTAL
):
_, __, p = cls.list_allocation(box)
if p - SplitMover.STEP > SplitMover.THRESHOLD:
box.set_position(p - SplitMover.STEP)
else:
box.set_position(SplitMover.THRESHOLD)
break
@classmethod
def list_allocation(cls, box):
box_rect = box.get_allocation()
return box_rect.width, box_rect.height, box.get_position()
| 6,133
|
Python
|
.py
| 141
| 33.212766
| 77
| 0.592319
|
Guake/guake
| 4,406
| 575
| 405
|
GPL-2.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,073
|
test_quick_open.py
|
Guake_guake/guake/tests/test_quick_open.py
|
import re
from guake.globals import QUICK_OPEN_MATCHERS
from textwrap import dedent
def test_quick_open():
chunk = dedent(
"""
Traceback (most recent call last):
File "./test.py", line 5, in <module>
os.path('/bad/path')
TypeError: 'module' object is not callable
"""
)
found = _execute_quick_open(chunk)
assert found == [("./test.py", "5")]
def _execute_quick_open(chunk):
found = []
for line in chunk.split("\n"):
for _1, _2, r in QUICK_OPEN_MATCHERS:
g = re.compile(r).match(line)
if g:
found.append((g.group(1), g.group(2)))
return found
| 683
|
Python
|
.py
| 22
| 23.636364
| 54
| 0.568807
|
Guake/guake
| 4,406
| 575
| 405
|
GPL-2.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,074
|
test_guake.py
|
Guake_guake/guake/tests/test_guake.py
|
# -*- coding: utf-8 -*-
# pylint: disable=redefined-outer-name
import json
import os
import time
from pathlib import Path
import pytest
import guake.guake_app
from guake.common import pixmapfile
from guake.guake_app import Guake
@pytest.fixture
def g(mocker, fs):
mocker.patch("guake.guake_app.Guake.get_xdg_config_directory", return_value=Path("/foobar"))
mocker.patch("guake.guake_app.shutil.copy", create=True)
mocker.patch("guake.guake_app.notifier.showMessage", create=True)
mocker.patch("guake.guake_app.traceback.print_exc", create=True)
fs.pause()
g = Guake()
fs.add_real_file(pixmapfile("guake-notification.png"))
fs.resume()
return g
# Accel Test
def test_accel_search_terminal(g):
nb = g.get_notebook()
page = nb.get_nth_page(0)
assert not page.search_revealer.get_reveal_child()
g.accel_search_terminal()
assert page.search_revealer.get_reveal_child()
def test_accel_search_terminal_debounce(g):
nb = g.get_notebook()
page = nb.get_nth_page(0)
assert not page.search_revealer.get_reveal_child()
g.prev_accel_search_terminal_time = time.time()
g.accel_search_terminal()
assert not page.search_revealer.get_reveal_child()
def test_accel_quit_without_prompt(mocker, g):
# Disable quit prompt
mocker.patch.object(g.settings.general, "get_boolean", return_value=False)
mocker.patch("guake.guake_app.Gtk.main_quit")
g.accel_quit()
assert guake.guake_app.Gtk.main_quit.call_count == 1
def test_accel_quit_with_prompt(mocker, g):
# Enable quit prompt
mocker.patch.object(g.settings.general, "get_boolean", return_value=True)
mocker.patch("guake.guake_app.PromptQuitDialog")
mocker.patch("guake.guake_app.Gtk.main_quit")
g.accel_quit()
assert guake.guake_app.Gtk.main_quit.call_count == 1
# Save/Restore Tabs
def test_guake_restore_tabs(g, fs):
d1 = fs.create_dir("/foobar/foo")
d2 = fs.create_dir("/foobar/bar")
d3 = fs.create_dir("/foobar/foo/foo")
d4 = fs.create_dir("/foobar/foo/bar")
session = {
"schema_version": 1,
"timestamp": 1556092197,
"workspace": {
"0": [
[
{"directory": d1.path, "label": "1", "custom_label_set": True},
{"directory": d2.path, "label": "2", "custom_label_set": True},
{"directory": d3.path, "label": d3.path, "custom_label_set": False},
]
],
"1": [[{"directory": d4.path, "label": "4", "custom_label_set": True}]],
},
}
fn = fs.create_file("/foobar/session.json")
with open(fn.path, "w", encoding="utf-8") as f:
f.write(json.dumps(session))
g.restore_tabs(fn.name)
nb = g.notebook_manager.get_notebook(0)
assert nb.get_n_pages() == 3
assert nb.get_tab_text_index(0) == "1"
assert nb.get_tab_text_index(1) == "2"
nb = g.notebook_manager.get_notebook(1)
assert nb.get_n_pages() == 1
assert nb.get_tab_text_index(0) == "4"
def test_guake_restore_tabs_json_without_schema_version(g, fs):
guake.guake_app.notifier.showMessage.reset_mock()
fn = fs.create_file("/foobar/bar.json")
with open(fn.path, "w", encoding="utf-8") as f:
f.write("{}")
g.restore_tabs(fn.name)
assert guake.guake_app.notifier.showMessage.call_count == 1
def test_guake_restore_tabs_with_higher_schema_version(g, fs):
guake.guake_app.notifier.showMessage.reset_mock()
fn = fs.create_file("/foobar/bar.json")
with open(fn.path, "w", encoding="utf-8") as f:
f.write('{"schema_version": 2147483647}')
g.restore_tabs(fn.name)
assert guake.guake_app.notifier.showMessage.call_count == 1
def test_guake_restore_tabs_json_broken_session_file(g, fs):
guake.guake_app.notifier.showMessage.reset_mock()
fn = fs.create_file("/foobar/foobar.json")
with open(fn.path, "w", encoding="utf-8") as f:
f.write("{")
g.restore_tabs(fn.name)
assert guake.guake_app.shutil.copy.call_count == 1
assert guake.guake_app.notifier.showMessage.call_count == 1
def test_guake_restore_tabs_schema_broken_session_file(g, fs):
guake.guake_app.notifier.showMessage.reset_mock()
fn = fs.create_file("/foobar/bar.json")
d = fs.create_dir("/foobar/foo")
with open(fn.path, "w", encoding="utf-8") as f:
f.write(f'{{"schema_version": 1, "workspace": {{"0": [[{{"directory": "{d.path}"}}]]}}}}')
g.restore_tabs(fn.name)
assert guake.guake_app.shutil.copy.call_count == 1
assert guake.guake_app.traceback.print_exc.call_count == 1
def test_guake_save_tabs_and_restore(mocker, g, fs):
# Disable auto save
mocker.patch.object(g.settings.general, "get_boolean", return_value=False)
# Save
assert not os.path.exists("/foobar/session.json")
g.add_tab()
g.rename_current_tab("foobar", True)
g.add_tab()
g.rename_current_tab("python", True)
assert g.get_notebook().get_n_pages() == 3
g.save_tabs()
assert os.path.exists("/foobar")
assert os.path.exists("/foobar/session.json")
# Restore prepare
g.close_tab()
g.close_tab()
assert g.get_notebook().get_n_pages() == 1
# Restore
g.restore_tabs()
nb = g.get_notebook()
assert nb.get_n_pages() == 3
assert nb.get_tab_text_index(1) == "foobar"
assert nb.get_tab_text_index(2) == "python"
def test_guake_hide_tab_bar_if_one_tab(mocker, g, fs):
# Set hide-tabs-if-one-tab to True
mocker.patch.object(g.settings.general, "get_boolean", return_value=True)
g.settings.general.set_boolean("hide-tabs-if-one-tab", True)
assert g.get_notebook().get_n_pages() == 1
assert g.get_notebook().get_property("show-tabs") is False
def test_load_cwd_guake_yml_not_found_error(g):
vte = g.get_notebook().get_current_terminal()
assert g.fm.read_yaml("/foo/.guake.yml") is None
assert g.load_cwd_guake_yaml(vte) == {}
def test_load_cwd_guake_yml_encoding_error(g, mocker, fs):
vte = g.get_notebook().get_current_terminal()
mocker.patch.object(vte, "get_current_directory", return_value="/foo/")
fs.create_file("/foo/.guake.yml", contents=b"\xfe\xf0[\xb1\x0b\xc1\x18\xda")
assert g.fm.read_yaml("/foo/.guake.yml") is None
assert g.load_cwd_guake_yaml(vte) == {}
def test_load_cwd_guake_yml_format_error(g, mocker, fs):
vte = g.get_notebook().get_current_terminal()
mocker.patch.object(vte, "get_current_directory", return_value="/foo/")
fs.create_file("/foo/.guake.yml", contents=b"[[as]")
assert g.fm.read_yaml("/foo/.guake.yml") is None
assert g.load_cwd_guake_yaml(vte) == {}
def test_load_cwd_guake_yml(mocker, g, fs):
vte = g.get_notebook().get_current_terminal()
mocker.patch.object(vte, "get_current_directory", return_value="/foo/")
f = fs.create_file("/foo/.guake.yml", contents="title: bar")
assert g.load_cwd_guake_yaml(vte) == {"title": "bar"}
# Cache in action.
f.set_contents("title: foo")
assert g.load_cwd_guake_yaml(vte) == {"title": "bar"}
g.fm.clear()
assert g.load_cwd_guake_yaml(vte) == {"title": "foo"}
def test_guake_compute_tab_title(mocker, g, fs):
vte = g.get_notebook().get_current_terminal()
mocker.patch.object(vte, "get_current_directory", return_value="/foo/")
# Original title.
assert g.compute_tab_title(vte) == "Terminal"
# Change title.
fs.create_file("/foo/.guake.yml", contents="title: bar")
assert g.compute_tab_title(vte) == "bar"
# Avoid loading the guake.yml
mocker.patch.object(g.settings.general, "get_boolean", return_value=False)
assert g.compute_tab_title(vte) == "Terminal"
| 7,679
|
Python
|
.py
| 176
| 38.181818
| 98
| 0.663798
|
Guake/guake
| 4,406
| 575
| 405
|
GPL-2.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,075
|
test_utils.py
|
Guake_guake/guake/tests/test_utils.py
|
# -*- coding: utf-8 -*-
# pylint: disable=redefined-outer-name
import os
from guake.utils import FileManager
from guake.utils import get_process_name
def test_file_manager(fs):
fs.create_file("/foo/bar", contents="test")
fm = FileManager()
assert fm.read("/foo/bar") == "test"
def test_file_manager_hit(fs):
f = fs.create_file("/foo/bar", contents="test")
fm = FileManager(delta=9999)
assert fm.read("/foo/bar") == "test"
f.set_contents("changed")
assert fm.read("/foo/bar") == "test"
def test_file_manager_miss(fs):
f = fs.create_file("/foo/bar", contents="test")
fm = FileManager(delta=0.0)
assert fm.read("/foo/bar") == "test"
f.set_contents("changed")
assert fm.read("/foo/bar") == "changed"
def test_file_manager_clear(fs):
f = fs.create_file("/foo/bar", contents="test")
fm = FileManager(delta=9999)
assert fm.read("/foo/bar") == "test"
f.set_contents("changed")
assert fm.read("/foo/bar") == "test"
fm.clear()
assert fm.read("/foo/bar") == "changed"
def test_process_name():
assert get_process_name(os.getpid())
| 1,117
|
Python
|
.py
| 31
| 31.870968
| 51
| 0.651119
|
Guake/guake
| 4,406
| 575
| 405
|
GPL-2.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,076
|
test_notebook.py
|
Guake_guake/guake/tests/test_notebook.py
|
# -*- coding: utf-8 -*-
# pylint: disable=redefined-outer-name
import pytest
from guake.notebook import TerminalNotebook
@pytest.fixture
def nb(mocker):
targets = [
"guake.notebook.TerminalNotebook.terminal_spawn",
"guake.notebook.TerminalNotebook.terminal_attached",
"guake.notebook.TerminalNotebook.guake",
"guake.notebook.TerminalBox.set_terminal",
]
for target in targets:
mocker.patch(target, create=True)
return TerminalNotebook()
def test_zero_page_notebook(nb):
assert nb.get_n_pages() == 0
def test_add_one_page_to_notebook(nb):
nb.new_page()
assert nb.get_n_pages() == 1
def test_add_two_pages_to_notebook(nb):
nb.new_page()
nb.new_page()
assert nb.get_n_pages() == 2
def test_remove_page_in_notebook(nb):
nb.new_page()
nb.new_page()
assert nb.get_n_pages() == 2
nb.remove_page(0)
assert nb.get_n_pages() == 1
nb.remove_page(0)
assert nb.get_n_pages() == 0
def test_rename_page(nb):
t1 = "foo"
t2 = "bar"
nb.new_page()
nb.rename_page(0, t1, True)
assert nb.get_tab_text_index(0) == t1
nb.rename_page(0, t2, False)
assert nb.get_tab_text_index(0) == t1
nb.rename_page(0, t2, True)
assert nb.get_tab_text_index(0) == t2
def test_add_new_page_with_focus_with_label(nb):
t = "test_this_label"
nb.new_page_with_focus(label=t)
assert nb.get_n_pages() == 1
assert nb.get_tab_text_index(0) == t
| 1,473
|
Python
|
.py
| 47
| 26.595745
| 60
| 0.659574
|
Guake/guake
| 4,406
| 575
| 405
|
GPL-2.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,077
|
test_about.py
|
Guake_guake/guake/tests/test_about.py
|
# -*- coding: utf-8 -*-
# pylint: disable=redefined-outer-name
import pytest
from guake import guake_version
from guake.about import AboutDialog
@pytest.fixture
def dialog(mocker, monkeypatch):
mocker.patch("guake.simplegladeapp.Gtk.Widget.show_all")
monkeypatch.setenv("LANGUAGE", "en_US.UTF-8")
yield AboutDialog()
def test_version_test(dialog):
assert dialog.get_widget("aboutdialog").get_version() == guake_version()
def test_title(dialog):
assert dialog.get_widget("aboutdialog").get_title() == "About Guake"
| 542
|
Python
|
.py
| 14
| 35.714286
| 76
| 0.751923
|
Guake/guake
| 4,406
| 575
| 405
|
GPL-2.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,078
|
setup.py
|
errbotio_errbot/setup.py
|
#!/usr/bin/env python
# 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, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
import os
import sys
from setuptools import find_packages, setup
py_version = sys.version_info[:2]
if py_version < (3, 9):
raise RuntimeError("Errbot requires Python 3.9 or later")
VERSION_FILE = os.path.join("errbot", "version.py")
deps = [
"webtest==3.0.0",
"setuptools==68.1.2",
"flask==2.3.3",
"requests==2.31.0",
"jinja2==3.1.3",
"pyOpenSSL==23.2.0",
"colorlog==6.7.0",
"markdown==3.4.4",
"ansi==0.3.6",
"Pygments==2.16.1",
"pygments-markdown-lexer==0.1.0.dev39", # sytax coloring to debug md
"dulwich==0.21.5", # python implementation of git
"deepmerge==1.1.0",
]
src_root = os.curdir
def read_version():
"""
Read directly the errbot/version.py and gives the version without loading Errbot.
:return: errbot.version.VERSION
"""
variables = {}
with open(VERSION_FILE) as f:
exec(compile(f.read(), "version.py", "exec"), variables)
return variables["VERSION"]
def read(fname, encoding="ascii"):
return open(
os.path.join(os.path.dirname(__file__), fname), "r", encoding=encoding
).read()
if __name__ == "__main__":
VERSION = read_version()
args = set(sys.argv)
changes = read("CHANGES.rst", "utf8")
if changes.find(VERSION) == -1:
raise Exception("You forgot to put a release note in CHANGES.rst ?!")
if args & {"bdist", "bdist_dumb", "bdist_rpm", "bdist_wininst", "bdist_msi"}:
raise Exception("err doesn't support binary distributions")
packages = find_packages(src_root, include=["errbot", "errbot.*"])
setup(
name="errbot",
version=VERSION,
packages=packages,
entry_points={
"console_scripts": [
"errbot = errbot.cli:main",
]
},
install_requires=deps,
tests_require=["nose", "webtest", "requests"],
package_data={
"errbot": [
"backends/*.plug",
"backends/*.html",
"backends/styles/*.css",
"backends/images/*.svg",
"core_plugins/*.plug",
"core_plugins/*.md",
"core_plugins/templates/*.md",
"storage/*.plug",
"templates/initdir/example.py",
"templates/initdir/example.plug",
"templates/initdir/config.py.tmpl",
"templates/*.md",
"templates/new_plugin.py.tmpl",
],
},
extras_require={
"slack": [
"errbot-backend-slackv3==0.2.1",
],
"discord": [
"err-backend-discord==3.0.1",
],
"mattermost": [
"err-backend-mattermost==3.0.0",
],
"IRC": [
"irc==20.3.0",
],
"telegram": [
"python-telegram-bot==13.15",
],
"XMPP": [
"slixmpp==1.8.4",
"pyasn1==0.5.0",
"pyasn1-modules==0.3.0",
],
':sys_platform!="win32"': ["daemonize==2.5.0"],
},
author="errbot.io",
author_email="info@errbot.io",
description="Errbot is a chatbot designed to be simple to extend with plugins written in Python.",
long_description_content_type="text/x-rst",
long_description="".join([read("README.rst"), "\n\n", changes]),
license="GPL",
keywords="xmpp irc slack hipchat gitter tox chatbot bot plugin chatops",
url="http://errbot.io/",
classifiers=[
"Development Status :: 5 - Production/Stable",
"Topic :: Communications :: Chat",
"Topic :: Communications :: Chat :: Internet Relay Chat",
"License :: OSI Approved :: GNU General Public License v3 (GPLv3)",
"Operating System :: OS Independent",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
],
src_root=src_root,
platforms="any",
)
| 4,951
|
Python
|
.py
| 132
| 28.734848
| 106
| 0.565145
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,079
|
gen_home.py
|
errbotio_errbot/tools/gen_home.py
|
#!/usr/bin/env python3
import json
from jinja2 import Template
template = Template(open("plugins.md").read())
blacklisted = [repo.strip() for repo in open("blacklisted.txt", "r").readlines()]
PREFIX_LEN = len("https://github.com/")
with open("repos.json", "r") as p:
repos = json.load(p)
# Removes the weird forks of errbot itself and
# blacklisted repos
filtered_plugins = []
for repo, plugins in repos.items():
for name, plugin in plugins.items():
if plugin["path"].startswith("errbot/builtins"):
continue
if plugin["repo"][PREFIX_LEN:] in blacklisted:
continue
filtered_plugins.append(plugin)
sorted_plugins = sorted(filtered_plugins, key=lambda plugin: -plugin["score"])
with open("Home.md", "w") as out:
out.write(template.render(plugins=sorted_plugins))
| 880
|
Python
|
.py
| 21
| 35.190476
| 82
| 0.654524
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,080
|
plugin-gen.py
|
errbotio_errbot/tools/plugin-gen.py
|
#!/usr/bin/env python3
import configparser
import json
import logging
import os
import pathlib
import sys
import time
from datetime import datetime
import requests
from requests.auth import HTTPBasicAuth
logging.basicConfig()
log = logging.getLogger(__name__)
log.setLevel(logging.DEBUG)
DEFAULT_AVATAR = "https://upload.wikimedia.org/wikipedia/commons/5/5f/Err-logo.png"
BLACKLISTED = []
user_cache = {}
plugins = {}
def get_auth():
"""Get auth creds from Github Token
token is generated from the personal tokens in github
"""
token_file = pathlib.Path("token")
token_env = os.getenv("ERRBOT_REPOS_TOKEN")
if token_file.is_file():
try:
token_info = open("token", "r").read()
except ValueError:
log.fatal(
"Token file cannot be properly read, should be of the form username:token"
)
sys.exit(-1)
elif token_env:
token_info = token_env
else:
msg = "No 'token' file or environment variable 'ERROBOT_REPOS_TOKEN' found."
log.fatal(msg)
sys.exit(-1)
try:
user, token = token_info.strip().split(":")
except ValueError:
msg = "Token file cannot be properly read, should be of the form username:token"
log.fatal(msg)
sys.exit(-1)
auth = HTTPBasicAuth(user, token)
return auth
AUTH = get_auth()
def add_blacklisted(repo):
with open("blacklisted.txt", "a") as f:
f.write(repo)
f.write("\n")
def save_plugins():
with open("repos.json", "w") as f:
json.dump(plugins, f, indent=2, separators=(",", ": "))
def get_avatar_url(repo):
username = repo.split("/")[0]
if username in user_cache:
user = user_cache[username]
else:
user_res = requests.get("https://api.github.com/users/" + username, auth=AUTH)
user = user_res.json()
if "avatar_url" in user: # don't pollute the presistent cache
user_cache[username] = user
with open("user_cache", "w") as f:
f.write(repr(user_cache))
rate_limit(user_res)
return user["avatar_url"] if "avatar_url" in user else DEFAULT_AVATAR
def rate_limit(resp):
"""
Wait enough to be in the budget for this request.
:param resp: the http response from github
:return:
"""
if "X-RateLimit-Remaining" not in resp.headers:
log.info("No rate limit detected. Hum along...")
return
remain = int(resp.headers["X-RateLimit-Remaining"])
limit = int(resp.headers["X-RateLimit-Limit"])
log.info("Rate limiter: %s allowed out of %d", remain, limit)
if remain > 1: # margin by one request
return
reset = int(resp.headers["X-RateLimit-Reset"])
ts = datetime.fromtimestamp(reset)
delay = (ts - datetime.now()).total_seconds()
log.info("Hit rate limit. Have to wait for %d seconds", delay)
if delay < 0: # time drift
delay = 2
time.sleep(delay)
def parse_date(gh_date: str) -> datetime:
return datetime.strptime(gh_date, "%Y-%m-%dT%H:%M:%SZ")
def check_repo(repo):
repo_name = repo.get("full_name", None)
if repo_name is None:
log.error("No name in %s", repo)
log.debug("Checking %s...", repo_name)
code_resp = requests.get(
"https://api.github.com/search/code?q=extension:plug+repo:%s" % repo_name,
auth=AUTH,
)
if code_resp.status_code != 200:
log.error(
"Error getting https://api.github.com/search/code?q=extension:plug+repo:%s",
repo_name,
)
log.error("code %d", code_resp.status_code)
log.error("content %s", code_resp.text)
return
plug_items = code_resp.json()["items"]
if not plug_items:
log.debug("No plugin found in %s, blacklisting it.", repo_name)
add_blacklisted(repo_name)
return
owner = repo["owner"]
avatar_url = owner["avatar_url"] if "avatar_url" in owner else DEFAULT_AVATAR
days_old = (datetime.now() - parse_date(repo["updated_at"])).days
score = (
repo["stargazers_count"]
+ repo["watchers_count"] * 2
+ repo["forks_count"]
- days_old / 25
)
for plug in plug_items:
plugfile_resp = requests.get(
"https://raw.githubusercontent.com/%s/master/%s" % (repo_name, plug["path"])
)
log.debug("Found a plugin:")
log.debug("Repo: %s", repo_name)
log.debug("File: %s", plug["path"])
parser = configparser.ConfigParser()
try:
parser.read_string(plugfile_resp.text)
name = parser["Core"]["Name"]
log.debug("Name: %s", name)
if "Documentation" in parser and "Description" in parser["Documentation"]:
doc = parser["Documentation"]["Description"]
log.debug("Documentation: %s", doc)
else:
doc = ""
if "Python" in parser:
python = parser["Python"]["Version"]
log.debug("Python Version: %s", python)
else:
python = "2"
plugin = {
"path": plug["path"],
"repo": repo["html_url"],
"documentation": doc,
"name": name,
"python": python,
"avatar_url": avatar_url,
"score": score,
}
repo_entry = plugins.get(repo_name, {})
repo_entry[name] = plugin
plugins[repo_name] = repo_entry
log.debug("Catalog added plugin %s.", plugin["name"])
except Exception:
log.error("Invalid syntax in %s, skipping...", plug["path"])
continue
rate_limit(plugfile_resp)
save_plugins()
rate_limit(code_resp)
def find_plugins(query):
url = (
"https://api.github.com/search/repositories?q=%s+in:name+language:python&sort=stars&order=desc"
% query
)
while True:
repo_resp = requests.get(url, auth=AUTH)
repo_json = repo_resp.json()
if repo_json.get("message", None) == "Bad credentials":
log.error("Invalid credentials, check your token file, see README.")
sys.exit(-1)
log.debug(
"Repo reqs before ratelimit %s/%s",
repo_resp.headers["X-RateLimit-Remaining"],
repo_resp.headers["X-RateLimit-Limit"],
)
if "message" in repo_json and repo_json["message"].startswith(
"API rate limit exceeded for"
):
log.error("API rate limit hit anyway ... wait for 30s")
time.sleep(30)
continue
items = repo_json["items"]
for repo in items:
if repo["full_name"] in BLACKLISTED:
log.debug("Skipping %s.", repo)
continue
check_repo(repo)
if "next" not in repo_resp.links:
break
url = repo_resp.links["next"]["url"]
log.debug("Next url: %s", url)
rate_limit(repo_resp)
def main():
find_plugins("err")
# Those are found by global search only available on github UI:
# https://github.com/search?l=&q=Documentation+extension%3Aplug&ref=advsearch&type=Code&utf8=%E2%9C%93
url = "https://api.github.com/repos/%s"
with open("extras.txt", "r") as extras:
for repo_name in extras:
repo_name = repo_name.strip()
repo_resp = requests.get(url % repo_name, auth=AUTH)
repo = repo_resp.json()
if repo.get("message", None) == "Bad credentials":
log.error("Invalid credentials, check your token file, see README.")
sys.exit(-1)
if "message" in repo and repo["message"].startswith(
"API rate limit exceeded for"
):
log.error("API rate limit hit anyway ... wait for 30s")
time.sleep(30)
continue
if "message" in repo and repo["message"].startswith("Not Found"):
log.error("%s not found.", repo_name)
else:
check_repo(repo)
rate_limit(repo_resp)
if __name__ == "__main__":
try:
with open("user_cache", "r") as f:
user_cache = eval(f.read())
except FileNotFoundError:
# File doesn't exist, so we continue on
log.info("No user cache existing, will be generating it for the first time.")
try:
with open("blacklisted.txt", "r") as f:
BLACKLISTED = [line.strip() for line in f.readlines()]
except FileNotFoundError:
log.info("No blacklisted.txt found, no plugins will be blacklisted.")
main()
| 8,727
|
Python
|
.py
| 232
| 28.857759
| 106
| 0.583126
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,081
|
conf.py
|
errbotio_errbot/docs/conf.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Errbot documentation build configuration file, created by
# sphinx-quickstart on Fri Sep 13 17:24:59 2013.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import subprocess
import sys
import os
sys.path.append(os.path.abspath('_themes'))
sys.path.append(os.path.abspath('_themes/err'))
sys.path.append(os.path.abspath('../'))
__import__('errbot.config-template')
sys.modules['config'] = sys.modules['errbot.config-template']
from errbot.version import VERSION
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.viewcode',
'sphinx_autodoc_annotation',
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = 'Err'
copyright = '2013, Guillaume Binet, Tali Davidovich Petrover and Nick Groenen'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = VERSION
# The full version, including alpha/beta/rc tags.
release = VERSION
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = [
'_build',
'error_pages/*',
'errbot.backends.tox.rst', # Also quite a pain to build at this stage
'_gh-pages',
]
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
#pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False
# -- Autodoc configuration -----------------------------------------------------
def autodoc_skip_member(app, what, name, obj, skip, options):
if name == "__init__":
return False
return skip
# -- Apidoc --------------------------------------------------------------------
def run_apidoc(_):
subprocess.check_call("sphinx-apidoc --separate -f -o . ../errbot", shell=True)
def run_repos_builder(*_):
last_dir = os.getcwd()
os.chdir('../tools/')
subprocess.check_call("python plugin-gen.py", shell=True, env=os.environ)
subprocess.check_call("pwd; cp repos.json ../docs/html_extras/", shell=True)
os.chdir(last_dir)
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'err'
# Add any paths that contain custom themes here, relative to this directory.
html_theme_path = ['_themes']
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#
# Note: Best leave this off until Sphinx issue #1496 gets resolved
# (https://bitbucket.org/birkenfeld/sphinx/issue/1496/smartypants-should-not-convert-text-in-a)
html_use_smartypants = False
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
html_domain_indices = True
# If false, no index is generated.
html_use_index = True
# If true, the index is split into individual pages for each letter.
html_split_index = False
# If true, links to the reST sources are added to the pages.
html_show_sourcelink = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'Errdoc'
html_extra_path = ['html_extras']
# -- Options for LaTeX output --------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'Err.tex', 'Err Documentation', 'Guillaume Binet, Tali Davidovich Petrover and Nick Groenen', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [('index', 'err', 'Err Documentation', ['Guillaume Binet, Tali Davidovich Petrover and Nick Groenen'], 1)]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output ------------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'Err', 'Err Documentation', 'Guillaume Binet, Tali Davidovich Petrover and Nick Groenen', 'Err',
'One line description of project.', 'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False
# -- Options for Epub output ---------------------------------------------------
# Bibliographic Dublin Core info.
epub_title = 'Err'
epub_author = 'Guillaume Binet, Tali Davidovich Petrover and Nick Groenen'
epub_publisher = 'Guillaume Binet, Tali Davidovich Petrover and Nick Groenen'
epub_copyright = '2013, Guillaume Binet, Tali Davidovich Petrover and Nick Groenen'
# The language of the text. It defaults to the language option
# or en if the language is not set.
#epub_language = ''
# The scheme of the identifier. Typical schemes are ISBN or URL.
#epub_scheme = ''
# The unique identifier of the text. This can be a ISBN number
# or the project homepage.
#epub_identifier = ''
# A unique identification for the text.
#epub_uid = ''
# A tuple containing the cover image and cover page html template filenames.
#epub_cover = ()
# A sequence of (type, uri, title) tuples for the guide element of content.opf.
#epub_guide = ()
# HTML files that should be inserted before the pages created by sphinx.
# The format is a list of tuples containing the path and title.
#epub_pre_files = []
# HTML files shat should be inserted after the pages created by sphinx.
# The format is a list of tuples containing the path and title.
#epub_post_files = []
# A list of files that should not be packed into the epub file.
#epub_exclude_files = []
# The depth of the table of contents in toc.ncx.
#epub_tocdepth = 3
# Allow duplicate toc entries.
#epub_tocdup = True
# Fix unsupported image types using the PIL.
#epub_fix_images = False
# Scale large images.
#epub_max_image_width = 0
# If 'no', URL addresses will not be shown.
#epub_show_urls = 'inline'
# If false, no index is generated.
#epub_use_index = True
# -- Misc options -------------------------------------------------------------
intersphinx_mapping = {'http://docs.python.org/': None}
def setup(app):
app.connect("autodoc-skip-member", autodoc_skip_member)
app.connect("builder-inited", run_apidoc)
#app.connect("html-page-context", run_repos_builder)
| 10,469
|
Python
|
.py
| 236
| 42.491525
| 118
| 0.710202
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,082
|
pygments_style.py
|
errbotio_errbot/docs/_themes/err/pygments_style.py
|
from pygments.style import Style
from pygments.token import Keyword, Name, Comment, String, \
Number, Operator, Generic, Whitespace
class ErrStyle(Style):
"""
A Pygments style based on the "friendly" theme
"""
background_color = "#ffffcc"
default_style = ""
styles = {
Whitespace: "#3e4349",
Comment: "#3f6b5b",
# Comment.Preproc: "noitalic #007020",
# Comment.Special: "noitalic bg:#fff0f0",
Keyword: "bold #f06f00",
# Keyword.Pseudo: "nobold",
# Keyword.Type: "nobold #902000",
Operator: "#3e4349",
# Operator.Word: "bold #007020",
Name: "#3e4349",
Name.Builtin: "#007020",
Name.Function: "bold #3e4349",
Name.Class: "bold #3e4349",
# Name.Namespace: "bold #f07e2a",
# Name.Exception: "#007020",
Name.Variable: "underline #8a2be2",
Name.Constant: "underline #b91f49",
# Name.Label: "bold #002070",
Name.Entity: "bold #330000",
# Name.Attribute: "#4070a0",
Name.Tag: "bold #f06f00",
Name.Decorator: "bold italic #3e4349",
# String: "#3e4349",
String: "#9a5151",
# String.Doc: "italic #3f65b5",
String.Doc: "italic #3f6b5b",
# String.Doc: "italic #9a7851",
# String.Doc: "italic #9a5151",
# String.Interpol: "italic #70a0d0",
# String.Escape: "bold #4070a0",
# String.Regex: "#235388",
# String.Symbol: "#517918",
# String.Other: "#c65d09",
Number: "underline #9a5151",
Generic: "#3e4349",
Generic.Heading: "bold #1014ad",
Generic.Subheading: "bold #1014ad",
Generic.Deleted: "bg:#c8f2ea #2020ff",
Generic.Inserted: "#3e4349",
# Generic.Error: "#FF0000",
# Generic.Emph: "italic",
# Generic.Strong: "bold",
# Generic.Prompt: "bold #c65d09",
# Generic.Output: "#888",
# Generic.Traceback: "#04D",
# Error: "border:#FF0000"
}
| 2,651
|
Python
|
.py
| 57
| 38.298246
| 60
| 0.43305
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,083
|
config-template.py
|
errbotio_errbot/docs/user_guide/config-template.py
|
##########################################################################
# #
# This is the config-template for Err. This file should be copied and #
# renamed to config.py, then modified as you see fit to run Errbot #
# the way you like it. #
# #
# As this is a regular Python file, note that you can do variable #
# assignments and the likes as usual. This can be useful for example if #
# you use the same values in multiple places. #
# #
# Note: Various config options require a tuple to be specified, even #
# when you are configuring only a single value. An example of this is #
# the BOT_ADMINS option. Make sure you use a valid tuple here, even if #
# you are only configuring a single item, else you will get errors. #
# (So don't forget the trailing "," in these cases) #
# #
##########################################################################
import logging
##########################################################################
# Core Errbot configuration #
##########################################################################
# BACKEND selection.
# This configures the type of chat server you wish to use Errbot with.
#
# The current choices:
# Debug backends to test your plugins manually:
# "Text" - on the text console
# Commercial backends:
# "Slack" - see https://slack.com/
# "Gitter" - see https://gitter.im/ (follow instructions from https://github.com/errbotio/err-backend-gitter)
# Open protocols:
# "TOX" - see https://tox.im/ (follow instructions from https://github.com/errbotio/err-backend-tox)
# "IRC" - for classic IRC or bridged services like https://gitter.im
# "XMPP" - the Extensible Messaging and Presence Protocol (https://xmpp.org/)
# "Telegram" - cloud-based mobile and desktop messaging app with a focus
# on security and speed. (https://telegram.org/)
# BACKEND = "Text" # defaults to Text
# STORAGE selection.
# This configures the type of persistence you wish to use Errbot with.
#
# The current choices:
# Debug:
# "Memory" - local memory storage to test your bot in memory:
# Filesystem:
# "Shelf" - python shelf (default)
# STORAGE = "Shelf" # defaults to filestorage (python shelf).
# BOT_EXTRA_STORAGE_PLUGINS_DIR = None # extra search path to find custom storage plugins
# The location where all of Err's data should be stored. Make sure to set
# this to a directory that is writable by the user running the bot.
BOT_DATA_DIR = "/var/lib/err"
### Repos and plugins config.
# Set this to change from where errbot gets its installable plugin list.
# By default it gets the index from errbot.io which is a file generated by tools/plugin-gen.py.
# BOT_PLUGIN_INDEXES = "https://errbot.io/repos.json"
#
# You can also specify a local file:
# BOT_PLUGIN_INDEXES = "tools/repos.json"
#
# Or a list. note: if some plugins exists in 2 lists, only the first hit will be taken into account.
# BOT_PLUGIN_INDEXES = ("/data/repos.json", "https://my.private.tld/errbot/myrepos.json")
# Set this to a directory on your system where you want to load extra
# plugins from, which is useful mostly if you want to develop a plugin
# locally before publishing it. Note that you can specify only a single
# directory, however you are free to create subdirectories with multiple
# plugins inside this directory.
BOT_EXTRA_PLUGIN_DIR = None
# If you use an external backend as a plugin,
# this is where you tell Errbot where to find it.
# BOT_EXTRA_BACKEND_DIR = "/opt/errbackends"
# If you want only a subset of the core plugins that are bundled with errbot, you can specify them here.
# CORE_PLUGINS = None # This is default, all core plugins.
# For example CORE_PLUGINS = ("ACLs", "Backup", "Help") you get those names from the .plug files Name entry.
# For absolutely no plug: CORE_PLUGINS = ()
# Defines an order in which the plugins are getting their callbacks. Useful if you want to have plugins do
# pre- or post-processing on messages.
# The "None" tuple entry represents all the plugins that aren't to be explicitly ordered. For example, if
# you want "A" to run first, then everything else but "B", then "B", you would use ("A", None, "B").
PLUGINS_CALLBACK_ORDER = (None,)
# Should plugin dependencies be installed automatically? If this is true
# then Errbot will use pip to install any missing dependencies automatically.
#
# If you have installed Errbot in a virtualenv, this will run the equivalent
# of `pip install -r requirements.txt`.
# If no virtualenv is detected, the equivalent of `pip install --user -r
# requirements.txt` is used to ensure the package(s) is/are only installed for
# the user running Err.
# AUTOINSTALL_DEPS = True
# To use your own custom log formatter, uncomment and set BOT_LOG_FORMATTER
# to your formatter instance (inherits from logging.Formatter)
# For information on how to create a logging formatter and what it can do, see
# https://docs.python.org/3/library/logging.html#formatter-objects
# BOT_LOG_FORMATTER =
# The location of the log file. If you set this to None, then logging will
# happen to console only.
BOT_LOG_FILE = BOT_DATA_DIR + "/err.log"
# The verbosity level of logging that is done to the above logfile, and to
# the console. This takes the standard Python logging levels, DEBUG, INFO,
# WARN, ERROR. For more info, see http://docs.python.org/library/logging.html
#
# If you encounter any issues with Err, please set your log level to
# logging.DEBUG and attach a log with your bug report to aid the developers
# in debugging the issue.
BOT_LOG_LEVEL = logging.INFO
# Enable logging to sentry (find out more about sentry at www.getsentry.com).
# You can also separate Flask exceptions by enabling it. This will give more information in sentry
# This is optional and disabled by default.
BOT_LOG_SENTRY = False
BOT_LOG_SENTRY_FLASK = False
SENTRY_DSN = ""
SENTRY_LOGLEVEL = BOT_LOG_LEVEL
SENTRY_EVENTLEVEL = BOT_LOG_LEVEL
# Options that can be passed to sentry_sdk.init() at initialization time
# Note that DSN should be specified via its dedicated config option
# and that the 'integrations' setting cannot be set
# e.g: SENTRY_OPTIONS = {"environment": "production"}
SENTRY_OPTIONS = {}
# Execute commands in asynchronous mode. In this mode, Errbot will spawn 10
# separate threads to handle commands, instead of blocking on each
# single command.
# BOT_ASYNC = True
# Size of the thread pool for the asynchronous mode.
# BOT_ASYNC_POOLSIZE = 10
##########################################################################
# Account and chatroom (MUC) configuration #
##########################################################################
# The identity, or credentials, used to connect to a server
BOT_IDENTITY = {
## Text mode
"username": "@errbot", # The name for the bot
## XMPP (Jabber) mode
# "username": "err@localhost", # The JID of the user you have created for the bot
# "password": "changeme", # The corresponding password for this user
# "server": ("host.domain.tld", 5222), # server override
## Slack mode (comment the others above if using this mode)
# "token": "xoxb-4426949411-aEM7...",
## you can also include the proxy for the SlackClient connection
# "proxies": {"http": "some-http-proxy", "https": "some-https-proxy"}
## Telegram mode (comment the others above if using this mode)
# "token": "103419016:AAbcd1234...",
## IRC mode (Comment the others above if using this mode)
# "nickname": "err-chatbot",
# "username": "err-chatbot", # optional, defaults to nickname if omitted
# "password": None, # optional
# "server": "irc.freenode.net",
# "port": 6667, # optional
# "ssl": False, # optional
# "ipv6": False, # optional
# "nickserv_password": None, # optional
## Optional: Specify an IP address or hostname (vhost), and a
## port, to use when making the connection. Leave port at 0
## if you have no source port preference.
## example: "bind_address": ("my-errbot.io", 0)
# "bind_address": ("localhost", 0),
}
# Set the admins of your bot. Only these users will have access
# to the admin-only commands.
#
# Unix-style glob patterns are supported, so "gbin@localhost"
# would be considered an admin if setting "*@localhost".
BOT_ADMINS = ("gbin@localhost",)
# Set of admins that wish to receive administrative bot notifications.
# BOT_ADMINS_NOTIFICATIONS = ()
# Chatrooms your bot should join on startup. For the IRC backend you
# should include the # sign here. For XMPP rooms that are password
# protected, you can specify another tuple here instead of a string,
# using the format (RoomName, Password).
# CHATROOM_PRESENCE = ("err@conference.server.tld",)
# The FullName, or nickname, your bot should use. What you set here will
# be the nickname that Errbot shows in chatrooms. Note that some XMPP
# implementations are very picky about what name you use.
# CHATROOM_FN = "Errbot"
##########################################################################
# Prefix configuration #
##########################################################################
# Command prefix, the prefix that is expected in front of commands directed
# at the bot.
#
# Note: When writing plugins,you should always use the default "!".
# If the prefix is changed from the default, the help strings will be
# automatically adjusted for you.
#
# BOT_PREFIX = "!"
#
# Uncomment the following and set it to True if you want the prefix to be
# optional for normal chat.
# (Meaning messages sent directly to the bot as opposed to within a MUC)
# BOT_PREFIX_OPTIONAL_ON_CHAT = False
# You might wish to have your bot respond by being called with certain
# names, rather than the BOT_PREFIX above. This option allows you to
# specify alternative prefixes the bot will respond to in addition to
# the prefix above.
# BOT_ALT_PREFIXES = ("Err",)
# If you use alternative prefixes, you might want to allow users to insert
# separators like , and ; between the prefix and the command itself. This
# allows users to refer to your bot like this (Assuming "Err" is in your
# BOT_ALT_PREFIXES):
# "Err, status" or "Err: status"
#
# Note: There's no need to add spaces to the separators here
#
# BOT_ALT_PREFIX_SEPARATORS = (":", ",", ";")
# Continuing on this theme, you might want to permit your users to be
# lazy and not require correct capitalization, so they can do "Err",
# "err" or even "ERR".
# BOT_ALT_PREFIX_CASEINSENSITIVE = True
##########################################################################
# Access controls and message diversion #
##########################################################################
# Access controls, allowing commands to be restricted to specific users/rooms.
# Available filters (you can omit a filter or set it to None to disable it):
# allowusers: Allow command from these users only
# denyusers: Deny command from these users
# allowrooms: Allow command only in these rooms (and direct messages)
# denyrooms: Deny command in these rooms
# allowargs: Allow a command's argument from these users only
# denyargs: Deny a command's argument from these users
# allowprivate: Allow command from direct messages to the bot
# allowmuc: Allow command inside rooms
# Rules listed in ACCESS_CONTROLS_DEFAULT are applied by default and merged
# with any commands found in ACCESS_CONTROLS.
#
# The options allowusers, denyusers, allowrooms and denyrooms, allowargs,
# denyargs support unix-style globbing similar to BOT_ADMINS.
#
# Command names also support unix-style globs and can optionally be restricted
# to a specific plugin by prefixing the command with the name of a plugin,
# separated by a colon. For example, `Health:status` will match the `!status`
# command of the `Health` plugin and `Health:*` will match all commands defined
# by the `Health` plugin.
#
# Please note that the first command match found will be used so if you have
# overlapping patterns you must used an OrderedDict instead of a regular dict:
# https://docs.python.org/3/library/collections.html#collections.OrderedDict
#
# Example:
#
# ACCESS_CONTROLS_DEFAULT = {} # Allow everyone access by default
# ACCESS_CONTROLS = {
# "status": {
# "allowrooms": ("someroom@conference.localhost",),
# },
# "about": {
# "denyusers": ("*@evilhost",),
# "allowrooms": ("room1@conference.localhost", "room2@conference.localhost"),
# },
# "uptime": {"allowusers": BOT_ADMINS},
# "help": {"allowmuc": False},
# "ChatRoom:*": {"allowusers": BOT_ADMINS},
# }
# Uncomment and set this to True to hide the restricted commands from
# the help output.
# HIDE_RESTRICTED_COMMANDS = False
# Uncomment and set this to True to ignore commands from users that have no
# access for these instead of replying with error message.
# HIDE_RESTRICTED_ACCESS = False
# A list of commands which should be responded to in private, even if
# the command was given in a MUC. For example:
# DIVERT_TO_PRIVATE = ("help", "about", "status")
# If all commands are desired, use the specical case "ALL_COMMANDS"
DIVERT_TO_PRIVATE = ()
# A list of commands which should be responded to in a thread if the backend supports it.
# For example:
# DIVERT_TO_THREAD = ("help", "about", "status")
# If all commands are desired, use the specical case "ALL_COMMANDS"
DIVERT_TO_THREAD = ()
# Chat relay
# Can be used to relay one to one message from specific users to the bot
# to MUCs. This can be useful with XMPP notifiers like for example the
# standard Altassian Jira which don't have native support for MUC.
# For example: CHATROOM_RELAY = {"gbin@localhost" : (_TEST_ROOM,)}
CHATROOM_RELAY = {}
# Reverse chat relay
# This feature forwards whatever is said to a specific user.
# It can be useful if you client like gtalk doesn't support MUC correctly
# For example: REVERSE_CHATROOM_RELAY = {_TEST_ROOM : ("gbin@localhost",)}
REVERSE_CHATROOM_RELAY = {}
##########################################################################
# Miscellaneous configuration options #
##########################################################################
# Define the maximum length a single message may be. If a plugin tries to
# send a message longer than this length, it will be broken up into multiple
# shorter messages that do fit.
# MESSAGE_SIZE_LIMIT = 10000
# XMPP TLS certificate verification. In order to validate offered certificates,
# you must supply a path to a file containing certificate authorities. By
# default, "/etc/ssl/certs/ca-certificates.crt" is used, which on most Linux
# systems holds the default system trusted CA certificates. You might need to
# change this depending on your environment. Setting this to None disables
# certificate validation, which can be useful if you have a self-signed
# certificate for example.
# XMPP_CA_CERT_FILE = "/etc/ssl/certs/ca-certificates.crt"
# Influence the security methods used on connection with XMPP-based
# backends. You can use this to work around authentication issues with
# some buggy XMPP servers.
#
# The default is to try anything:
# XMPP_FEATURE_MECHANISMS = {}
# To use only unencrypted plain auth:
# XMPP_FEATURE_MECHANISMS = {
# "use_mech": "PLAIN",
# "unencrypted_plain": True,
# "encrypted_plain": False,
# }
# Modify the default keep-alive interval. By default, Errbot will send
# some whitespace to the XMPP server every 300 seconds to keep the TCP
# connection alive. On some servers, or when running Errbot from behind
# a NAT router, the default might not be fast enough and you will need
# to set it to a lower value.
#
# If you're having issues with your bot getting constantly disconnected,
# try to gradually lower this value until it no longer happens.
# XMPP_KEEPALIVE_INTERVAL = 300
# Modify default settings for IPv6 usage. This key affects the XMPP backend.
# XMPP_USE_IPV6 = False
# XMPP supports some formatting with XEP-0071 (http://www.xmpp.org/extensions/xep-0071.html).
# It is disabled by default because XMPP clients support has been found to be spotty.
# Switch it to True to enable XHTML-IM formatting.
# XMPP_XHTML_IM = False
# XMPP may require a specific ssl protocol version when making connections.
# This option allows the option to change that behavior.
# It uses python's built-in ssl module.
# import ssl
# XMPP_SSL_VERSION = ssl.PROTOCOL_TLSv1_2
# Message rate limiting for the IRC backend. This will delay subsequent
# messages by this many seconds (floats are supported). Setting these
# to a value of 0 effectively disables rate limiting.
# IRC_CHANNEL_RATE = 1 # Regular channel messages
# IRC_PRIVATE_RATE = 1 # Private messages
# IRC_RECONNECT_ON_KICK = 5 # Reconnect back to a channel after a kick (in seconds)
# Put it at None if you don't want the chat to
# reconnect
# IRC_RECONNECT_ON_DISCONNECT = 5 # Reconnect back to a channel after a disconnection (in seconds)
# The pattern to build a user representation from for ACL matches.
# The default is "{nick}!{user}@{host}" which results in "zoni!zoni@ams1.groenen.me"
# for the user zoni connecting from ams1.groenen.me.
# Available substitution variables:
# {nick} -> The nickname of the user
# {user} -> The username of the user
# {host} -> The hostname the user is connecting from
# IRC_ACL_PATTERN = "{nick}!{user}@{host}"
# Allow messages sent in a chatroom to be directed at requester.
# GROUPCHAT_NICK_PREFIXED = False
# Disable table borders, making output more compact (supported only on IRC, Slack and Telegram currently).
# COMPACT_OUTPUT = True
# Disables the logging output in Text mode and only outputs Ansi.
# TEXT_DEMO_MODE = False
# Prevent ErrBot from saying anything if the command is unrecognized.
# SUPPRESS_CMD_NOT_FOUND = False
| 18,339
|
Python
|
.py
| 348
| 51.227011
| 111
| 0.684122
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,084
|
dynaplug_test.py
|
errbotio_errbot/tests/dynaplug_test.py
|
from os import path
extra_plugin_dir = path.join(path.dirname(path.realpath(__file__)), "dyna_plugin")
def test_simple(testbot):
assert "added" in testbot.exec_command("!add_simple")
assert "yep" in testbot.exec_command("!say_yep")
assert "foo" in testbot.exec_command("!say_foo")
assert "documented" in testbot.exec_command("!help")
assert "removed" in testbot.exec_command("!remove_simple")
assert 'Command "say_foo" not found' in testbot.exec_command("!say_foo")
def test_arg(testbot):
assert "added" in testbot.exec_command("!add_arg")
assert "string to echo is string_to_echo" in testbot.exec_command(
"!echo_to_me string_to_echo"
)
assert "removed" in testbot.exec_command("!remove_arg")
assert (
'Command "echo_to_me" / "echo_to_me string_to_echo" not found'
in testbot.exec_command("!echo_to_me string_to_echo")
)
def test_re(testbot):
assert "added" in testbot.exec_command("!add_re")
assert "fffound" in testbot.exec_command("I said cheese")
assert "removed" in testbot.exec_command("!remove_re")
def test_saw(testbot):
assert "added" in testbot.exec_command("!add_saw")
assert "foo+bar+baz" in testbot.exec_command("!splitme foo,bar,baz")
assert "removed" in testbot.exec_command("!remove_saw")
def test_clashing(testbot):
assert "original" in testbot.exec_command("!clash")
assert (
"clashing.clash clashes with Dyna.clash so it has been renamed clashing-clash"
in testbot.exec_command("!add_clashing")
)
assert "added" in testbot.pop_message()
assert "original" in testbot.exec_command("!clash")
assert "dynamic" in testbot.exec_command("!clashing-clash")
assert "removed" in testbot.exec_command("!remove_clashing")
assert "original" in testbot.exec_command("!clash")
assert "not found" in testbot.exec_command("!clashing-clash")
| 1,903
|
Python
|
.py
| 39
| 43.717949
| 86
| 0.698327
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,085
|
core_test.py
|
errbotio_errbot/tests/core_test.py
|
"""Test _admins_to_notify wrapper functionality"""
extra_config = {"BOT_ADMINS_NOTIFICATIONS": "zoni@localdomain"}
def test_admins_to_notify(testbot):
"""Test which admins will be notified"""
notified_admins = testbot._bot._admins_to_notify()
assert "zoni@localdomain" in notified_admins
def test_admins_not_notified(testbot):
"""Test which admins will not be notified"""
notified_admins = testbot._bot._admins_to_notify()
assert "gbin@local" not in notified_admins
| 495
|
Python
|
.py
| 10
| 45.6
| 63
| 0.735417
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,086
|
muc_test.py
|
errbotio_errbot/tests/muc_test.py
|
import logging
import os
import errbot.backends.base
from errbot.backends.test import TestOccupant
log = logging.getLogger(__name__)
extra_plugin_dir = os.path.join(
os.path.dirname(os.path.realpath(__file__)), "room_plugin"
)
def test_plugin_methods(testbot):
p = testbot.bot.plugin_manager.get_plugin_obj_by_name("ChatRoom")
assert p is not None
assert hasattr(p, "rooms")
assert hasattr(p, "query_room")
def test_create_join_leave_destroy_lifecycle(testbot): # noqa
rooms = testbot.bot.rooms()
assert len(rooms) == 1
r1 = rooms[0]
assert str(r1) == "testroom"
assert issubclass(r1.__class__, errbot.backends.base.Room)
r2 = testbot.bot.query_room("testroom2")
assert not r2.exists
r2.create()
assert r2.exists
rooms = testbot.bot.rooms()
assert r2 not in rooms
assert not r2.joined
r2.destroy()
rooms = testbot.bot.rooms()
assert r2 not in rooms
r2.join()
assert r2.exists
assert r2.joined
rooms = testbot.bot.rooms()
assert r2 in rooms
r2 = testbot.bot.query_room("testroom2")
assert r2.joined
r2.leave()
assert not r2.joined
r2.destroy()
rooms = testbot.bot.rooms()
assert r2 not in rooms
def test_occupants(testbot): # noqa
room = testbot.bot.rooms()[0]
assert len(room.occupants) == 1
assert TestOccupant("err", "testroom") in room.occupants
def test_topic(testbot): # noqa
room = testbot.bot.rooms()[0]
assert room.topic is None
room.topic = "Errbot rocks!"
assert room.topic == "Errbot rocks!"
assert testbot.bot.rooms()[0].topic == "Errbot rocks!"
def test_plugin_callbacks(testbot): # noqa
p = testbot.bot.plugin_manager.get_plugin_obj_by_name("RoomTest")
assert p is not None
p.purge()
log.debug("query and join")
p.query_room("newroom").join()
assert p.events.get(timeout=5) == "callback_room_joined newroom"
p.query_room("newroom").topic = "Errbot rocks!"
assert p.events.get(timeout=5) == "callback_room_topic Errbot rocks!"
p.query_room("newroom").leave()
assert p.events.get(timeout=5) == "callback_room_left newroom"
def test_botcommands(testbot): # noqa
rooms = testbot.bot.rooms()
room = testbot.bot.query_room("testroom")
assert len(rooms) == 1
assert rooms[0] == room
assert room.joined
assert "Left the room testroom" in testbot.exec_command("!room leave testroom")
room = testbot.bot.query_room("testroom")
assert not room.joined
assert "I'm not currently in any rooms." in testbot.exec_command("!room list")
assert "Destroyed the room testroom" in testbot.exec_command(
"!room destroy testroom"
)
rooms = testbot.bot.rooms()
room = testbot.bot.query_room("testroom")
assert not room.exists
assert room not in rooms
assert "Created the room testroom" in testbot.exec_command("!room create testroom")
rooms = testbot.bot.rooms()
room = testbot.bot.query_room("testroom")
assert room.exists
assert room not in rooms
assert not room.joined
assert "Joined the room testroom" in testbot.exec_command("!room join testroom")
rooms = testbot.bot.rooms()
room = testbot.bot.query_room("testroom")
assert room.exists
assert room.joined
assert room in rooms
assert "Created the room testroom with spaces" in testbot.exec_command(
"!room create 'testroom with spaces'"
)
rooms = testbot.bot.rooms()
room = testbot.bot.query_room("testroom with spaces")
assert room.exists
assert room not in rooms
assert not room.joined
assert "Joined the room testroom with spaces" in testbot.exec_command(
"!room join 'testroom with spaces'"
)
rooms = testbot.bot.rooms()
room = testbot.bot.query_room("testroom with spaces")
assert room.exists
assert room.joined
assert room in rooms
assert "testroom" in testbot.exec_command("!room list")
assert "err" in testbot.exec_command("!room occupants testroom")
assert "No topic is set for testroom" in testbot.exec_command(
"!room topic testroom"
)
assert "Topic for testroom set." in testbot.exec_command(
"!room topic testroom 'Errbot rocks!'"
)
assert "Topic for testroom: Errbot rocks!" in testbot.exec_command(
"!room topic testroom"
)
| 4,368
|
Python
|
.py
| 118
| 31.949153
| 87
| 0.692216
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,087
|
core_plugins_test.py
|
errbotio_errbot/tests/core_plugins_test.py
|
import os
extra_plugin_dir = os.path.join(
os.path.dirname(os.path.realpath(__file__)), "room_plugin"
)
extra_config = {
"CORE_PLUGINS": ("Help", "Utils", "CommandNotFoundFilter"),
"BOT_ALT_PREFIXES": ("!",),
"BOT_PREFIX": "$",
}
def test_help_is_still_here(testbot):
assert "All commands" in testbot.exec_command("!help")
def test_backup_help_not_here(testbot):
assert "That command is not defined." in testbot.exec_command("!help backup")
def test_backup_should_not_be_there(testbot):
assert 'Command "backup" not found.' in testbot.exec_command("!backup")
def test_echo_still_here(testbot):
assert "toto" in testbot.exec_command("!echo toto")
def test_bot_prefix_replaced(testbot):
assert "$help - Returns a help string" in testbot.exec_command("$help")
| 804
|
Python
|
.py
| 19
| 38.842105
| 81
| 0.704134
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,088
|
link_test.py
|
errbotio_errbot/tests/link_test.py
|
# coding=utf-8
from os import path
extra_plugin_dir = path.join(path.dirname(path.realpath(__file__)), "test_link")
def test_linked_plugin_here(testbot):
testbot.push_message("!status plugins")
assert "Dummy" in testbot.pop_message()
| 246
|
Python
|
.py
| 6
| 38
| 80
| 0.737288
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,089
|
dependencies_test.py
|
errbotio_errbot/tests/dependencies_test.py
|
import os
extra_plugin_dir = os.path.join(
os.path.dirname(os.path.realpath(__file__)), "dependent_plugins"
)
def test_if_all_loaded_by_default(testbot):
plug_names = testbot.bot.plugin_manager.get_all_active_plugin_names()
assert "Single" in plug_names
assert "Parent1" in plug_names
assert "Parent2" in plug_names
def test_single_dependency(testbot):
pm = testbot.bot.plugin_manager
for p in ("Single", "Parent1", "Parent2"):
pm.deactivate_plugin(p)
# everything should be gone
plug_names = pm.get_all_active_plugin_names()
assert "Single" not in plug_names
assert "Parent1" not in plug_names
assert "Parent2" not in plug_names
pm.activate_plugin("Single")
# it should have activated the dependent plugin 'Parent1' only
plug_names = pm.get_all_active_plugin_names()
assert "Single" in plug_names
assert "Parent1" in plug_names
assert "Parent2" not in plug_names
def test_double_dependency(testbot):
pm = testbot.bot.plugin_manager
all = ("Double", "Parent1", "Parent2")
for p in all:
pm.deactivate_plugin(p)
pm.activate_plugin("Double")
plug_names = pm.get_all_active_plugin_names()
for p in all:
assert p in plug_names
def test_dependency_retrieval(testbot):
assert "youpi" in testbot.exec_command("!depfunc")
def test_direct_circular_dependency(testbot):
plug_names = testbot.bot.plugin_manager.get_all_active_plugin_names()
assert "Circular1" not in plug_names
def test_indirect_circular_dependency(testbot):
plug_names = testbot.bot.plugin_manager.get_all_active_plugin_names()
assert "Circular2" not in plug_names
assert "Circular3" not in plug_names
assert "Circular4" not in plug_names
def test_chained_dependency(testbot):
plug_names = testbot.bot.plugin_manager.get_all_active_plugin_names()
assert "Chained1" in plug_names
assert "Chained2" in plug_names
assert "Chained3" in plug_names
| 1,982
|
Python
|
.py
| 48
| 36.479167
| 73
| 0.720627
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,090
|
flow_test.py
|
errbotio_errbot/tests/flow_test.py
|
import logging
import pytest
from errbot.backends.test import TestPerson
from errbot.flow import Flow, FlowRoot, InvalidState
log = logging.getLogger(__name__)
def test_node():
root = FlowRoot("test", "This is my flowroot")
node = root.connect("a", lambda ctx: ctx["toto"] == "titui")
assert root.predicate_for_node(node)({"toto": "titui"})
assert not root.predicate_for_node(node)({"toto": "blah"})
def test_flow_predicate():
root = FlowRoot("test", "This is my flowroot")
node = root.connect("a", lambda ctx: "toto" in ctx and ctx["toto"] == "titui")
somebody = TestPerson("me")
# Non-matching predicate
flow = Flow(root, somebody, {})
assert node in flow.next_steps()
assert node not in flow.next_autosteps()
with pytest.raises(InvalidState):
flow.advance(node)
flow.advance(node, enforce_predicate=False) # This will bypass the restriction
assert flow._current_step == node
# Matching predicate
flow = Flow(root, somebody, {"toto": "titui"})
assert node in flow.next_steps()
assert node in flow.next_autosteps()
flow.advance(node)
assert flow._current_step == node
def test_autotrigger():
root = FlowRoot("test", "This is my flowroot")
node = root.connect(
"a", lambda ctx: "toto" in ctx and ctx["toto"] == "titui", auto_trigger=True
)
assert node.command in root.auto_triggers
| 1,408
|
Python
|
.py
| 34
| 36.735294
| 84
| 0.682586
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,091
|
templates_test.py
|
errbotio_errbot/tests/templates_test.py
|
from os import path
# This is to test end2end i18n behavior.
extra_plugin_dir = path.join(path.dirname(path.realpath(__file__)), "template_plugin")
def test_templates_1(testbot):
assert "ok" in testbot.exec_command("!test template1")
def test_templates_2(testbot):
assert "ok" in testbot.exec_command("!test template2")
def test_templates_3(testbot):
assert "ok" in testbot.exec_command("!test template3")
def test_templates_4(testbot):
assert "ok" in testbot.exec_command("!test template4 ok")
def test_templates_5(testbot):
assert "the following arguments are required: my_var" in testbot.exec_command(
"!test template4"
)
| 669
|
Python
|
.py
| 15
| 40.666667
| 86
| 0.735202
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,092
|
persistence_test.py
|
errbotio_errbot/tests/persistence_test.py
|
from errbot.storage import StoreMixin
from errbot.storage.memory import MemoryStoragePlugin
def test_simple_store_retreive():
sm = StoreMixin()
sm.open_storage(MemoryStoragePlugin(None), "ns")
sm["toto"] = "titui"
assert sm["toto"] == "titui"
def test_mutable():
sm = StoreMixin()
sm.open_storage(MemoryStoragePlugin(None), "ns")
sm["toto"] = [1, 3]
with sm.mutable("toto") as titi:
titi[1] = 5
assert sm["toto"] == [1, 5]
| 473
|
Python
|
.py
| 14
| 29.214286
| 53
| 0.662252
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,093
|
plugin_management_test.py
|
errbotio_errbot/tests/plugin_management_test.py
|
import os
import tempfile
from configparser import ConfigParser
from pathlib import Path
import pytest
import errbot.repo_manager
from errbot import plugin_manager
from errbot.plugin_info import PluginInfo
from errbot.plugin_manager import IncompatiblePluginException
from errbot.utils import collect_roots, entry_point_plugins, find_roots
CORE_PLUGINS = plugin_manager.CORE_PLUGINS
def touch(name):
with open(name, "a"):
os.utime(name, None)
assets = Path(__file__).parent / "assets"
def test_check_dependencies():
response, deps = errbot.repo_manager.check_dependencies(
assets / "requirements_never_there.txt"
)
assert "You need these dependencies for" in response
assert "impossible_requirement" in response
assert ["impossible_requirement"] == deps
def test_check_dependencies_no_requirements_file():
response, deps = errbot.repo_manager.check_dependencies(
assets / "requirements_non_existent.txt"
)
assert response is None
def test_check_dependencies_requirements_file_all_installed():
response, deps = errbot.repo_manager.check_dependencies(
assets / "requirements_already_there.txt"
)
assert response is None
def test_find_plugin_roots():
root = tempfile.mkdtemp()
a = os.path.join(root, "a")
b = os.path.join(a, "b")
c = os.path.join(root, "c")
os.mkdir(a)
os.mkdir(b)
os.mkdir(c)
touch(os.path.join(a, "toto.plug"))
touch(os.path.join(b, "titi.plug"))
touch(os.path.join(root, "tutu.plug"))
roots = find_roots(root)
assert root in roots
assert a in roots
assert b in roots
assert c not in roots
def test_collect_roots():
toto = tempfile.mkdtemp()
touch(os.path.join(toto, "toto.plug"))
touch(os.path.join(toto, "titi.plug"))
titi = tempfile.mkdtemp()
touch(os.path.join(titi, "tata.plug"))
tutu = tempfile.mkdtemp()
subtutu = os.path.join(tutu, "subtutu")
os.mkdir(subtutu)
touch(os.path.join(subtutu, "tutu.plug"))
assert collect_roots((CORE_PLUGINS, None)) == [CORE_PLUGINS]
assert collect_roots((CORE_PLUGINS, toto)) == [CORE_PLUGINS, toto]
assert collect_roots((CORE_PLUGINS, [toto, titi])) == [CORE_PLUGINS, toto, titi]
assert collect_roots((CORE_PLUGINS, toto, titi, "nothing")) == [
CORE_PLUGINS,
toto,
titi,
]
assert collect_roots((toto, tutu)) == [toto, subtutu]
def test_ignore_dotted_directories():
root = tempfile.mkdtemp()
a = os.path.join(root, ".invisible")
os.mkdir(a)
touch(os.path.join(a, "toto.plug"))
assert collect_roots((CORE_PLUGINS, root)) == [CORE_PLUGINS]
def dummy_config_parser() -> ConfigParser:
cp = ConfigParser()
cp.add_section("Core")
cp.set("Core", "Name", "dummy")
cp.set("Core", "Module", "dummy")
cp.add_section("Errbot")
return cp
def test_errbot_version_check():
real_version = plugin_manager.VERSION
too_high_min_1 = dummy_config_parser()
too_high_min_1.set("Errbot", "Min", "1.6.0")
too_high_min_2 = dummy_config_parser()
too_high_min_2.set("Errbot", "Min", "1.6.0")
too_high_min_2.set("Errbot", "Max", "2.0.0")
too_low_max_1 = dummy_config_parser()
too_low_max_1.set("Errbot", "Max", "1.0.1-beta")
too_low_max_2 = dummy_config_parser()
too_low_max_2.set("Errbot", "Min", "0.9.0-rc2")
too_low_max_2.set("Errbot", "Max", "1.0.1-beta")
ok1 = dummy_config_parser() # empty section
ok2 = dummy_config_parser()
ok2.set("Errbot", "Min", "1.4.0")
ok3 = dummy_config_parser()
ok3.set("Errbot", "Max", "1.5.2")
ok4 = dummy_config_parser()
ok4.set("Errbot", "Min", "1.2.1")
ok4.set("Errbot", "Max", "1.6.1-rc1")
try:
plugin_manager.VERSION = "1.5.2"
for config in (too_high_min_1, too_high_min_2, too_low_max_1, too_low_max_2):
pi = PluginInfo.parse(config)
with pytest.raises(IncompatiblePluginException):
plugin_manager.check_errbot_version(pi)
for config in (ok1, ok2, ok3, ok4):
pi = PluginInfo.parse(config)
plugin_manager.check_errbot_version(pi)
finally:
plugin_manager.VERSION = real_version
def test_entry_point_plugin():
no_plugins_found = entry_point_plugins("errbot.no_plugins")
assert [] == no_plugins_found
| 4,356
|
Python
|
.py
| 114
| 32.894737
| 85
| 0.664289
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,094
|
simple_identifiers_test.py
|
errbotio_errbot/tests/simple_identifiers_test.py
|
from errbot.backends.test import TestOccupant, TestPerson
def test_identifier_eq():
a = TestPerson("foo")
b = TestPerson("foo")
assert a == b
def test_identifier_ineq():
a = TestPerson("foo")
b = TestPerson("bar")
assert not a == b
assert a != b
def test_mucidentifier_eq():
a = TestOccupant("foo", "room")
b = TestOccupant("foo", "room")
assert a == b
def test_mucidentifier_ineq1():
a = TestOccupant("foo", "room")
b = TestOccupant("bar", "room")
assert not a == b
assert a != b
def test_mucidentifier_ineq2():
a = TestOccupant("foo", "room1")
b = TestOccupant("foo", "room2")
assert not a == b
assert a != b
| 693
|
Python
|
.py
| 24
| 24.458333
| 57
| 0.626707
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,095
|
multi_plugin_test.py
|
errbotio_errbot/tests/multi_plugin_test.py
|
from os import path
extra_plugin_dir = path.join(path.dirname(path.realpath(__file__)), "multi_plugin")
# This tests the decorellation between plugin class names and real names
# by making 2 instances of the same plugin collide on purpose.
def test_first(testbot):
r = testbot.exec_command("!myname")
assert "Multi1" == r or "Multi2" == r
def test_second(testbot):
assert "Multi2" == testbot.exec_command(
"!multi2-myname"
) or "Multi1" == testbot.exec_command("!multi1-myname")
| 509
|
Python
|
.py
| 11
| 42.545455
| 83
| 0.713415
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,096
|
backend_manager_test.py
|
errbotio_errbot/tests/backend_manager_test.py
|
import logging
import pytest
from errbot.backend_plugin_manager import BackendPluginManager
from errbot.bootstrap import CORE_BACKENDS
from errbot.core import ErrBot
logging.basicConfig(level=logging.DEBUG)
backends_to_check = ["Text", "Test", "Null"]
@pytest.mark.parametrize("backend_name", backends_to_check)
def test_builtins(backend_name):
bpm = BackendPluginManager(
{}, "errbot.backends", backend_name, ErrBot, CORE_BACKENDS
)
assert bpm.plugin_info.name == backend_name
| 504
|
Python
|
.py
| 13
| 35.769231
| 66
| 0.781443
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,097
|
base_backend_test.py
|
errbotio_errbot/tests/base_backend_test.py
|
# coding=utf-8
import logging
import os # noqa
import re # noqa
import sys
from collections import OrderedDict
from os.path import sep
from pathlib import Path
from queue import Empty, Queue # noqa
from tempfile import mkdtemp
import pytest
from errbot import arg_botcmd, botcmd, re_botcmd, templating # noqa
from errbot.backend_plugin_manager import BackendPluginManager
from errbot.backends.base import ONLINE, Identifier, Message, Room
from errbot.backends.test import (
ShallowConfig,
TestOccupant,
TestPerson,
TestRoom,
TestRoomAcl,
)
from errbot.bootstrap import CORE_STORAGE, bot_config_defaults
from errbot.core import ErrBot
from errbot.core_plugins.acls import ACLS
from errbot.plugin_manager import BotPluginManager
from errbot.rendering import text
from errbot.repo_manager import BotRepoManager
from errbot.storage.base import StoragePluginBase
from errbot.utils import PLUGINS_SUBDIR
LONG_TEXT_STRING = (
"This is a relatively long line of output, but I am repeated multiple times.\n"
)
logging.basicConfig(level=logging.DEBUG)
SIMPLE_JSON_PLUGINS_INDEX = """
{"errbotio/err-helloworld":
{"HelloWorld":
{"path": "/helloWorld.plug",
"documentation": "let's say hello!",
"avatar_url": "https://avatars.githubusercontent.com/u/15802630?v=3",
"name": "HelloWorld",
"python": "2+",
"repo": "https://github.com/errbotio/err-helloworld"
}
}
}
"""
class DummyBackend(ErrBot):
def change_presence(self, status: str = ONLINE, message: str = "") -> None:
pass
def prefix_groupchat_reply(self, message: Message, identifier: Identifier):
pass
def query_room(self, room: str) -> Room:
pass
def __init__(self, extra_config=None):
self.outgoing_message_queue = Queue()
if extra_config is None:
extra_config = {}
# make up a config.
tempdir = mkdtemp()
# reset the config every time
sys.modules.pop("errbot.config-template", None)
__import__("errbot.config-template")
config = ShallowConfig()
config.__dict__.update(sys.modules["errbot.config-template"].__dict__)
bot_config_defaults(config)
# It injects itself as a plugin. Changed the name to be sure we distinguish it.
self.name = "DummyBackendRealName"
config.BOT_DATA_DIR = tempdir
config.BOT_LOG_FILE = tempdir + sep + "log.txt"
config.BOT_PLUGIN_INDEXES = tempdir + sep + "repos.json"
config.BOT_EXTRA_PLUGIN_DIR = []
config.BOT_LOG_LEVEL = logging.DEBUG
config.BOT_IDENTITY = {"username": "err@localhost"}
config.BOT_ASYNC = False
config.BOT_PREFIX = "!"
config.CHATROOM_FN = "blah"
# Writeout the made up repos file
with open(config.BOT_PLUGIN_INDEXES, "w") as index_file:
index_file.write(SIMPLE_JSON_PLUGINS_INDEX)
for key in extra_config:
setattr(config, key, extra_config[key])
super().__init__(config)
self.bot_identifier = self.build_identifier("err")
self.md = text() # We just want simple text for testing purposes
# setup a memory based storage
spm = BackendPluginManager(
config, "errbot.storage", "Memory", StoragePluginBase, CORE_STORAGE
)
storage_plugin = spm.load_plugin()
# setup the plugin_manager just internally
botplugins_dir = os.path.join(config.BOT_DATA_DIR, PLUGINS_SUBDIR)
if not os.path.exists(botplugins_dir):
os.makedirs(botplugins_dir, mode=0o755)
# get it back from where we publish it.
repo_index_paths = (
os.path.join(
os.path.dirname(__file__), "..", "docs", "_extra", "repos.json"
),
)
repo_manager = BotRepoManager(storage_plugin, botplugins_dir, repo_index_paths)
self.attach_storage_plugin(storage_plugin)
self.attach_repo_manager(repo_manager)
self.attach_plugin_manager(
BotPluginManager(
storage_plugin,
config.BOT_EXTRA_PLUGIN_DIR,
config.AUTOINSTALL_DEPS,
getattr(config, "CORE_PLUGINS", None),
lambda name, clazz: clazz(self, name),
getattr(config, "PLUGINS_CALLBACK_ORDER", (None,)),
)
)
self.inject_commands_from(self)
self.inject_command_filters_from(ACLS(self))
def build_identifier(self, text_representation):
return TestPerson(text_representation)
def build_reply(self, msg, text=None, private=False, threaded=False):
reply = self.build_message(text)
reply.frm = self.bot_identifier
reply.to = msg.frm
if threaded:
reply.parent = msg
return reply
def send_message(self, msg):
msg._body = self.md.convert(msg.body)
self.outgoing_message_queue.put(msg)
def pop_message(self, timeout=3, block=True):
return self.outgoing_message_queue.get(timeout=timeout, block=block)
@botcmd
def command(self, msg, args):
return "Regular command"
@botcmd(admin_only=True)
def admin_command(self, msg, args):
return "Admin command"
@re_botcmd(pattern=r"^regex command with prefix$", prefixed=True)
def regex_command_with_prefix(self, msg, match):
return "Regex command"
@re_botcmd(pattern=r"^regex command without prefix$", prefixed=False)
def regex_command_without_prefix(self, msg, match):
return "Regex command"
@re_botcmd(
pattern=r"regex command with capture group: (?P<capture>.*)", prefixed=False
)
def regex_command_with_capture_group(self, msg, match):
return match.group("capture")
@re_botcmd(pattern=r"matched by two commands")
def double_regex_command_one(self, msg, match):
return "one"
@re_botcmd(pattern=r"matched by two commands", flags=re.IGNORECASE)
def double_regex_command_two(self, msg, match):
return "two"
@re_botcmd(pattern=r"match_here", matchall=True)
def regex_command_with_matchall(self, msg, matches):
return len(matches)
@botcmd
def return_args_as_str(self, msg, args):
return "".join(args)
@botcmd(template="args_as_md")
def return_args_as_md(self, msg, args):
return {"args": args}
@botcmd
def send_args_as_md(self, msg, args):
self.send_templated(msg.frm, "args_as_md", {"args": args})
@botcmd
def raises_exception(self, msg, args):
raise Exception("Kaboom!")
@botcmd
def yield_args_as_str(self, msg, args):
for arg in args:
yield arg
@botcmd(template="args_as_md")
def yield_args_as_md(self, msg, args):
for arg in args:
yield {"args": [arg]}
@botcmd
def yields_str_then_raises_exception(self, msg, args):
yield "foobar"
raise Exception("Kaboom!")
@botcmd
def return_long_output(self, msg, args):
return LONG_TEXT_STRING * 3
@botcmd
def yield_long_output(self, msg, args):
for i in range(2):
yield LONG_TEXT_STRING * 3
##
# arg_botcmd test commands
##
@arg_botcmd("--first-name", dest="first_name")
@arg_botcmd("--last-name", dest="last_name")
def yields_first_name_last_name(self, msg, first_name=None, last_name=None):
yield "%s %s" % (first_name, last_name)
@arg_botcmd("--first-name", dest="first_name")
@arg_botcmd("--last-name", dest="last_name")
def returns_first_name_last_name(self, msg, first_name=None, last_name=None):
return "%s %s" % (first_name, last_name)
@arg_botcmd("--first-name", dest="first_name")
@arg_botcmd("--last-name", dest="last_name", unpack_args=False)
def returns_first_name_last_name_without_unpacking(self, msg, args):
return "%s %s" % (args.first_name, args.last_name)
@arg_botcmd("value", type=str)
@arg_botcmd("--count", dest="count", type=int)
def returns_value_repeated_count_times(self, msg, value=None, count=None):
# str * int gives a repeated string
return value * count
@property
def mode(self):
return "Dummy"
@property
def rooms(self):
return []
@pytest.fixture
def dummy_backend():
return DummyBackend()
def test_buildreply(dummy_backend):
m = dummy_backend.build_message("Content")
m.frm = dummy_backend.build_identifier("user")
m.to = dummy_backend.build_identifier("somewhere")
resp = dummy_backend.build_reply(m, "Response")
assert str(resp.to) == "user"
assert str(resp.frm) == "err"
assert str(resp.body) == "Response"
assert resp.parent is None
def test_buildreply_with_parent(dummy_backend):
m = dummy_backend.build_message("Content")
m.frm = dummy_backend.build_identifier("user")
m.to = dummy_backend.build_identifier("somewhere")
resp = dummy_backend.build_reply(m, "Response", threaded=True)
assert resp.parent is not None
def test_all_command_private():
dummy_backend = DummyBackend(extra_config={"DIVERT_TO_PRIVATE": ("ALL_COMMANDS",)})
m = dummy_backend.build_message("Content")
m.frm = dummy_backend.build_identifier("user")
m.to = dummy_backend.build_identifier("somewhere")
resp = dummy_backend.build_reply(m, "Response", threaded=True)
assert "ALL_COMMANDS" in dummy_backend.bot_config.DIVERT_TO_PRIVATE
assert resp is not None
def test_bot_admins_unique_string():
dummy = DummyBackend(extra_config={"BOT_ADMINS": "err@localhost"})
assert dummy.bot_config.BOT_ADMINS == ("err@localhost",)
@pytest.fixture
def dummy_execute_and_send():
dummy = DummyBackend()
example_message = dummy.build_message("some_message")
example_message.frm = dummy.build_identifier("noterr")
example_message.to = dummy.build_identifier("err")
assets_path = os.path.join(os.path.dirname(__file__), "assets")
templating.template_path.append(
str(templating.make_templates_path(Path(assets_path)))
)
templating.env = templating.Environment(
loader=templating.FileSystemLoader(templating.template_path)
)
return dummy, example_message
def test_commands_can_return_string(dummy_execute_and_send):
dummy, m = dummy_execute_and_send
dummy._execute_and_send(
cmd="return_args_as_str",
args=["foo", "bar"],
match=None,
msg=m,
template_name=dummy.return_args_as_str._err_command_template,
)
assert "foobar" == dummy.pop_message().body
def test_commands_can_return_md(dummy_execute_and_send):
dummy, m = dummy_execute_and_send
dummy._execute_and_send(
cmd="return_args_as_md",
args=["foo", "bar"],
match=None,
msg=m,
template_name=dummy.return_args_as_md._err_command_template,
)
response = dummy.pop_message()
assert "foobar" == response.body
def test_commands_can_send_templated(dummy_execute_and_send):
dummy, m = dummy_execute_and_send
dummy._execute_and_send(
cmd="send_args_as_md",
args=["foo", "bar"],
match=None,
msg=m,
template_name=dummy.return_args_as_md._err_command_template,
)
response = dummy.pop_message()
assert "foobar" == response.body
def test_exception_is_caught_and_shows_error_message(dummy_execute_and_send):
dummy, m = dummy_execute_and_send
dummy._execute_and_send(
cmd="raises_exception",
args=[],
match=None,
msg=m,
template_name=dummy.raises_exception._err_command_template,
)
assert dummy.MSG_ERROR_OCCURRED in dummy.pop_message().body
dummy._execute_and_send(
cmd="yields_str_then_raises_exception",
args=[],
match=None,
msg=m,
template_name=dummy.yields_str_then_raises_exception._err_command_template,
)
assert "foobar" == dummy.pop_message().body
assert dummy.MSG_ERROR_OCCURRED in dummy.pop_message().body
def test_commands_can_yield_strings(dummy_execute_and_send):
dummy, m = dummy_execute_and_send
dummy._execute_and_send(
cmd="yield_args_as_str",
args=["foo", "bar"],
match=None,
msg=m,
template_name=dummy.yield_args_as_str._err_command_template,
)
assert "foo" == dummy.pop_message().body
assert "bar" == dummy.pop_message().body
def test_commands_can_yield_md(dummy_execute_and_send):
dummy, m = dummy_execute_and_send
dummy._execute_and_send(
cmd="yield_args_as_md",
args=["foo", "bar"],
match=None,
msg=m,
template_name=dummy.yield_args_as_md._err_command_template,
)
assert "foo" == dummy.pop_message().body
assert "bar" == dummy.pop_message().body
def test_output_longer_than_max_msg_size_is_split_into_multiple_msgs_when_returned(
dummy_execute_and_send,
):
dummy, m = dummy_execute_and_send
dummy.bot_config.MESSAGE_SIZE_LIMIT = len(LONG_TEXT_STRING)
dummy._execute_and_send(
cmd="return_long_output",
args=["foo", "bar"],
match=None,
msg=m,
template_name=dummy.return_long_output._err_command_template,
)
for i in range(
3
): # return_long_output outputs a string that's 3x longer than the size limit
assert LONG_TEXT_STRING.strip() == dummy.pop_message().body
with pytest.raises(Empty):
dummy.pop_message(block=False)
def test_output_longer_than_max_msg_size_is_split_into_multiple_msgs_when_yielded(
dummy_execute_and_send,
):
dummy, m = dummy_execute_and_send
dummy.bot_config.MESSAGE_SIZE_LIMIT = len(LONG_TEXT_STRING)
dummy._execute_and_send(
cmd="yield_long_output",
args=["foo", "bar"],
match=None,
msg=m,
template_name=dummy.yield_long_output._err_command_template,
)
for i in range(
6
): # yields_long_output yields 2 strings that are 3x longer than the size limit
assert LONG_TEXT_STRING.strip() == dummy.pop_message().body
with pytest.raises(Empty):
dummy.pop_message(block=False)
def makemessage(dummy, message, from_=None, to=None):
if not from_:
from_ = dummy.build_identifier("noterr")
if not to:
to = dummy.build_identifier("noterr")
m = dummy.build_message(message)
m.frm = from_
m.to = to
return m
def test_inject_skips_methods_without_botcmd_decorator(dummy_backend):
assert "build_message" not in dummy_backend.commands
def test_inject_and_remove_botcmd(dummy_backend):
assert "command" in dummy_backend.commands
dummy_backend.remove_commands_from(dummy_backend)
assert len(dummy_backend.commands) == 0
def test_inject_and_remove_re_botcmd(dummy_backend):
assert "regex_command_with_prefix" in dummy_backend.re_commands
dummy_backend.remove_commands_from(dummy_backend)
assert len(dummy_backend.re_commands) == 0
def test_callback_message(dummy_backend):
dummy_backend.callback_message(
makemessage(dummy_backend, "!return_args_as_str one two")
)
assert "one two" == dummy_backend.pop_message().body
def test_callback_message_with_prefix_optional():
dummy = DummyBackend({"BOT_PREFIX_OPTIONAL_ON_CHAT": True})
m = makemessage(dummy, "return_args_as_str one two")
dummy.callback_message(m)
assert "one two" == dummy.pop_message().body
# Groupchat should still require the prefix
m.frm = TestOccupant("someone", "room")
room = TestRoom("room", bot=dummy)
m.to = room
dummy.callback_message(m)
with pytest.raises(Empty):
dummy.pop_message(block=False)
m = makemessage(
dummy,
"!return_args_as_str one two",
from_=TestOccupant("someone", "room"),
to=room,
)
dummy.callback_message(m)
assert "one two" == dummy.pop_message().body
def test_callback_message_with_bot_alt_prefixes():
dummy = DummyBackend(
{"BOT_ALT_PREFIXES": ("Err",), "BOT_ALT_PREFIX_SEPARATORS": (",", ";")}
)
dummy.callback_message(makemessage(dummy, "Err return_args_as_str one two"))
assert "one two" == dummy.pop_message().body
dummy.callback_message(makemessage(dummy, "Err, return_args_as_str one two"))
assert "one two" == dummy.pop_message().body
def test_callback_message_with_re_botcmd(dummy_backend):
dummy_backend.callback_message(
makemessage(dummy_backend, "!regex command with prefix")
)
assert "Regex command" == dummy_backend.pop_message().body
dummy_backend.callback_message(
makemessage(dummy_backend, "regex command without prefix")
)
assert "Regex command" == dummy_backend.pop_message().body
dummy_backend.callback_message(
makemessage(dummy_backend, "!regex command with capture group: Captured text")
)
assert "Captured text" == dummy_backend.pop_message().body
dummy_backend.callback_message(
makemessage(dummy_backend, "regex command with capture group: Captured text")
)
assert "Captured text" == dummy_backend.pop_message().body
dummy_backend.callback_message(
makemessage(
dummy_backend,
"This command also allows extra text in front - regex "
"command with capture group: Captured text",
)
)
assert "Captured text" == dummy_backend.pop_message().body
def test_callback_message_with_re_botcmd_and_alt_prefixes():
dummy_backend = DummyBackend(
{"BOT_ALT_PREFIXES": ("Err",), "BOT_ALT_PREFIX_SEPARATORS": (",", ";")}
)
dummy_backend.callback_message(
makemessage(dummy_backend, "!regex command with prefix")
)
assert "Regex command" == dummy_backend.pop_message().body
dummy_backend.callback_message(
makemessage(dummy_backend, "Err regex command with prefix")
)
assert "Regex command" == dummy_backend.pop_message().body
dummy_backend.callback_message(
makemessage(dummy_backend, "Err, regex command with prefix")
)
assert "Regex command" == dummy_backend.pop_message().body
dummy_backend.callback_message(
makemessage(dummy_backend, "regex command without prefix")
)
assert "Regex command" == dummy_backend.pop_message().body
dummy_backend.callback_message(
makemessage(dummy_backend, "!regex command with capture group: Captured text")
)
assert "Captured text" == dummy_backend.pop_message().body
dummy_backend.callback_message(
makemessage(dummy_backend, "regex command with capture group: Captured text")
)
assert "Captured text" == dummy_backend.pop_message().body
dummy_backend.callback_message(
makemessage(
dummy_backend,
"This command also allows extra text in front - "
"regex command with capture group: Captured text",
)
)
assert "Captured text" == dummy_backend.pop_message().body
dummy_backend.callback_message(
makemessage(
dummy_backend, "Err, regex command with capture group: Captured text"
)
)
assert "Captured text" == dummy_backend.pop_message().body
dummy_backend.callback_message(
makemessage(
dummy_backend,
"Err This command also allows extra text in front - "
"regex command with capture group: Captured text",
)
)
assert "Captured text" == dummy_backend.pop_message().body
dummy_backend.callback_message(makemessage(dummy_backend, "!match_here"))
assert "1" == dummy_backend.pop_message().body
dummy_backend.callback_message(
makemessage(dummy_backend, "!match_here match_here match_here")
)
assert "3" == dummy_backend.pop_message().body
def test_regex_commands_can_overlap(dummy_backend):
dummy_backend.callback_message(
makemessage(dummy_backend, "!matched by two commands")
)
response = (dummy_backend.pop_message().body, dummy_backend.pop_message().body)
assert response == ("one", "two") or response == ("two", "one")
def test_regex_commands_allow_passing_re_flags(dummy_backend):
dummy_backend.callback_message(
makemessage(dummy_backend, "!MaTcHeD By TwO cOmMaNdS")
)
assert "two" == dummy_backend.pop_message().body
with pytest.raises(Empty):
dummy_backend.pop_message(timeout=1)
def test_arg_botcmd_returns_first_name_last_name(dummy_backend):
dummy_backend.callback_message(
makemessage(
dummy_backend,
"!returns_first_name_last_name --first-name=Err --last-name=Bot",
)
)
assert "Err Bot"
def test_arg_botcmd_returns_with_escaping(dummy_backend):
first_name = 'Err\\"'
last_name = "Bot"
dummy_backend.callback_message(
makemessage(
dummy_backend,
"!returns_first_name_last_name --first-name=%s --last-name=%s"
% (first_name, last_name),
)
)
assert 'Err" Bot' == dummy_backend.pop_message().body
def test_arg_botcmd_returns_with_incorrect_escaping(dummy_backend):
first_name = 'Err"'
last_name = "Bot"
dummy_backend.callback_message(
makemessage(
dummy_backend,
"!returns_first_name_last_name --first-name=%s --last-name=%s"
% (first_name, last_name),
)
)
assert (
"I couldn't parse this command; No closing quotation"
in dummy_backend.pop_message().body
)
def test_arg_botcmd_yields_first_name_last_name(dummy_backend):
dummy_backend.callback_message(
makemessage(
dummy_backend,
"!yields_first_name_last_name --first-name=Err --last-name=Bot",
)
)
assert "Err Bot" == dummy_backend.pop_message().body
def test_arg_botcmd_returns_value_repeated_count_times(dummy_backend):
dummy_backend.callback_message(
makemessage(dummy_backend, "!returns_value_repeated_count_times Foo --count 5")
)
assert "FooFooFooFooFoo" == dummy_backend.pop_message().body
def test_arg_botcmd_doesnt_raise_systemerror(dummy_backend):
dummy_backend.callback_message(
makemessage(dummy_backend, "!returns_first_name_last_name --invalid-parameter")
)
def test_arg_botcdm_returns_errors_as_chat(dummy_backend):
dummy_backend.callback_message(
makemessage(dummy_backend, "!returns_first_name_last_name --invalid-parameter")
)
assert (
"I couldn't parse the arguments; unrecognized arguments: --invalid-parameter"
in dummy_backend.pop_message().body
)
def test_arg_botcmd_returns_help_message_as_chat(dummy_backend):
dummy_backend.callback_message(
makemessage(dummy_backend, "!returns_first_name_last_name --help")
)
assert (
"usage: returns_first_name_last_name [-h] [--last-name LAST_NAME]"
in dummy_backend.pop_message().body
)
def test_arg_botcmd_undoes_fancy_unicode_dash_conversion(dummy_backend):
dummy_backend.callback_message(
makemessage(
dummy_backend,
"!returns_first_name_last_name —first-name=Err —last-name=Bot",
)
)
assert "Err Bot" == dummy_backend.pop_message().body
def test_arg_botcmd_without_argument_unpacking(dummy_backend):
dummy_backend.callback_message(
makemessage(
dummy_backend,
"!returns_first_name_last_name_without_unpacking --first-name=Err --last-name=Bot",
)
)
assert "Err Bot" == dummy_backend.pop_message().body
def test_access_controls(dummy_backend):
testroom = TestRoom("room", bot=dummy_backend)
tests = [
# BOT_ADMINS scenarios
dict(
message=makemessage(dummy_backend, "!admin_command"),
bot_admins=("noterr",),
expected_response="Admin command",
),
dict(
message=makemessage(dummy_backend, "!admin_command"),
bot_admins=(),
expected_response="This command requires bot-admin privileges",
),
dict(
message=makemessage(dummy_backend, "!admin_command"),
bot_admins=("*err",),
expected_response="Admin command",
),
# admin_only commands SHOULD be private-message only by default
dict(
message=makemessage(
dummy_backend,
"!admin_command",
from_=TestOccupant("noterr", room=testroom),
to=testroom,
),
bot_admins=("noterr",),
expected_response="This command may only be issued through a direct message",
),
# But MAY be sent via groupchat IF 'allowmuc' is specifically set to True.
dict(
message=makemessage(
dummy_backend,
"!admin_command",
from_=TestOccupant("noterr", room=testroom),
to=testroom,
),
bot_admins=("noterr",),
acl={"admin_command": {"allowmuc": True}},
expected_response="Admin command",
),
# ACCESS_CONTROLS scenarios WITHOUT wildcards (<4.0 format)
dict(
message=makemessage(dummy_backend, "!command"),
expected_response="Regular command",
),
dict(
message=makemessage(dummy_backend, "!regex command with prefix"),
expected_response="Regex command",
),
dict(
message=makemessage(dummy_backend, "!command"),
acl_default={"allowmuc": False, "allowprivate": False},
expected_response="You're not allowed to access this command via private message to me",
),
dict(
message=makemessage(dummy_backend, "regex command without prefix"),
acl_default={"allowmuc": False, "allowprivate": False},
expected_response="You're not allowed to access this command via private message to me",
),
dict(
message=makemessage(dummy_backend, "!command"),
acl_default={"allowmuc": True, "allowprivate": False},
expected_response="You're not allowed to access this command via private message to me",
),
dict(
message=makemessage(dummy_backend, "!command"),
acl_default={"allowmuc": False, "allowprivate": True},
expected_response="Regular command",
),
dict(
message=makemessage(dummy_backend, "!command"),
acl={"command": {"allowprivate": False}},
acl_default={"allowmuc": False, "allowprivate": True},
expected_response="You're not allowed to access this command via private message to me",
),
dict(
message=makemessage(dummy_backend, "!command"),
acl={"command": {"allowmuc": True}},
acl_default={"allowmuc": True, "allowprivate": False},
expected_response="You're not allowed to access this command via private message to me",
),
dict(
message=makemessage(dummy_backend, "!command"),
acl={"command": {"allowprivate": True}},
acl_default={"allowmuc": False, "allowprivate": False},
expected_response="Regular command",
),
dict(
message=makemessage(
dummy_backend,
"!command",
from_=TestOccupant("someone", "room"),
to=TestRoom("room", bot=dummy_backend),
),
acl={"command": {"allowrooms": ("room",)}},
expected_response="Regular command",
),
dict(
message=makemessage(
dummy_backend,
"!command",
from_=TestOccupant("someone", "room"),
to=TestRoomAcl("room", bot=dummy_backend),
),
acl={"command": {"allowrooms": ("room",)}},
expected_response="Regular command",
),
dict(
message=makemessage(
dummy_backend,
"!command",
from_=TestOccupant("someone", "room_1"),
to=TestRoom("room1", bot=dummy_backend),
),
acl={"command": {"allowrooms": ("room_*",)}},
expected_response="Regular command",
),
dict(
message=makemessage(
dummy_backend,
"!command",
from_=TestOccupant("someone", "room"),
to=TestRoom("room", bot=dummy_backend),
),
acl={"command": {"allowrooms": ("anotherroom@localhost",)}},
expected_response="You're not allowed to access this command from this room",
),
dict(
message=makemessage(
dummy_backend,
"!command",
from_=TestOccupant("someone", "room"),
to=TestRoomAcl("room", bot=dummy_backend),
),
acl={"command": {"allowrooms": ("anotherroom@localhost",)}},
expected_response="You're not allowed to access this command from this room",
),
dict(
message=makemessage(
dummy_backend,
"!command",
from_=TestOccupant("someone", "room"),
to=TestRoom("room", bot=dummy_backend),
),
acl={"command": {"denyrooms": ("room",)}},
expected_response="You're not allowed to access this command from this room",
),
dict(
message=makemessage(
dummy_backend,
"!command",
from_=TestOccupant("someone", "room"),
to=TestRoom("room", bot=dummy_backend),
),
acl={"command": {"denyrooms": ("*",)}},
expected_response="You're not allowed to access this command from this room",
),
dict(
message=makemessage(
dummy_backend,
"!command",
from_=TestOccupant("someone", "room"),
to=TestRoom("room", bot=dummy_backend),
),
acl={"command": {"denyrooms": ("anotherroom",)}},
expected_response="Regular command",
),
dict(
message=makemessage(dummy_backend, "!command"),
acl={"command": {"allowusers": ("noterr",)}},
expected_response="Regular command",
),
dict(
message=makemessage(dummy_backend, "!command"),
acl={"command": {"allowusers": "noterr"}}, # simple string instead of tuple
expected_response="Regular command",
),
dict(
message=makemessage(dummy_backend, "!command"),
acl={"command": {"allowusers": ("err",)}},
expected_response="You're not allowed to access this command from this user",
),
dict(
message=makemessage(dummy_backend, "!command"),
acl={"command": {"allowusers": ("*err",)}},
expected_response="Regular command",
),
dict(
message=makemessage(dummy_backend, "!command"),
acl={"command": {"denyusers": ("err",)}},
expected_response="Regular command",
),
dict(
message=makemessage(dummy_backend, "!command"),
acl={"command": {"denyusers": ("noterr",)}},
expected_response="You're not allowed to access this command from this user",
),
dict(
message=makemessage(dummy_backend, "!command"),
acl={"command": {"denyusers": "noterr"}}, # simple string instead of tuple
expected_response="You're not allowed to access this command from this user",
),
dict(
message=makemessage(dummy_backend, "!command"),
acl={"command": {"denyusers": ("*err",)}},
expected_response="You're not allowed to access this command from this user",
),
dict(
message=makemessage(dummy_backend, "!command echo"),
acl={"command": {"allowargs": ("echo",)}},
expected_response="Regular command",
),
dict(
message=makemessage(dummy_backend, "!command notallowed"),
acl={"command": {"allowargs": ("echo",)}},
expected_response="You're not allowed to access this command using the provided arguments",
),
dict(
message=makemessage(dummy_backend, "!command echodeny"),
acl={"command": {"denyargs": ("echodeny",)}},
expected_response="You're not allowed to access this command using the provided arguments",
),
dict(
message=makemessage(dummy_backend, "!command echo"),
acl={"command": {"denyargs": ("echodeny",)}},
expected_response="Regular command",
),
# ACCESS_CONTROLS scenarios WITH wildcards (>=4.0 format)
dict(
message=makemessage(dummy_backend, "!command"),
acl={"DummyBackendRealName:command": {"denyusers": ("noterr",)}},
expected_response="You're not allowed to access this command from this user",
),
dict(
message=makemessage(dummy_backend, "!command"),
acl={"*:command": {"denyusers": ("noterr",)}},
expected_response="You're not allowed to access this command from this user",
),
dict(
message=makemessage(dummy_backend, "!command"),
acl={"DummyBackendRealName:*": {"denyusers": ("noterr",)}},
expected_response="You're not allowed to access this command from this user",
),
dict(
message=makemessage(dummy_backend, "!command echo"),
acl={"command": {"allowargs": ("ec*",)}},
expected_response="Regular command",
),
dict(
message=makemessage(dummy_backend, "!command notallowed"),
acl={"command": {"allowargs": ("e*",)}},
expected_response="You're not allowed to access this command using the provided arguments",
),
dict(
message=makemessage(dummy_backend, "!command denied"),
acl={"command": {"denyargs": ("den*",)}},
expected_response="You're not allowed to access this command using the provided arguments",
),
# Overlapping globs should use first match
dict(
message=makemessage(dummy_backend, "!command"),
acl=OrderedDict(
[
("DummyBackendRealName:*", {"denyusers": ("noterr",)}),
("DummyBackendRealName:command", {"denyusers": ()}),
]
),
expected_response="You're not allowed to access this command from this user",
),
# ACCESS_CONTROLS with numeric username as in telegram
dict(
message=makemessage(
dummy_backend, "!command", from_=dummy_backend.build_identifier(1234)
),
acl={"command": {"allowusers": (1234,)}},
expected_response="Regular command",
),
]
for test in tests:
dummy_backend.bot_config.ACCESS_CONTROLS_DEFAULT = test.get("acl_default", {})
dummy_backend.bot_config.ACCESS_CONTROLS = test.get("acl", {})
dummy_backend.bot_config.BOT_ADMINS = test.get("bot_admins", ())
logger = logging.getLogger(__name__)
logger.info(f"** message: {test['message'].body}")
logger.info(f"** bot_admins: {dummy_backend.bot_config.BOT_ADMINS}")
logger.info(f"** acl: {dummy_backend.bot_config.ACCESS_CONTROLS}")
logger.info(
"** acl_default: {!r}".format(
dummy_backend.bot_config.ACCESS_CONTROLS_DEFAULT
)
)
dummy_backend.callback_message(test["message"])
assert test["expected_response"] == dummy_backend.pop_message().body
| 36,028
|
Python
|
.py
| 886
| 32.143341
| 103
| 0.622183
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,098
|
poller_test.py
|
errbotio_errbot/tests/poller_test.py
|
import time
from os import path
CURRENT_FILE_DIR = path.dirname(path.realpath(__file__))
extra_plugin_dir = path.join(CURRENT_FILE_DIR, "poller_plugin")
def test_delayed_hello(testbot):
assert "Hello, world!" in testbot.exec_command("!hello")
time.sleep(1)
delayed_msg = "Hello world! was sent 5 seconds ago"
assert delayed_msg in testbot.pop_message(timeout=1)
# Assert that only one message has been enqueued
assert testbot.bot.outgoing_message_queue.empty()
def test_delayed_hello_loop(testbot):
assert "Hello, world!" in testbot.exec_command("!hello_loop")
time.sleep(1)
delayed_msg = "Hello world! was sent 5 seconds ago"
assert delayed_msg in testbot.pop_message(timeout=1)
# Assert that only one message has been enqueued
assert testbot.bot.outgoing_message_queue.empty()
| 832
|
Python
|
.py
| 18
| 42.277778
| 65
| 0.74042
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,099
|
repo_manager_test.py
|
errbotio_errbot/tests/repo_manager_test.py
|
import os
import shutil
import tempfile
import pytest
from errbot import repo_manager
from errbot.storage.memory import MemoryStoragePlugin
assets = os.path.join(os.path.dirname(__file__), "assets")
@pytest.fixture
def plugdir_and_storage(request):
plugins_dir = tempfile.mkdtemp()
storage_plugin = MemoryStoragePlugin("repomgr")
def on_finish():
shutil.rmtree(plugins_dir)
request.addfinalizer(on_finish)
return plugins_dir, storage_plugin
def test_index_population(plugdir_and_storage):
plugdir, storage = plugdir_and_storage
manager = repo_manager.BotRepoManager(
storage, plugdir, (os.path.join(assets, "repos", "simple.json"),)
)
manager.index_update()
index_entry = manager[repo_manager.REPO_INDEX]
assert repo_manager.LAST_UPDATE in index_entry
assert "pluginname1" in index_entry["name1/err-reponame1"]
assert "pluginname2" in index_entry["name2/err-reponame2"]
def test_index_merge(plugdir_and_storage):
plugdir, storage = plugdir_and_storage
manager = repo_manager.BotRepoManager(
storage,
plugdir,
(
os.path.join(assets, "repos", "b.json"),
os.path.join(assets, "repos", "a.json"),
),
)
manager.index_update()
index_entry = manager[repo_manager.REPO_INDEX]
# First they should be all here
assert "pluginname1" in index_entry["name1/err-reponame1"]
assert "pluginname2" in index_entry["name2/err-reponame2"]
assert "pluginname3" in index_entry["name3/err-reponame3"]
# then it must be the correct one of the overriden one
assert index_entry["name2/err-reponame2"]["pluginname2"]["name"] == "NewPluginName2"
def test_reverse_merge(plugdir_and_storage):
plugdir, storage = plugdir_and_storage
manager = repo_manager.BotRepoManager(
storage,
plugdir,
(
os.path.join(assets, "repos", "a.json"),
os.path.join(assets, "repos", "b.json"),
),
)
manager.index_update()
index_entry = manager[repo_manager.REPO_INDEX]
assert (
not index_entry["name2/err-reponame2"]["pluginname2"]["name"]
== "NewPluginName2"
)
def test_no_update_if_one_fails(plugdir_and_storage):
plugdir, storage = plugdir_and_storage
manager = repo_manager.BotRepoManager(
storage,
plugdir,
(
os.path.join(assets, "repos", "a.json"),
os.path.join(assets, "repos", "doh.json"),
),
)
manager.index_update()
assert repo_manager.REPO_INDEX not in manager
def test_tokenization():
e = {
"python": "2+",
"repo": "https://github.com/name/err-reponame1",
"path": "/plugin1.plug",
"avatar_url": "https://avatars.githubusercontent.com/u/588833?v=3",
"name": "PluginName1",
"documentation": "docs1",
}
words = {
"https",
"com",
"name",
"err",
"docs1",
"reponame1",
"plug",
"2",
"plugin1",
"avatars",
"github",
"githubusercontent",
"u",
"v",
"3",
"588833",
"pluginname1",
}
assert repo_manager.tokenizeJsonEntry(e) == words
def test_search(plugdir_and_storage):
plugdir, storage = plugdir_and_storage
manager = repo_manager.BotRepoManager(
storage, plugdir, (os.path.join(assets, "repos", "simple.json"),)
)
a = [p for p in manager.search_repos("docs2")]
assert len(a) == 1
assert a[0].name == "pluginname2"
a = [p for p in manager.search_repos("zorg")]
assert len(a) == 0
a = [p for p in manager.search_repos("plug")]
assert len(a) == 2
def test_git_url_name_guessing():
assert (
repo_manager.human_name_for_git_url(
"https://github.com/errbotio/err-imagebot.git"
)
== "errbotio/err-imagebot"
)
| 3,924
|
Python
|
.py
| 119
| 26.336134
| 88
| 0.630366
|
errbotio/errbot
| 3,120
| 612
| 59
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|